@mcptoolshop/research-os 0.3.0 → 0.3.1

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/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/intake/schema.ts","../src/intake/scaffold.ts","../src/intake/index.ts","../src/sections/schema.ts","../src/sections/scaffold.ts","../src/sections/index.ts","../src/sources/fetch.ts","../src/sources/url-input.ts","../src/sources/extractors/heuristic.ts","../src/sources/extractors/ollama-intern.ts","../src/sources/extractors/index.ts","../src/sources/schema.ts","../src/sources/cards.ts","../src/sources/gather.ts","../src/sources/excerpts/schema.ts","../src/sources/excerpts/chunk.ts","../src/sources/excerpts/ledger.ts","../src/sources/excerpts/index.ts","../src/sources/index.ts","../src/claims/extractors/heuristic.ts","../src/claims/extractors/ollama-intern.ts","../src/claims/extractors/index.ts","../src/claims/schema.ts","../src/claims/extract.ts","../src/claims/density/schema.ts","../src/claims/density/run.ts","../src/claims/density/index.ts","../src/claims/index.ts","../src/contradictions/schema.ts","../src/contradictions/scope.ts","../src/contradictions/detectors/heuristic.ts","../src/contradictions/detectors/ollama-intern.ts","../src/contradictions/detectors/index.ts","../src/contradictions/markdown.ts","../src/triage/schema.ts","../src/triage/run.ts","../src/contradictions/map.ts","../src/contradictions/resolution-schema.ts","../src/contradictions/resolve.ts","../src/contradictions/index.ts","../src/review/schema.ts","../src/gates/checks/source-floor.ts","../src/gates/checks/claim-integrity.ts","../src/gates/checks/scope-integrity.ts","../src/gates/checks/freshness.ts","../src/gates/checks/contradiction.ts","../src/gates/checks/section-budget.ts","../src/gates/checks/waivers.ts","../src/gates/checks/accepted-claim-floor.ts","../src/gates/checks/index.ts","../src/gates/markdown.ts","../src/gates/schema.ts","../src/gates/run.ts","../src/gates/index.ts","../src/review/profiles.ts","../src/review/reviewers/heuristic.ts","../src/review/reviewers/ollama-intern.ts","../src/review/reviewers/index.ts","../src/review/decision.ts","../src/review/markdown.ts","../src/review/run.ts","../src/review/promote.ts","../src/review/index.ts","../src/indexer/schema.ts","../src/indexer/db.ts","../src/indexer/build.ts","../src/indexer/query.ts","../src/indexer/export.ts","../src/indexer/sync.ts","../src/indexer/index.ts","../src/dispositions/schema.ts","../src/cowork/derive.ts","../src/cowork/schema.ts","../src/cowork/markdown.ts","../src/cowork/run.ts","../src/cowork/index.ts","../src/synth/derive.ts","../src/synth/schema.ts","../src/synth/markdown.ts","../src/synth/run.ts","../src/synth/index.ts","../src/audit/aggregate.ts","../src/audit/schema.ts","../src/audit/markdown.ts","../src/audit/run.ts","../src/audit/index.ts","../src/freeze/checks.ts","../src/freeze/citations.ts","../src/freeze/markdown.ts","../src/freeze/schema.ts","../src/freeze/run.ts","../src/freeze/index.ts","../src/invalidate/schema.ts","../src/invalidate/run.ts","../src/invalidate/review.ts","../src/invalidate/index.ts","../src/triage/index.ts","../src/discover/schema.ts","../src/discover/providers/llm-heuristic.ts","../src/discover/run.ts","../src/discover/index.ts","../src/index.ts","../src/section_report/schema.ts","../src/section_report/run.ts","../src/section_report/index.ts","../src/cli.ts","../src/pack/publish/index.ts","../src/pack/publish/manifest.ts","../src/pack/publish/schema.ts","../src/pack/publish/readme.ts","../src/pack/publish/how-to-read.ts","../src/pack/publish/copy.ts","../src/pack/publish/verify.ts"],"sourcesContent":["export class ResearchOSError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n public readonly hint?: string,\n cause?: Error,\n public readonly retryable?: boolean,\n ) {\n super(message, cause ? { cause } : undefined);\n this.name = 'ResearchOSError';\n }\n}\n\nexport class IntakeValidationError extends ResearchOSError {\n constructor(message: string, public readonly issues: unknown) {\n super(message, 'INTAKE_VALIDATION');\n this.name = 'IntakeValidationError';\n }\n}\n\nexport class PackExistsError extends ResearchOSError {\n constructor(path: string) {\n super(`Pack directory already exists: ${path}`, 'PACK_EXISTS');\n this.name = 'PackExistsError';\n }\n}\n\nexport class TemplateNotFoundError extends ResearchOSError {\n constructor(path: string) {\n super(`Pack template not found at ${path}`, 'TEMPLATE_NOT_FOUND');\n this.name = 'TemplateNotFoundError';\n }\n}\n\nexport class PackNotFoundError extends ResearchOSError {\n constructor(path: string) {\n super(`No research.yaml found at ${path}. Run 'research-os init' first.`, 'PACK_NOT_FOUND');\n this.name = 'PackNotFoundError';\n }\n}\n\nexport class SectionExistsError extends ResearchOSError {\n constructor(id: string) {\n super(`Section already exists: ${id}`, 'SECTION_EXISTS');\n this.name = 'SectionExistsError';\n }\n}\n\nexport class InvalidSectionIdError extends ResearchOSError {\n constructor(id: string) {\n super(`Invalid section id: \"${id}\". Must match pattern NN-slug (e.g. \"01-landscape\").`, 'INVALID_SECTION_ID');\n this.name = 'InvalidSectionIdError';\n }\n}\n\nexport class SectionNotFoundError extends ResearchOSError {\n constructor(id: string) {\n super(`Section not found: ${id}. Run 'research-os section add' first.`, 'SECTION_NOT_FOUND');\n this.name = 'SectionNotFoundError';\n }\n}\n\nexport class NoUrlsProvidedError extends ResearchOSError {\n constructor() {\n super(\n `No URLs provided. Pass --url <url> (repeatable) or --urls-file <path>. 'gather' acquires known sources; discovery/search is a separate step.`,\n 'NO_URLS_PROVIDED',\n );\n this.name = 'NoUrlsProvidedError';\n }\n}\n\nexport class NoSourcesGatheredError extends ResearchOSError {\n constructor(sectionId: string) {\n super(\n `Section \"${sectionId}\" has no gathered sources. Run 'research-os gather ${sectionId} --url ...' first. Claim extraction requires source truth.`,\n 'NO_SOURCES_GATHERED',\n );\n this.name = 'NoSourcesGatheredError';\n }\n}\n\nexport class HandoffNotFoundError extends ResearchOSError {\n constructor() {\n super(\n `No handoff on file at handoffs/cowork-handoff.json. Run 'research-os cowork handoff' first.`,\n 'HANDOFF_NOT_FOUND',\n );\n this.name = 'HandoffNotFoundError';\n }\n}\n\nexport class SynthesisNotReadyError extends ResearchOSError {\n constructor(public readonly mode: string) {\n super(\n `Synthesis workspace refused: pack is in ${mode} mode. Run 'research-os cowork handoff' for repair instructions.`,\n 'SYNTHESIS_NOT_READY',\n );\n this.name = 'SynthesisNotReadyError';\n }\n}\n","import { z } from 'zod';\n\nexport const SectionStatusSchema = z.enum([\n 'draft',\n 'gathering',\n 'gated',\n 'reviewed',\n 'frozen',\n]);\n\nexport const SectionSchema = z.object({\n id: z\n .string()\n .regex(/^[0-9]{2}-[a-z0-9-]+$/, 'Section id must look like \"01-landscape\"'),\n purpose: z.string().min(1),\n max_time_minutes: z.number().int().positive().default(45),\n min_sources: z.number().int().nonnegative().default(8),\n primary_sources_required: z.number().int().nonnegative().default(2),\n contradictions_required: z.boolean().default(true),\n status: SectionStatusSchema.default('draft'),\n});\n\nexport const SourceFloorGateSchema = z.object({\n min_sources: z.number().int().nonnegative().default(8),\n min_independent_publishers: z.number().int().nonnegative().default(4),\n primary_sources_required: z.number().int().nonnegative().default(2),\n primary_source_waiver_allowed: z.boolean().default(true),\n});\n\nexport const ClaimIntegrityGateSchema = z.object({\n every_claim_needs_source: z.boolean().default(true),\n no_orphan_claims: z.boolean().default(true),\n no_source_cluster_monopoly: z.boolean().default(true),\n});\n\nexport const FreshnessGateSchema = z.object({\n required_for_current_topics: z.boolean().default(true),\n stale_source_policy: z.enum(['warn', 'fail']).default('warn'),\n});\n\nexport const ContradictionGateSchema = z.object({\n required: z.boolean().default(true),\n unresolved_contradictions_block_synthesis: z.boolean().default(true),\n});\n\nexport const SectionBudgetGateSchema = z.object({\n max_time_minutes: z.number().int().positive().default(45),\n extension_requires_evidence: z.boolean().default(true),\n});\n\nexport const GateConfigSchema = z.object({\n source_floor: SourceFloorGateSchema.default({}),\n claim_integrity: ClaimIntegrityGateSchema.default({}),\n freshness: FreshnessGateSchema.default({}),\n contradiction: ContradictionGateSchema.default({}),\n section_budget: SectionBudgetGateSchema.default({}),\n});\n\nexport const PrimarySourceWaiverSchema = z.object({\n status: z.enum(['none', 'requested', 'granted']).default('none'),\n reason: z.string().optional(),\n compensating_controls: z.array(z.string()).default([]),\n});\n\nexport const FreshnessRequirementsSchema = z.object({\n required: z.boolean().default(true),\n max_source_age_months: z.number().int().positive().nullable().default(null),\n});\n\n// A documented reviewer-profile preset. Bundles the model/window/mode that\n// were known-good (or known-bad) on a given rig so future runs don't have\n// to rediscover timeout/context/false-positive issues. Status:\n// - calibrated_baseline: passed seeded calibration; safe default\n// - experimental: not yet calibrated; results untrusted\n// - deprecated: shipped, then disqualified by calibration\nexport const ReviewProfilePresetSchema = z.object({\n general_model: z.string().nullable().default(null),\n critic_model: z.string().nullable().default(null),\n review_window: z.number().int().positive().nullable().default(null),\n mode: z.enum(['general', 'two_pass']).default('two_pass'),\n status: z\n .enum(['calibrated_baseline', 'experimental', 'deprecated'])\n .default('experimental'),\n notes: z.string().nullable().default(null),\n});\n\nexport const DEFAULT_REVIEW_PROFILES: Record<string, z.input<typeof ReviewProfilePresetSchema>> = {\n // The dogfood-validated baseline. Section 03 of research-os-spec is the\n // calibration fixture: long sources, waiver pressure, 715 candidates,\n // hermes3:8b-only two-pass with window 10 hits 0% false-flag on the\n // seeded fixture and the narrow_critic actually fires.\n 'hermes-two-pass': {\n general_model: 'hermes3:8b',\n critic_model: 'hermes3:8b',\n review_window: 10,\n mode: 'two_pass',\n status: 'calibrated_baseline',\n notes:\n 'Calibrated baseline as of v0.1. 0% good-claim FPR on the seeded fixture; bad-claim any-flag recall 9/13 (69%). Smaller window required because hermes3:8b at 4-bit on a 5080 cannot complete 25-claim windows within a 3-minute budget.',\n },\n};\n\nexport const ResearchYamlSchema = z.object({\n research_os_version: z.string(),\n created_at: z.string(),\n topic: z.string().min(10, 'Topic must be at least 10 characters'),\n decision: z.string().default(''),\n audience: z.string().default('self'),\n desired_output: z.string().default(''),\n max_runtime_minutes: z.number().int().positive().default(240),\n freshness: FreshnessRequirementsSchema.default({}),\n excluded_sources: z.array(z.string()).default([]),\n primary_source_waiver: PrimarySourceWaiverSchema.default({}),\n sections: z.array(SectionSchema).default([]),\n gates: GateConfigSchema.default({}),\n // Reviewer-profile presets baked into the pack so future review runs\n // (across any section in this pack) inherit the calibrated configuration\n // without rediscovering rig-specific timeouts and context issues. Override\n // with `--preset <name>` on `research-os review`.\n review_profiles: z\n .record(z.string(), ReviewProfilePresetSchema)\n .default(() => ({ ...DEFAULT_REVIEW_PROFILES })),\n frozen_at: z.string().nullable().default(null),\n});\n\nexport type Section = z.infer<typeof SectionSchema>;\nexport type GateConfig = z.infer<typeof GateConfigSchema>;\nexport type PrimarySourceWaiver = z.infer<typeof PrimarySourceWaiverSchema>;\nexport type ReviewProfilePreset = z.infer<typeof ReviewProfilePresetSchema>;\nexport type ResearchYaml = z.infer<typeof ResearchYamlSchema>;\n","import { mkdir, writeFile, readFile, readdir, stat } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { stringify as yamlStringify } from 'yaml';\n\nimport { PackExistsError, TemplateNotFoundError } from '../errors.js';\nimport { ResearchYamlSchema, type ResearchYaml } from './schema.js';\nimport type { InitOptions, InitResult } from './types.js';\n\nconst PACKAGE_VERSION = '0.1.0';\n\nexport function slugify(input: string): string {\n const normalized = input\n .toLowerCase()\n .normalize('NFKD')\n .replace(/[̀-ͯ]/g, '')\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 60)\n .replace(/-+$/g, '');\n return normalized || 'research-pack';\n}\n\nfunction findTemplatesDir(): string {\n const here = dirname(fileURLToPath(import.meta.url));\n const candidates = [\n resolve(here, '../templates/pack'),\n resolve(here, '../../templates/pack'),\n resolve(here, '../../../templates/pack'),\n ];\n for (const candidate of candidates) {\n if (existsSync(candidate)) return candidate;\n }\n throw new TemplateNotFoundError(candidates.join(' | '));\n}\n\nasync function copyTreeRelative(srcDir: string, destDir: string, written: string[]): Promise<void> {\n const entries = await readdir(srcDir, { withFileTypes: true });\n for (const entry of entries) {\n const srcPath = join(srcDir, entry.name);\n const destPath = join(destDir, entry.name);\n if (entry.isDirectory()) {\n await mkdir(destPath, { recursive: true });\n await copyTreeRelative(srcPath, destPath, written);\n } else if (entry.isFile()) {\n const data = await readFile(srcPath);\n await writeFile(destPath, data);\n written.push(destPath);\n }\n }\n}\n\nexport function buildResearchYaml(options: InitOptions): ResearchYaml {\n const draft = {\n research_os_version: PACKAGE_VERSION,\n created_at: new Date().toISOString(),\n topic: options.topic,\n decision: options.decision ?? '',\n audience: options.audience ?? 'self',\n desired_output: options.desiredOutput ?? '',\n max_runtime_minutes: options.maxRuntimeMinutes ?? 240,\n freshness: { required: true, max_source_age_months: null },\n excluded_sources: [],\n primary_source_waiver: { status: 'none', compensating_controls: [] },\n sections: [],\n frozen_at: null,\n gates: {\n source_floor: {\n min_sources: 8,\n min_independent_publishers: 4,\n primary_sources_required: 2,\n primary_source_waiver_allowed: true,\n },\n claim_integrity: {\n every_claim_needs_source: true,\n no_orphan_claims: true,\n no_source_cluster_monopoly: true,\n },\n freshness: {\n required_for_current_topics: true,\n stale_source_policy: 'warn',\n },\n contradiction: {\n required: true,\n unresolved_contradictions_block_synthesis: true,\n },\n section_budget: {\n max_time_minutes: 45,\n extension_requires_evidence: true,\n },\n },\n };\n return ResearchYamlSchema.parse(draft);\n}\n\nexport async function init(options: InitOptions): Promise<InitResult> {\n const packName = options.name?.trim() || slugify(options.topic);\n const baseDir = options.outDir ? resolve(options.outDir) : process.cwd();\n const packPath = resolve(baseDir, packName);\n\n if (existsSync(packPath) && !options.force) {\n const s = await stat(packPath);\n if (s.isDirectory()) {\n const entries = await readdir(packPath);\n if (entries.length > 0) throw new PackExistsError(packPath);\n } else {\n throw new PackExistsError(packPath);\n }\n }\n\n const written: string[] = [];\n\n await mkdir(packPath, { recursive: true });\n for (const dir of [\n 'sections',\n 'evidence/source-cards',\n 'synthesis',\n 'audits',\n 'prompts',\n ]) {\n await mkdir(join(packPath, dir), { recursive: true });\n }\n\n const templatesDir = findTemplatesDir();\n await copyTreeRelative(templatesDir, packPath, written);\n\n const research = buildResearchYaml(options);\n const yamlPath = join(packPath, 'research.yaml');\n await writeFile(yamlPath, yamlStringify(research, { lineWidth: 0 }), 'utf8');\n written.push(yamlPath);\n\n const fetchLogPath = join(packPath, 'evidence', 'fetch-log.jsonl');\n const citationLedgerPath = join(packPath, 'evidence', 'citation-ledger.jsonl');\n for (const ledger of [fetchLogPath, citationLedgerPath]) {\n if (!existsSync(ledger)) {\n await writeFile(ledger, '', 'utf8');\n written.push(ledger);\n }\n }\n\n return { packPath, packName, filesWritten: written };\n}\n","export { init, buildResearchYaml, slugify } from './scaffold.js';\nexport type { InitOptions, InitResult } from './types.js';\nexport {\n ResearchYamlSchema,\n SectionSchema,\n GateConfigSchema,\n PrimarySourceWaiverSchema,\n type ResearchYaml,\n type Section,\n type GateConfig,\n type PrimarySourceWaiver,\n} from './schema.js';\n","import { z } from 'zod';\nimport { SectionStatusSchema } from '../intake/schema.js';\n\nexport const SectionGatesYamlSchema = z.object({\n section_id: z\n .string()\n .regex(/^[0-9]{2}-[a-z0-9-]+$/, 'Section id must look like \"01-landscape\"'),\n purpose: z.string().min(1),\n status: SectionStatusSchema,\n created_at: z.string(),\n max_time_minutes: z.number().int().positive(),\n min_sources: z.number().int().nonnegative(),\n primary_sources_required: z.number().int().nonnegative(),\n contradictions_required: z.boolean(),\n});\n\nexport type SectionGatesYaml = z.infer<typeof SectionGatesYamlSchema>;\n","import { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { parse as yamlParse, stringify as yamlStringify } from 'yaml';\n\nimport {\n PackNotFoundError,\n SectionExistsError,\n InvalidSectionIdError,\n} from '../errors.js';\nimport {\n ResearchYamlSchema,\n SectionSchema,\n type Section,\n type ResearchYaml,\n} from '../intake/schema.js';\nimport { SectionGatesYamlSchema, type SectionGatesYaml } from './schema.js';\nimport type { SectionAddOptions, SectionAddResult } from './types.js';\n\nconst SECTION_ID_PATTERN = /^[0-9]{2}-[a-z0-9-]+$/;\n\nfunction briefStub(opts: SectionAddOptions): string {\n return `# Section: ${opts.id}\n\n**Status:** draft\n**Purpose:** ${opts.purpose}\n\n## Findings\n\n_This section has not been gathered yet. Sources, claims, and contradictions will be populated by the section-worker pass._\n\n## What the evidence supports\n\n_To be populated after gathering and gate pass._\n\n## What the evidence does not support\n\n_To be populated._\n\n## Unresolved\n\n_To be populated._\n`;\n}\n\nfunction contradictionsStub(id: string): string {\n return `# Contradictions: ${id}\n\n_No contradictions recorded yet. Each contradiction must include both sides with source IDs from the source ledger._\n\n## Format\n\n\\`\\`\\`\n## Contradiction C-<n>: <short label>\n\n**Side A:** <claim> (source: <source_id>)\n**Side B:** <claim> (source: <source_id>)\n**Status:** unresolved | reconciled-by-<source_id> | preserved-deliberately\n**Notes:** <reason>\n\\`\\`\\`\n`;\n}\n\nfunction openQuestionsStub(id: string): string {\n return `# Open questions: ${id}\n\n_Questions raised by this section that are not resolved within section scope. Cross-section synthesis or additional gathering may resolve them._\n\n## Format\n\n\\`\\`\\`\n- **Q-<n>:** <question> — needs: <evidence-shape>\n\\`\\`\\`\n`;\n}\n\nasync function loadResearchYaml(packPath: string): Promise<{ yaml: ResearchYaml; path: string }> {\n const yamlPath = join(packPath, 'research.yaml');\n if (!existsSync(yamlPath)) throw new PackNotFoundError(packPath);\n const text = await readFile(yamlPath, 'utf8');\n const parsed = ResearchYamlSchema.parse(yamlParse(text));\n return { yaml: parsed, path: yamlPath };\n}\n\nexport async function add(options: SectionAddOptions): Promise<SectionAddResult> {\n if (!SECTION_ID_PATTERN.test(options.id)) {\n throw new InvalidSectionIdError(options.id);\n }\n if (!options.purpose || options.purpose.trim().length === 0) {\n throw new Error('Section purpose is required');\n }\n\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n const { yaml, path: yamlPath } = await loadResearchYaml(packPath);\n\n if (yaml.sections.some((s) => s.id === options.id)) {\n throw new SectionExistsError(options.id);\n }\n\n const newSection: Section = SectionSchema.parse({\n id: options.id,\n purpose: options.purpose,\n max_time_minutes: options.maxTimeMinutes ?? yaml.gates.section_budget.max_time_minutes,\n min_sources: options.minSources ?? yaml.gates.source_floor.min_sources,\n primary_sources_required:\n options.primarySourcesRequired ?? yaml.gates.source_floor.primary_sources_required,\n contradictions_required:\n options.contradictionsRequired ?? yaml.gates.contradiction.required,\n status: 'draft',\n });\n\n const updated: ResearchYaml = ResearchYamlSchema.parse({\n ...yaml,\n sections: [...yaml.sections, newSection],\n });\n\n const sectionPath = join(packPath, 'sections', options.id);\n await mkdir(sectionPath, { recursive: true });\n\n const written: string[] = [];\n\n const writes: Array<[string, string]> = [\n [join(sectionPath, 'brief.md'), briefStub(options)],\n [join(sectionPath, 'sources.jsonl'), ''],\n [join(sectionPath, 'claims.jsonl'), ''],\n [join(sectionPath, 'contradictions.md'), contradictionsStub(options.id)],\n [join(sectionPath, 'open_questions.md'), openQuestionsStub(options.id)],\n ];\n for (const [path, content] of writes) {\n await writeFile(path, content, 'utf8');\n written.push(path);\n }\n\n const gatesYaml: SectionGatesYaml = SectionGatesYamlSchema.parse({\n section_id: newSection.id,\n purpose: newSection.purpose,\n status: newSection.status,\n created_at: new Date().toISOString(),\n max_time_minutes: newSection.max_time_minutes,\n min_sources: newSection.min_sources,\n primary_sources_required: newSection.primary_sources_required,\n contradictions_required: newSection.contradictions_required,\n });\n const gatesPath = join(sectionPath, 'gates.yaml');\n await writeFile(gatesPath, yamlStringify(gatesYaml, { lineWidth: 0 }), 'utf8');\n written.push(gatesPath);\n\n await writeFile(yamlPath, yamlStringify(updated, { lineWidth: 0 }), 'utf8');\n written.push(yamlPath);\n\n return {\n sectionId: newSection.id,\n sectionPath,\n filesWritten: written,\n };\n}\n","export { add } from './scaffold.js';\nexport { SectionGatesYamlSchema, type SectionGatesYaml } from './schema.js';\nexport type { SectionAddOptions, SectionAddResult } from './types.js';\n","import { createHash } from 'node:crypto';\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport { extname, join, relative } from 'node:path';\nimport { URL } from 'node:url';\n\nimport type { FetchReceipt } from './schema.js';\n\nexport interface FetchAttemptResult {\n receipt: FetchReceipt;\n rawText: string | null;\n rawTextAbsPath: string | null;\n}\n\nfunction urlHash(url: string): string {\n return createHash('sha256').update(url).digest('hex').slice(0, 12);\n}\n\nexport function makeSourceId(url: string): string {\n return `src_${urlHash(url)}`;\n}\n\nexport function makeReceiptId(sourceId: string, when: Date): string {\n const ts = when.getTime();\n return `rcpt_${sourceId.replace(/^src_/, '')}_${ts}`;\n}\n\nfunction pickExtension(contentType: string | null, finalUrl: string | null): string {\n if (contentType?.includes('text/html')) return '.html';\n if (contentType?.includes('text/plain')) return '.txt';\n if (contentType?.includes('application/json')) return '.json';\n if (contentType?.includes('text/markdown')) return '.md';\n if (finalUrl) {\n try {\n const ext = extname(new URL(finalUrl).pathname);\n if (ext) return ext;\n } catch {\n /* fall through */\n }\n }\n return '.txt';\n}\n\nfunction isTextLike(contentType: string | null): boolean {\n if (!contentType) return true;\n return (\n contentType.startsWith('text/') ||\n contentType.includes('json') ||\n contentType.includes('xml') ||\n contentType.includes('javascript')\n );\n}\n\nexport interface FetchOptions {\n sectionId: string;\n packPath: string;\n fetchImpl?: typeof fetch;\n}\n\nexport async function fetchOnce(\n url: string,\n options: FetchOptions,\n): Promise<FetchAttemptResult> {\n const fetchImpl = options.fetchImpl ?? globalThis.fetch;\n const sourceId = makeSourceId(url);\n const fetchedAt = new Date();\n const receiptId = makeReceiptId(sourceId, fetchedAt);\n\n const receiptBase = {\n receipt_id: receiptId,\n source_id: sourceId,\n section_id: options.sectionId,\n requested_url: url,\n fetched_at: fetchedAt.toISOString(),\n extraction_outcome: 'skipped' as const,\n extraction_extractor: null,\n extraction_error: null,\n };\n\n let response: Response;\n try {\n response = await fetchImpl(url, {\n redirect: 'follow',\n headers: { 'User-Agent': 'research-os/0.1.0' },\n });\n } catch (err) {\n const receipt: FetchReceipt = {\n ...receiptBase,\n final_url: null,\n status: null,\n status_text: null,\n content_type: null,\n byte_count: null,\n sha256: null,\n title: null,\n raw_text_path: null,\n fetch_outcome: 'network_error',\n fetch_error: err instanceof Error ? err.message : String(err),\n };\n return { receipt, rawText: null, rawTextAbsPath: null };\n }\n\n const finalUrl = response.url || url;\n const contentType = response.headers.get('content-type');\n\n if (!response.ok) {\n const receipt: FetchReceipt = {\n ...receiptBase,\n final_url: finalUrl,\n status: response.status,\n status_text: response.statusText || null,\n content_type: contentType,\n byte_count: null,\n sha256: null,\n title: null,\n raw_text_path: null,\n fetch_outcome: 'http_error',\n fetch_error: `${response.status} ${response.statusText || ''}`.trim(),\n };\n return { receipt, rawText: null, rawTextAbsPath: null };\n }\n\n const buffer = Buffer.from(await response.arrayBuffer());\n const sha256 = createHash('sha256').update(buffer).digest('hex');\n const byteCount = buffer.byteLength;\n\n let rawText: string | null = null;\n let rawTextRelPath: string | null = null;\n let rawTextAbsPath: string | null = null;\n\n if (isTextLike(contentType)) {\n rawText = buffer.toString('utf8');\n const ext = pickExtension(contentType, finalUrl);\n const dir = join(options.packPath, 'evidence', 'raw');\n await mkdir(dir, { recursive: true });\n const abs = join(dir, `${sourceId}${ext}`);\n await writeFile(abs, rawText, 'utf8');\n rawTextRelPath = relative(options.packPath, abs).split('\\\\').join('/');\n rawTextAbsPath = abs;\n }\n\n let title: string | null = null;\n if (rawText && contentType?.includes('text/html')) {\n const m = /<title[^>]*>([\\s\\S]*?)<\\/title>/i.exec(rawText);\n if (m && m[1]) title = m[1].trim() || null;\n }\n\n const receipt: FetchReceipt = {\n ...receiptBase,\n final_url: finalUrl,\n status: response.status,\n status_text: response.statusText || null,\n content_type: contentType,\n byte_count: byteCount,\n sha256,\n title,\n raw_text_path: rawTextRelPath,\n fetch_outcome: 'ok',\n fetch_error: null,\n };\n\n return { receipt, rawText, rawTextAbsPath };\n}\n","import { readFile } from 'node:fs/promises';\n\nexport function parseUrlsFileText(text: string): string[] {\n return text\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter((line) => line.length > 0 && !line.startsWith('#'));\n}\n\nexport async function readUrlsFile(path: string): Promise<string[]> {\n const text = await readFile(path, 'utf8');\n return parseUrlsFileText(text);\n}\n\nfunction isValidHttpUrl(candidate: string): boolean {\n try {\n const u = new URL(candidate);\n return u.protocol === 'http:' || u.protocol === 'https:';\n } catch {\n return false;\n }\n}\n\nexport function dedupeAndValidate(urls: string[]): { valid: string[]; invalid: string[] } {\n const seen = new Set<string>();\n const valid: string[] = [];\n const invalid: string[] = [];\n for (const u of urls) {\n if (!isValidHttpUrl(u)) {\n invalid.push(u);\n continue;\n }\n const norm = u;\n if (seen.has(norm)) continue;\n seen.add(norm);\n valid.push(norm);\n }\n return { valid, invalid };\n}\n\nexport async function collectUrls(input: {\n urls?: string[];\n urlsFile?: string;\n}): Promise<{ urls: string[]; invalid: string[] }> {\n const collected: string[] = [];\n if (input.urls) collected.push(...input.urls);\n if (input.urlsFile) collected.push(...(await readUrlsFile(input.urlsFile)));\n const { valid, invalid } = dedupeAndValidate(collected);\n return { urls: valid, invalid };\n}\n","import * as cheerio from 'cheerio';\nimport { URL } from 'node:url';\n\nimport type {\n Extractor,\n ExtractionInput,\n ExtractionResult,\n Relevance,\n SourceType,\n} from '../types.js';\n\nfunction deriveSourceType(rawUrl: string, finalUrl: string | null): SourceType {\n const u = finalUrl ?? rawUrl;\n let host: string;\n try {\n host = new URL(u).hostname.toLowerCase();\n } catch {\n return 'unknown';\n }\n if (host.startsWith('docs.') || host.endsWith('.readthedocs.io')) return 'docs';\n if (host === 'github.com' && /\\/(issues|pull|discussions)\\//.test(u)) return 'forum';\n if (host === 'news.ycombinator.com' || host.endsWith('reddit.com') || host.endsWith('stackoverflow.com'))\n return 'forum';\n if (host.endsWith('arxiv.org') || host.endsWith('semanticscholar.org')) return 'primary';\n if (host.endsWith('paperswithcode.com')) return 'benchmark';\n if (host.endsWith('anthropic.com') || host.endsWith('openai.com') || host.endsWith('claude.com'))\n return 'primary';\n return 'secondary';\n}\n\nfunction clean(text: string | undefined | null): string {\n return (text ?? '').replace(/\\s+/g, ' ').trim();\n}\n\nexport class HeuristicExtractor implements Extractor {\n readonly name = 'heuristic' as const;\n\n async available(): Promise<boolean> {\n return true;\n }\n\n async extract(input: ExtractionInput): Promise<ExtractionResult> {\n if (!input.rawText) {\n return { ok: false, error: 'No raw text available for extraction' };\n }\n const isHtml = (input.contentType ?? '').includes('text/html') || /<html/i.test(input.rawText);\n\n if (!isHtml) {\n const title = clean(input.rawText.split(/\\r?\\n/, 1)[0] || '').slice(0, 200);\n const asserts = title || clean(input.rawText).slice(0, 240);\n const keyPoints = clean(input.rawText)\n .split(/(?<=[.!?])\\s+/)\n .slice(0, 3)\n .map((s) => clean(s))\n .filter((s) => s.length > 0);\n return {\n ok: true,\n publisher: null,\n published_at: null,\n title: title || '(untitled)',\n source_type: deriveSourceType(input.url, input.finalUrl),\n relevance: 'unknown',\n key_points: keyPoints,\n limitations: [],\n asserts: asserts || '(empty)',\n scope: null,\n not: null,\n };\n }\n\n const $ = cheerio.load(input.rawText);\n\n $('script, style, noscript, nav, header, footer').remove();\n\n const title =\n clean($('meta[property=\"og:title\"]').attr('content')) ||\n clean($('meta[name=\"twitter:title\"]').attr('content')) ||\n clean($('title').first().text()) ||\n clean($('h1').first().text()) ||\n '(untitled)';\n\n const description =\n clean($('meta[property=\"og:description\"]').attr('content')) ||\n clean($('meta[name=\"description\"]').attr('content')) ||\n '';\n\n let publisher: string | null =\n clean($('meta[property=\"og:site_name\"]').attr('content')) || null;\n if (!publisher) {\n try {\n publisher = new URL(input.finalUrl ?? input.url).hostname;\n } catch {\n publisher = null;\n }\n }\n\n let publishedAt: string | null =\n clean($('meta[property=\"article:published_time\"]').attr('content')) ||\n clean($('meta[name=\"date\"]').attr('content')) ||\n clean($('time[datetime]').first().attr('datetime')) ||\n null;\n if (publishedAt === '') publishedAt = null;\n\n const mainNode =\n $('article').first().length > 0\n ? $('article').first()\n : $('main').first().length > 0\n ? $('main').first()\n : $('body');\n\n const paragraphs = mainNode\n .find('p')\n .map((_, el) => clean($(el).text()))\n .get()\n .filter((t) => t.length > 40);\n\n const keyPoints = paragraphs.slice(0, 5);\n const asserts = description || paragraphs[0] || title;\n\n return {\n ok: true,\n publisher,\n published_at: publishedAt,\n title,\n source_type: deriveSourceType(input.url, input.finalUrl),\n relevance: 'unknown' as Relevance,\n key_points: keyPoints,\n limitations: [],\n asserts: asserts.slice(0, 600),\n scope: null,\n not: null,\n };\n }\n}\n","import type {\n Extractor,\n ExtractionInput,\n ExtractionResult,\n SourceType,\n Relevance,\n} from '../types.js';\n\nconst DEFAULT_HOST = 'http://localhost:11434';\nconst DEFAULT_MODEL = 'hermes3:8b';\n\nexport function normalizeOllamaHost(host: string): string {\n const trimmed = host.trim().replace(/\\/+$/, '');\n if (/^https?:\\/\\//i.test(trimmed)) return trimmed;\n return `http://${trimmed}`;\n}\n\nconst SYSTEM_PROMPT = `You are an extractor for a gated research pack. Given the URL, content type, and raw text of a fetched source, return ONE JSON object with these fields and no other prose:\n\n{\n \"publisher\": string | null,\n \"published_at\": ISO-8601 string | null,\n \"title\": short string,\n \"source_type\": \"primary\" | \"secondary\" | \"forum\" | \"benchmark\" | \"docs\" | \"unknown\",\n \"relevance\": \"high\" | \"medium\" | \"low\" | \"unknown\",\n \"key_points\": string[] // 3-5 short factual points the source actually makes\n \"limitations\": string[] // honest caveats about source quality, recency, scope\n \"asserts\": string // ONE sentence summarizing what the source claims as its main thrust\n \"scope\": string | null // ONE sentence naming the contextual scope of \"asserts\" (the situation, system, or domain to which it applies). null only if the scope is genuinely indeterminable from the source.\n \"not\": string | null // ONE sentence stating what the source explicitly is NOT a claim about, to prevent overgeneralization. null if no such limit can be inferred.\n}\n\nBe strict. Do not fabricate. If the source does not state a value, leave it null. If the source argues a contextual position, \"scope\" must reflect that context — never widen a contextual claim into a universal one.`;\n\nexport interface OllamaConfig {\n host?: string;\n model?: string;\n timeoutMs?: number;\n fetchImpl?: typeof fetch;\n}\n\nexport class OllamaInternExtractor implements Extractor {\n readonly name = 'ollama-intern' as const;\n private readonly host: string;\n private readonly model: string;\n private readonly timeoutMs: number;\n private readonly fetchImpl: typeof fetch;\n\n constructor(config: OllamaConfig = {}) {\n this.host = normalizeOllamaHost(config.host ?? process.env.OLLAMA_HOST ?? DEFAULT_HOST);\n this.model = config.model ?? process.env.OLLAMA_INTERN_MODEL ?? DEFAULT_MODEL;\n this.timeoutMs = config.timeoutMs ?? 60_000;\n this.fetchImpl = config.fetchImpl ?? globalThis.fetch;\n }\n\n async available(): Promise<boolean> {\n try {\n const ctrl = new AbortController();\n const t = setTimeout(() => ctrl.abort(), 1500);\n const res = await this.fetchImpl(`${this.host}/api/tags`, { signal: ctrl.signal });\n clearTimeout(t);\n if (!res.ok) return false;\n const body = (await res.json()) as { models?: Array<{ name: string }> };\n const names = (body.models ?? []).map((m) => m.name);\n return names.some((n) => n === this.model || n.startsWith(this.model.split(':')[0]));\n } catch {\n return false;\n }\n }\n\n async extract(input: ExtractionInput): Promise<ExtractionResult> {\n if (!input.rawText) {\n return { ok: false, error: 'No raw text available for extraction' };\n }\n\n const truncated = input.rawText.slice(0, 16_000);\n const userMsg = `URL: ${input.url}\\nFinal URL: ${input.finalUrl ?? input.url}\\nContent-Type: ${input.contentType ?? 'unknown'}\\n\\nRAW TEXT BEGIN\\n${truncated}\\nRAW TEXT END`;\n\n const ctrl = new AbortController();\n const t = setTimeout(() => ctrl.abort(), this.timeoutMs);\n\n let body: { message?: { content?: string }; response?: string };\n try {\n const res = await this.fetchImpl(`${this.host}/api/chat`, {\n method: 'POST',\n signal: ctrl.signal,\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n model: this.model,\n stream: false,\n format: 'json',\n messages: [\n { role: 'system', content: SYSTEM_PROMPT },\n { role: 'user', content: userMsg },\n ],\n }),\n });\n if (!res.ok) {\n return { ok: false, error: `Ollama HTTP ${res.status}` };\n }\n body = (await res.json()) as typeof body;\n } catch (err) {\n return {\n ok: false,\n error: err instanceof Error ? err.message : 'Ollama request failed',\n };\n } finally {\n clearTimeout(t);\n }\n\n const text = body.message?.content ?? body.response ?? '';\n let parsed: Record<string, unknown>;\n try {\n parsed = JSON.parse(text);\n } catch {\n return { ok: false, error: 'Ollama response was not valid JSON' };\n }\n\n const sourceTypes: SourceType[] = ['primary', 'secondary', 'forum', 'benchmark', 'docs', 'unknown'];\n const relevances: Relevance[] = ['high', 'medium', 'low', 'unknown'];\n\n const sourceType = sourceTypes.includes(parsed.source_type as SourceType)\n ? (parsed.source_type as SourceType)\n : 'unknown';\n const relevance = relevances.includes(parsed.relevance as Relevance)\n ? (parsed.relevance as Relevance)\n : 'unknown';\n\n const stringOrNull = (v: unknown): string | null =>\n typeof v === 'string' && v.trim().length > 0 ? v.trim() : null;\n\n const stringArray = (v: unknown): string[] =>\n Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string').map((s) => s.trim()) : [];\n\n return {\n ok: true,\n publisher: stringOrNull(parsed.publisher),\n published_at: stringOrNull(parsed.published_at),\n title: typeof parsed.title === 'string' && parsed.title.trim().length > 0 ? parsed.title.trim() : '(untitled)',\n source_type: sourceType,\n relevance,\n key_points: stringArray(parsed.key_points),\n limitations: stringArray(parsed.limitations),\n asserts: typeof parsed.asserts === 'string' && parsed.asserts.trim().length > 0 ? parsed.asserts.trim() : '(no assertion extracted)',\n scope: stringOrNull(parsed.scope),\n not: stringOrNull(parsed.not),\n };\n }\n}\n","import type { Extractor } from '../types.js';\nimport { HeuristicExtractor } from './heuristic.js';\nimport { OllamaInternExtractor } from './ollama-intern.js';\n\nexport { HeuristicExtractor } from './heuristic.js';\nexport { OllamaInternExtractor } from './ollama-intern.js';\n\nexport function defaultExtractors(): Extractor[] {\n return [new OllamaInternExtractor(), new HeuristicExtractor()];\n}\n\nexport async function pickExtractor(extractors: Extractor[]): Promise<Extractor> {\n for (const e of extractors) {\n if (await e.available()) return e;\n }\n throw new Error(\n 'No extractor available. The HeuristicExtractor should always be available — this indicates a bug.',\n );\n}\n","import { z } from 'zod';\n\nexport const SourceTypeSchema = z.enum([\n 'primary',\n 'secondary',\n 'forum',\n 'benchmark',\n 'docs',\n 'unknown',\n]);\n\nexport const RelevanceSchema = z.enum(['high', 'medium', 'low', 'unknown']);\n\nexport const ExtractorNameSchema = z.enum(['heuristic', 'ollama-intern']);\n\nexport const FetchReceiptSchema = z.object({\n receipt_id: z.string().regex(/^rcpt_[a-z0-9]+_\\d+$/),\n source_id: z.string().regex(/^src_[a-f0-9]{12}$/),\n section_id: z.string().regex(/^[0-9]{2}-[a-z0-9-]+$/),\n requested_url: z.string().url(),\n final_url: z.string().url().nullable(),\n status: z.number().int().nullable(),\n status_text: z.string().nullable(),\n content_type: z.string().nullable(),\n fetched_at: z.string(),\n byte_count: z.number().int().nonnegative().nullable(),\n sha256: z.string().regex(/^[a-f0-9]{64}$/).nullable(),\n title: z.string().nullable(),\n raw_text_path: z.string().nullable(),\n fetch_outcome: z.enum(['ok', 'http_error', 'network_error']),\n fetch_error: z.string().nullable(),\n extraction_outcome: z.enum(['ok', 'failed', 'skipped']),\n extraction_extractor: ExtractorNameSchema.nullable(),\n extraction_error: z.string().nullable(),\n});\n\nexport const SourceCardSchema = z.object({\n source_id: z.string().regex(/^src_[a-f0-9]{12}$/),\n receipt_id: z.string().regex(/^rcpt_[a-z0-9]+_\\d+$/),\n section_id: z.string().regex(/^[0-9]{2}-[a-z0-9-]+$/),\n url: z.string().url(),\n final_url: z.string().url().nullable(),\n fetched_at: z.string(),\n publisher: z.string().nullable(),\n published_at: z.string().nullable(),\n title: z.string().min(1),\n source_type: SourceTypeSchema,\n relevance: RelevanceSchema,\n key_points: z.array(z.string()),\n limitations: z.array(z.string()),\n asserts: z.string().min(1),\n scope: z.string().nullable(),\n not: z.string().nullable(),\n extracted_by: ExtractorNameSchema,\n extracted_at: z.string(),\n});\n\nexport type FetchReceipt = z.infer<typeof FetchReceiptSchema>;\nexport type SourceCard = z.infer<typeof SourceCardSchema>;\n","import { mkdir, readFile, writeFile, appendFile } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\n\nimport { SourceCardSchema, type FetchReceipt, type SourceCard } from './schema.js';\nimport type { ExtractionResult, ExtractorName } from './types.js';\n\nexport function buildCard(args: {\n receipt: FetchReceipt;\n extraction: Extract<ExtractionResult, { ok: true }>;\n extractedBy: ExtractorName;\n}): SourceCard {\n const { receipt, extraction, extractedBy } = args;\n const card = SourceCardSchema.parse({\n source_id: receipt.source_id,\n receipt_id: receipt.receipt_id,\n section_id: receipt.section_id,\n url: receipt.requested_url,\n final_url: receipt.final_url,\n fetched_at: receipt.fetched_at,\n publisher: extraction.publisher,\n published_at: extraction.published_at,\n title: extraction.title,\n source_type: extraction.source_type,\n relevance: extraction.relevance,\n key_points: extraction.key_points,\n limitations: extraction.limitations,\n asserts: extraction.asserts,\n scope: extraction.scope,\n not: extraction.not,\n extracted_by: extractedBy,\n extracted_at: new Date().toISOString(),\n });\n return card;\n}\n\nexport async function writeSourceCard(packPath: string, card: SourceCard): Promise<string> {\n const dir = join(packPath, 'evidence', 'source-cards');\n await mkdir(dir, { recursive: true });\n const cardPath = join(dir, `${card.source_id}.json`);\n await writeFile(cardPath, JSON.stringify(card, null, 2), 'utf8');\n return cardPath;\n}\n\nexport async function appendFetchLog(packPath: string, receipt: FetchReceipt): Promise<void> {\n const path = join(packPath, 'evidence', 'fetch-log.jsonl');\n await appendFile(path, JSON.stringify(receipt) + '\\n', 'utf8');\n}\n\nexport async function appendSectionSourceId(\n packPath: string,\n sectionId: string,\n sourceId: string,\n): Promise<void> {\n const path = join(packPath, 'sections', sectionId, 'sources.jsonl');\n if (!existsSync(path)) {\n await writeFile(path, '', 'utf8');\n }\n const existing = await readFile(path, 'utf8');\n const ids = new Set(\n existing\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter(Boolean)\n .map((line) => {\n try {\n return (JSON.parse(line) as { source_id: string }).source_id;\n } catch {\n return null;\n }\n })\n .filter((x): x is string => x !== null),\n );\n if (ids.has(sourceId)) return;\n await appendFile(path, JSON.stringify({ source_id: sourceId, added_at: new Date().toISOString() }) + '\\n', 'utf8');\n}\n","import { existsSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\n\nimport {\n NoUrlsProvidedError,\n PackNotFoundError,\n SectionNotFoundError,\n} from '../errors.js';\nimport { fetchOnce } from './fetch.js';\nimport { collectUrls } from './url-input.js';\nimport { defaultExtractors, pickExtractor } from './extractors/index.js';\nimport {\n appendFetchLog,\n appendSectionSourceId,\n buildCard,\n writeSourceCard,\n} from './cards.js';\nimport type { GatherOptions, GatherSummary, Extractor } from './types.js';\n\nexport async function gather(options: GatherOptions): Promise<GatherSummary> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n if (!existsSync(join(packPath, 'research.yaml'))) throw new PackNotFoundError(packPath);\n if (!existsSync(join(packPath, 'sections', options.sectionId)))\n throw new SectionNotFoundError(options.sectionId);\n\n const { urls } = await collectUrls({ urls: options.urls, urlsFile: options.urlsFile });\n if (urls.length === 0) throw new NoUrlsProvidedError();\n\n const extractorList: Extractor[] = options.extractors ?? defaultExtractors();\n const extractor = await pickExtractor(extractorList);\n\n const summary: GatherSummary = {\n sectionId: options.sectionId,\n attempted: urls.length,\n fetchedOk: 0,\n fetchedFailed: 0,\n extractedOk: 0,\n extractedFailed: 0,\n cardsWritten: 0,\n receiptsAppended: 0,\n sourceIds: [],\n };\n\n for (const url of urls) {\n const { receipt, rawText } = await fetchOnce(url, {\n sectionId: options.sectionId,\n packPath,\n fetchImpl: options.fetchImpl,\n });\n\n let receiptToWrite = receipt;\n\n if (receipt.fetch_outcome === 'ok' && rawText !== null) {\n summary.fetchedOk += 1;\n const result = await extractor.extract({\n url,\n finalUrl: receipt.final_url,\n rawText,\n contentType: receipt.content_type,\n });\n if (result.ok) {\n summary.extractedOk += 1;\n receiptToWrite = {\n ...receipt,\n extraction_outcome: 'ok',\n extraction_extractor: extractor.name,\n extraction_error: null,\n };\n const card = buildCard({ receipt: receiptToWrite, extraction: result, extractedBy: extractor.name });\n await writeSourceCard(packPath, card);\n await appendSectionSourceId(packPath, options.sectionId, card.source_id);\n summary.cardsWritten += 1;\n summary.sourceIds.push(card.source_id);\n } else {\n summary.extractedFailed += 1;\n receiptToWrite = {\n ...receipt,\n extraction_outcome: 'failed',\n extraction_extractor: extractor.name,\n extraction_error: result.error,\n };\n }\n } else {\n summary.fetchedFailed += 1;\n }\n\n await appendFetchLog(packPath, receiptToWrite);\n summary.receiptsAppended += 1;\n }\n\n return summary;\n}\n","import { z } from 'zod';\n\n// Excerpts are deterministic source spans owned by research-os.\n// Models may interpret excerpts; they may not author them.\n//\n// Excerpt ID format: ex_<source_id_hex_12>_<3-digit_index>\n// e.g. ex_abcdef012345_001\nexport const EXCERPT_ID_PATTERN = /^ex_[a-f0-9]{12}_\\d{3,}$/;\n\nexport const ExcerptOriginSchema = z.enum(['raw_text', 'key_point']);\n\nexport const ExcerptSchema = z.object({\n excerpt_id: z.string().regex(EXCERPT_ID_PATTERN),\n source_id: z.string().regex(/^src_[a-f0-9]{12}$/),\n source_hash: z.string().regex(/^[a-f0-9]{64}$/).nullable(),\n text: z.string().min(1),\n location_hint: z.string().nullable(),\n char_start: z.number().int().nonnegative(),\n char_end: z.number().int().nonnegative(),\n origin: ExcerptOriginSchema,\n created_at: z.string(),\n});\n\nexport type Excerpt = z.infer<typeof ExcerptSchema>;\nexport type ExcerptOrigin = z.infer<typeof ExcerptOriginSchema>;\n","// Deterministic source-span chunker. Given raw text (HTML or plain), produces a\n// stable ordered list of excerpts. Same input → same output, byte-for-byte.\n// The model never authors evidence spans; this is where they come from.\n\nconst MIN_EXCERPT_CHARS = 30;\nconst MAX_EXCERPT_CHARS = 800;\n\nconst HTML_ENTITIES: Record<string, string> = {\n '&amp;': '&',\n '&lt;': '<',\n '&gt;': '>',\n '&quot;': '\"',\n '&#39;': \"'\",\n '&apos;': \"'\",\n '&nbsp;': ' ',\n};\n\nfunction decodeEntities(s: string): string {\n return s.replace(/&(amp|lt|gt|quot|#39|apos|nbsp);/g, (m) => HTML_ENTITIES[m] ?? m);\n}\n\nfunction looksLikeHtml(text: string): boolean {\n return /<\\/?(p|div|br|li|h[1-6]|article|section|main|body|html)\\b/i.test(text);\n}\n\n// Replace block-level HTML tags with paragraph breaks, then strip inline tags.\n// Preserves character flow but forces paragraph boundaries.\nfunction htmlToParagraphedText(text: string): string {\n let t = text\n .replace(/<script[\\s\\S]*?<\\/script>/gi, ' ')\n .replace(/<style[\\s\\S]*?<\\/style>/gi, ' ')\n .replace(/<\\/(p|div|li|h[1-6]|article|section|main|tr|table|blockquote)>/gi, '\\n\\n')\n .replace(/<br\\s*\\/?>/gi, '\\n')\n .replace(/<(p|div|li|h[1-6]|article|section|main|tr|table|blockquote)\\b[^>]*>/gi, '\\n\\n')\n .replace(/<[^>]+>/g, ' ');\n t = decodeEntities(t);\n // Normalise within-line whitespace but preserve paragraph breaks (\\n\\n+).\n t = t.replace(/[ \\t]+/g, ' ');\n t = t.replace(/\\n{2,}/g, '\\n\\n');\n t = t.replace(/[ \\t]*\\n[ \\t]*/g, '\\n');\n return t.trim();\n}\n\nfunction plainToParagraphedText(text: string): string {\n let t = text.replace(/\\r\\n/g, '\\n').replace(/\\r/g, '\\n');\n t = t.replace(/[ \\t]+/g, ' ');\n t = t.replace(/\\n{2,}/g, '\\n\\n');\n return t.trim();\n}\n\nexport interface ExcerptDraft {\n text: string;\n char_start: number;\n char_end: number;\n location_hint: string | null;\n}\n\n// Split a paragraph into sentences. Conservative: only splits on .!? followed\n// by whitespace + uppercase / end-of-text. Won't split inside common abbreviations.\nfunction splitSentences(paragraph: string): string[] {\n // Quick path: short paragraph stays intact.\n if (paragraph.length <= MAX_EXCERPT_CHARS) return [paragraph];\n const out: string[] = [];\n let buf = '';\n for (let i = 0; i < paragraph.length; i += 1) {\n const ch = paragraph[i]!;\n buf += ch;\n if (ch === '.' || ch === '!' || ch === '?') {\n const next = paragraph[i + 1];\n const nextNext = paragraph[i + 2];\n // boundary if next is space and nextNext is uppercase, OR end of string\n if (\n next === undefined ||\n (next === ' ' && nextNext !== undefined && /[A-Z0-9\"'([]/u.test(nextNext))\n ) {\n out.push(buf.trim());\n buf = '';\n }\n }\n }\n if (buf.trim().length > 0) out.push(buf.trim());\n // Merge tiny tail-fragments so we don't produce sub-min excerpts here.\n const merged: string[] = [];\n for (const s of out) {\n if (merged.length > 0 && (merged[merged.length - 1]!.length < MIN_EXCERPT_CHARS || s.length < MIN_EXCERPT_CHARS)) {\n merged[merged.length - 1] = `${merged[merged.length - 1]} ${s}`.trim();\n } else {\n merged.push(s);\n }\n }\n return merged;\n}\n\n// Produces a stable ordered list of excerpt drafts from raw source text.\n// char_start/char_end are positions inside the *cleaned* paragraphed text,\n// not the original raw HTML — that's intentional: the cleaned text is what\n// the model sees, so offsets must be reproducible from it.\nexport function chunkRawText(rawText: string): { cleaned: string; drafts: ExcerptDraft[] } {\n const cleaned = looksLikeHtml(rawText) ? htmlToParagraphedText(rawText) : plainToParagraphedText(rawText);\n const drafts: ExcerptDraft[] = [];\n if (cleaned.length === 0) return { cleaned, drafts };\n\n // Walk the cleaned text and recover paragraph offsets so char_start/char_end\n // are accurate inside `cleaned`.\n const paragraphRegex = /([^\\n][\\s\\S]*?)(?:\\n\\n+|$)/g;\n let m: RegExpExecArray | null;\n let paraIndex = 0;\n while ((m = paragraphRegex.exec(cleaned)) !== null) {\n const paraText = m[1]!.trim();\n if (paraText.length === 0) continue;\n paraIndex += 1;\n const paraStart = m.index;\n const sentences = splitSentences(paraText);\n let cursor = 0;\n for (const sentence of sentences) {\n // Locate the sentence inside the original paragraph at-or-after cursor.\n const idxInPara = m[1]!.indexOf(sentence, cursor);\n const start = idxInPara >= 0 ? paraStart + idxInPara : paraStart;\n const end = idxInPara >= 0 ? start + sentence.length : start + sentence.length;\n cursor = idxInPara >= 0 ? idxInPara + sentence.length : cursor + sentence.length;\n let text = sentence;\n if (text.length > MAX_EXCERPT_CHARS) {\n text = text.slice(0, MAX_EXCERPT_CHARS).trimEnd() + ' …';\n }\n if (text.length < MIN_EXCERPT_CHARS) continue;\n drafts.push({\n text,\n char_start: start,\n char_end: end,\n location_hint: `paragraph ${paraIndex}`,\n });\n }\n }\n return { cleaned, drafts };\n}\n\n// Build excerpt drafts from source-card key_points (used when no raw text is\n// available — still deterministic).\nexport function chunkKeyPoints(keyPoints: string[]): ExcerptDraft[] {\n const drafts: ExcerptDraft[] = [];\n let cursor = 0;\n let kpIndex = 0;\n for (const kpRaw of keyPoints) {\n const kp = kpRaw.trim();\n if (kp.length === 0) continue;\n kpIndex += 1;\n let text = kp;\n if (text.length > MAX_EXCERPT_CHARS) {\n text = text.slice(0, MAX_EXCERPT_CHARS).trimEnd() + ' …';\n }\n // Skip too-short key points: they'd fail evidence_excerpt min length anyway.\n if (text.length < 1) continue;\n drafts.push({\n text,\n char_start: cursor,\n char_end: cursor + text.length,\n location_hint: `key_point ${kpIndex}`,\n });\n cursor += text.length + 2;\n }\n return drafts;\n}\n","import { existsSync } from 'node:fs';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\n\nimport { chunkKeyPoints, chunkRawText } from './chunk.js';\nimport { ExcerptSchema, type Excerpt, type ExcerptOrigin } from './schema.js';\nimport type { SourceCard } from '../schema.js';\n\nexport function ledgerPathFor(packPath: string, sourceId: string): string {\n return join(packPath, 'evidence', 'excerpts', `${sourceId}.jsonl`);\n}\n\nfunction makeExcerptId(sourceId: string, index: number): string {\n // 1-indexed, zero-padded to at least 3 digits.\n const idx = String(index).padStart(3, '0');\n // Source IDs are always src_<12 hex>; strip the prefix so excerpts mirror the hex.\n const hex = sourceId.replace(/^src_/, '');\n return `ex_${hex}_${idx}`;\n}\n\nasync function readLedger(path: string): Promise<Excerpt[]> {\n const text = await readFile(path, 'utf8');\n const out: Excerpt[] = [];\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n out.push(ExcerptSchema.parse(JSON.parse(line)));\n } catch {\n /* skip malformed line — append-only ledgers tolerate corrupt tails */\n }\n }\n return out;\n}\n\nasync function writeLedger(path: string, excerpts: Excerpt[]): Promise<void> {\n await mkdir(dirname(path), { recursive: true });\n const body = excerpts.map((e) => JSON.stringify(e)).join('\\n') + (excerpts.length > 0 ? '\\n' : '');\n await writeFile(path, body, 'utf8');\n}\n\nexport interface LoadOrBuildArgs {\n packPath: string;\n sourceCard: SourceCard;\n sourceHash: string | null;\n rawText: string | null;\n now?: () => string;\n}\n\nexport interface LoadOrBuildResult {\n excerpts: Excerpt[];\n origin: ExcerptOrigin | 'mixed';\n built: boolean;\n}\n\n// Returns the excerpt ledger for a source. If it already exists on disk, load\n// it (deterministic input → already-deterministic ledger). Otherwise build it\n// from raw text when available, falling back to source card key_points.\nexport async function loadOrBuildLedger(args: LoadOrBuildArgs): Promise<LoadOrBuildResult> {\n const { packPath, sourceCard, sourceHash, rawText } = args;\n const now = args.now ?? (() => new Date().toISOString());\n const path = ledgerPathFor(packPath, sourceCard.source_id);\n\n if (existsSync(path)) {\n const excerpts = await readLedger(path);\n if (excerpts.length > 0) {\n const origins = new Set(excerpts.map((e) => e.origin));\n const origin: ExcerptOrigin | 'mixed' = origins.size === 1 ? (excerpts[0]!.origin) : 'mixed';\n return { excerpts, origin, built: false };\n }\n }\n\n let drafts;\n let origin: ExcerptOrigin;\n if (rawText && rawText.trim().length > 0) {\n drafts = chunkRawText(rawText).drafts;\n origin = 'raw_text';\n }\n if (!drafts || drafts.length === 0) {\n drafts = chunkKeyPoints(sourceCard.key_points);\n origin = 'key_point';\n }\n\n const createdAt = now();\n const excerpts: Excerpt[] = drafts.map((d, i) => ({\n excerpt_id: makeExcerptId(sourceCard.source_id, i + 1),\n source_id: sourceCard.source_id,\n source_hash: sourceHash,\n text: d.text,\n location_hint: d.location_hint,\n char_start: d.char_start,\n char_end: d.char_end,\n origin: origin!,\n created_at: createdAt,\n }));\n\n await writeLedger(path, excerpts);\n\n return { excerpts, origin: origin!, built: true };\n}\n\n// Render excerpts in the order the model will see them.\nexport function renderLedgerForPrompt(excerpts: Excerpt[]): string {\n return excerpts\n .map((e) => `${e.excerpt_id}${e.location_hint ? ` (${e.location_hint})` : ''}: ${e.text}`)\n .join('\\n');\n}\n\nexport function buildExcerptIndex(excerpts: Excerpt[]): Map<string, Excerpt> {\n const index = new Map<string, Excerpt>();\n for (const e of excerpts) index.set(e.excerpt_id, e);\n return index;\n}\n","export {\n EXCERPT_ID_PATTERN,\n ExcerptSchema,\n ExcerptOriginSchema,\n type Excerpt,\n type ExcerptOrigin,\n} from './schema.js';\nexport { chunkRawText, chunkKeyPoints, type ExcerptDraft } from './chunk.js';\nexport {\n loadOrBuildLedger,\n ledgerPathFor,\n renderLedgerForPrompt,\n buildExcerptIndex,\n type LoadOrBuildArgs,\n type LoadOrBuildResult,\n} from './ledger.js';\n","export { gather } from './gather.js';\nexport { fetchOnce, makeSourceId, makeReceiptId } from './fetch.js';\nexport {\n parseUrlsFileText,\n readUrlsFile,\n dedupeAndValidate,\n collectUrls,\n} from './url-input.js';\nexport {\n HeuristicExtractor,\n OllamaInternExtractor,\n defaultExtractors,\n pickExtractor,\n} from './extractors/index.js';\nexport { normalizeOllamaHost } from './extractors/ollama-intern.js';\nexport { buildCard, writeSourceCard, appendFetchLog, appendSectionSourceId } from './cards.js';\nexport {\n FetchReceiptSchema,\n SourceCardSchema,\n SourceTypeSchema,\n RelevanceSchema,\n ExtractorNameSchema,\n type FetchReceipt,\n type SourceCard,\n} from './schema.js';\nexport type {\n Extractor,\n ExtractionInput,\n ExtractionResult,\n ExtractorName,\n GatherOptions,\n GatherSummary,\n SourceType,\n Relevance,\n} from './types.js';\nexport {\n EXCERPT_ID_PATTERN,\n ExcerptSchema,\n ExcerptOriginSchema,\n chunkRawText,\n chunkKeyPoints,\n loadOrBuildLedger,\n ledgerPathFor,\n renderLedgerForPrompt,\n buildExcerptIndex,\n type Excerpt,\n type ExcerptOrigin,\n type ExcerptDraft,\n type LoadOrBuildArgs,\n type LoadOrBuildResult,\n} from './excerpts/index.js';\n","import type { Excerpt } from '../../sources/excerpts/schema.js';\nimport type {\n ClaimExtractionInput,\n ClaimExtractionResult,\n ClaimExtractorAdapter,\n DraftClaim,\n} from '../types.js';\n\nfunction normalize(s: string): string {\n return s.replace(/\\s+/g, ' ').toLowerCase().trim();\n}\n\n// For a given key_point, find the ledger excerpt that best matches it.\n// Preference order:\n// 1. Exact substring of key_point inside excerpt\n// 2. Exact substring of excerpt inside key_point\n// 3. First excerpt whose origin is key_point and whose text equals key_point\n// 4. null (no usable excerpt)\nfunction findExcerptForKeyPoint(keyPoint: string, excerpts: Excerpt[]): Excerpt | null {\n const norm = normalize(keyPoint);\n if (norm.length === 0) return null;\n for (const e of excerpts) {\n if (normalize(e.text).includes(norm)) return e;\n }\n for (const e of excerpts) {\n if (norm.includes(normalize(e.text))) return e;\n }\n return null;\n}\n\nexport class HeuristicClaimExtractor implements ClaimExtractorAdapter {\n readonly name = 'heuristic' as const;\n\n async available(): Promise<boolean> {\n return true;\n }\n\n async extract(input: ClaimExtractionInput): Promise<ClaimExtractionResult> {\n const card = input.sourceCard;\n const excerpts = input.excerpts;\n const keyPoints = card.key_points\n .map((kp) => kp.trim())\n .filter((kp) => kp.length > 0);\n\n const drafts: DraftClaim[] = [];\n if (keyPoints.length === 0) {\n // No key_points — fall back to source-card asserts paired with the\n // first available excerpt.\n const first = excerpts[0];\n if (first) {\n drafts.push({\n asserts: card.asserts,\n scope: null,\n not: null,\n evidence_excerpt_ids: [first.excerpt_id],\n evidence_location: first.location_hint,\n confidence: 'low',\n });\n }\n } else {\n let fallbackIdx = 0;\n for (const kp of keyPoints) {\n const matched = findExcerptForKeyPoint(kp, excerpts);\n const chosen = matched ?? excerpts[fallbackIdx % excerpts.length];\n if (!chosen) continue;\n if (!matched) fallbackIdx += 1;\n drafts.push({\n asserts: kp,\n scope: null,\n not: null,\n evidence_excerpt_ids: [chosen.excerpt_id],\n evidence_location: chosen.location_hint,\n confidence: 'low',\n });\n }\n }\n\n return { ok: true, claims: drafts, method: 'heuristic_key_point' };\n }\n}\n","import { renderLedgerForPrompt } from '../../sources/excerpts/ledger.js';\nimport { normalizeOllamaHost } from '../../sources/extractors/ollama-intern.js';\nimport type { Excerpt } from '../../sources/excerpts/schema.js';\nimport type {\n ClaimExtractionInput,\n ClaimExtractionResult,\n ClaimExtractorAdapter,\n Confidence,\n DraftClaim,\n} from '../types.js';\n\nconst DEFAULT_HOST = 'http://localhost:11434';\nconst DEFAULT_MODEL = 'hermes3:8b';\nconst DEFAULT_TIMEOUT_MS = 240_000;\n// Per-window character budget. Keeps the rendered ledger small enough that a\n// 12B-class model can return JSON within DEFAULT_TIMEOUT_MS even on a modest\n// rig. Larger ledgers are paged into multiple windows; claims are merged and\n// deduped after.\nconst DEFAULT_WINDOW_CHARS = 5_000;\n\n// Span-first extraction prompt. The model is shown a deterministic excerpt\n// ledger and asked to choose excerpt IDs — it must NOT author or paraphrase\n// evidence text. research-os copies the literal text from the ledger into the\n// claim's evidence_excerpt field.\nconst SYSTEM_PROMPT = `You are extracting atomic propositional claims from a source for a gated research pack. Return ONE JSON object: {\"claims\": [ ... ]}.\n\nEach claim is an atomic, source-grounded proposition that:\n- Asserts ONE thing\n- Could later be cited, challenged, scoped, contradicted, or promoted into synthesis\n- Is grounded in one or more LITERAL excerpt spans you select from the supplied ledger\n\nA claim is NOT a sentence, a paragraph summary, or a generic topic restatement.\n\nYou will be given a ledger of source spans, each with a stable ID like \"ex_abcdef012345_001\". Pick the IDs that ground each claim. DO NOT author or paraphrase evidence text. The system fills the literal text from the ledger after you respond.\n\nReturn 3 to 7 claims per source. For each claim:\n{\n \"asserts\": \"ONE sentence stating the proposition in your own words\",\n \"scope\": \"ONE sentence naming the contextual scope of the assertion (situation, system, domain). null ONLY if the source's wording is genuinely universal.\",\n \"not\": \"ONE sentence stating what this claim is explicitly NOT about, to prevent overgeneralization. null if no such limit can be inferred.\",\n \"evidence_excerpt_ids\": [\"ex_..._001\", \"ex_..._002\"], // 1 or more IDs FROM THE LEDGER. Required.\n \"evidence_location\": \"short locator like 'paragraph 3' / 'heading: Foo' / null\",\n \"confidence\": \"low\" | \"medium\" | \"high\"\n}\n\nHard rules:\n- Do not fabricate. Every excerpt ID must come from the supplied ledger verbatim.\n- Do not author or paraphrase evidence text — only cite excerpt IDs.\n- Do not widen scope beyond what the chosen spans actually say.\n- Do not synthesize across multiple claims into one — emit them separately.\n- If the source genuinely makes fewer than 3 distinct propositional claims, return whatever it actually makes.`;\n\nexport interface OllamaClaimConfig {\n host?: string;\n model?: string;\n timeoutMs?: number;\n // Per-window ledger character budget. Defaults to DEFAULT_WINDOW_CHARS.\n windowChars?: number;\n fetchImpl?: typeof fetch;\n}\n\ninterface ChatResponse {\n message?: { content?: string };\n response?: string;\n}\n\nfunction asConfidence(v: unknown): Confidence {\n if (v === 'low' || v === 'medium' || v === 'high') return v;\n return 'low';\n}\n\nfunction asStringOrNull(v: unknown): string | null {\n if (typeof v !== 'string') return null;\n const trimmed = v.trim();\n if (trimmed.length === 0) return null;\n if (trimmed.toLowerCase() === 'null') return null;\n return trimmed;\n}\n\nfunction asIdArray(v: unknown): string[] {\n if (!Array.isArray(v)) return [];\n const out: string[] = [];\n for (const x of v) {\n if (typeof x === 'string' && x.trim().length > 0) out.push(x.trim());\n }\n return out;\n}\n\n// Split an excerpt list into windows each under windowChars, never breaking\n// inside an excerpt. Deterministic — same input → same windows.\nexport function pageExcerpts(excerpts: Excerpt[], windowChars: number): Excerpt[][] {\n const windows: Excerpt[][] = [];\n let cursor: Excerpt[] = [];\n let cursorChars = 0;\n for (const ex of excerpts) {\n // Approximate the rendered cost: id + location_hint + ': ' + text + '\\n'\n const approxLine =\n ex.excerpt_id.length +\n (ex.location_hint ? ex.location_hint.length + 3 : 0) +\n 2 +\n ex.text.length +\n 1;\n if (cursor.length > 0 && cursorChars + approxLine > windowChars) {\n windows.push(cursor);\n cursor = [];\n cursorChars = 0;\n }\n cursor.push(ex);\n cursorChars += approxLine;\n }\n if (cursor.length > 0) windows.push(cursor);\n return windows;\n}\n\nexport class OllamaInternClaimExtractor implements ClaimExtractorAdapter {\n readonly name = 'ollama-intern' as const;\n private readonly host: string;\n private readonly model: string;\n private readonly timeoutMs: number;\n private readonly windowChars: number;\n private readonly fetchImpl: typeof fetch;\n\n constructor(config: OllamaClaimConfig = {}) {\n this.host = normalizeOllamaHost(config.host ?? process.env.OLLAMA_HOST ?? DEFAULT_HOST);\n this.model = config.model ?? process.env.OLLAMA_INTERN_MODEL ?? DEFAULT_MODEL;\n this.timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const envWindow = process.env.OLLAMA_INTERN_WINDOW_CHARS;\n this.windowChars =\n config.windowChars ??\n (envWindow ? parseInt(envWindow, 10) || DEFAULT_WINDOW_CHARS : DEFAULT_WINDOW_CHARS);\n this.fetchImpl = config.fetchImpl ?? globalThis.fetch;\n }\n\n async available(): Promise<boolean> {\n try {\n const ctrl = new AbortController();\n const t = setTimeout(() => ctrl.abort(), 1500);\n const res = await this.fetchImpl(`${this.host}/api/tags`, { signal: ctrl.signal });\n clearTimeout(t);\n if (!res.ok) return false;\n const body = (await res.json()) as { models?: Array<{ name: string }> };\n const names = (body.models ?? []).map((m) => m.name);\n const family = this.model.split(':')[0] ?? this.model;\n return names.some((n) => n === this.model || n === family || n.startsWith(`${family}:`));\n } catch {\n return false;\n }\n }\n\n // One LLM call against a single ledger window. Returns drafts or an error.\n // Errors here become page-level failures; the orchestrating extract() method\n // tolerates page failures and merges drafts from successful pages.\n private async extractOnePage(\n cardSummary: string,\n ledgerText: string,\n ): Promise<{ ok: true; drafts: DraftClaim[] } | { ok: false; error: string }> {\n const userMsg = `${cardSummary}\n\nEXCERPT LEDGER BEGIN\n${ledgerText}\nEXCERPT LEDGER END`;\n\n const ctrl = new AbortController();\n const t = setTimeout(() => ctrl.abort(), this.timeoutMs);\n let body: ChatResponse;\n try {\n const res = await this.fetchImpl(`${this.host}/api/chat`, {\n method: 'POST',\n signal: ctrl.signal,\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n model: this.model,\n stream: false,\n format: 'json',\n // Override Ollama's default 4096 context — the rendered ledger\n // window is sized in chars, but the prompt + system message can\n // easily exceed 4K tokens for hermes3:8b without this option,\n // and the silent server-side truncation eats excerpt IDs.\n options: { num_ctx: 8192 },\n messages: [\n { role: 'system', content: SYSTEM_PROMPT },\n { role: 'user', content: userMsg },\n ],\n }),\n });\n if (!res.ok) return { ok: false, error: `Ollama HTTP ${res.status}` };\n body = (await res.json()) as ChatResponse;\n } catch (err) {\n return { ok: false, error: err instanceof Error ? err.message : 'Ollama request failed' };\n } finally {\n clearTimeout(t);\n }\n\n const text = body.message?.content ?? body.response ?? '';\n let parsed: { claims?: unknown };\n try {\n parsed = JSON.parse(text) as { claims?: unknown };\n } catch {\n return { ok: false, error: 'Ollama response was not valid JSON' };\n }\n\n if (!Array.isArray(parsed.claims)) {\n return { ok: false, error: 'Ollama response did not contain a claims array' };\n }\n\n const drafts: DraftClaim[] = [];\n for (const raw of parsed.claims) {\n if (!raw || typeof raw !== 'object') continue;\n const r = raw as Record<string, unknown>;\n const asserts = asStringOrNull(r.asserts);\n const ids = asIdArray(r.evidence_excerpt_ids);\n if (!asserts || ids.length === 0) continue;\n drafts.push({\n asserts,\n scope: asStringOrNull(r.scope),\n not: asStringOrNull(r.not),\n evidence_excerpt_ids: ids,\n evidence_location: asStringOrNull(r.evidence_location),\n confidence: asConfidence(r.confidence),\n });\n }\n return { ok: true, drafts };\n }\n\n async extract(input: ClaimExtractionInput): Promise<ClaimExtractionResult> {\n if (input.excerpts.length === 0) {\n return { ok: false, error: 'No excerpts available; ledger is empty for this source' };\n }\n\n const card = input.sourceCard;\n const cardSummary = `URL: ${card.url}\nSource title: ${card.title}\nPublisher: ${card.publisher ?? 'unknown'}\nSource-card asserts: ${card.asserts}\nSource-card scope: ${card.scope ?? 'null'}\nSource-card not: ${card.not ?? 'null'}`;\n\n const windows = pageExcerpts(input.excerpts, this.windowChars);\n const allDrafts: DraftClaim[] = [];\n const pageErrors: string[] = [];\n let pagesOk = 0;\n for (const window of windows) {\n const ledgerText = renderLedgerForPrompt(window);\n const page = await this.extractOnePage(cardSummary, ledgerText);\n if (!page.ok) {\n pageErrors.push(page.error);\n continue;\n }\n pagesOk += 1;\n allDrafts.push(...page.drafts);\n }\n\n // If every page failed, surface the most common error so the caller sees\n // the right diagnostic (HTTP 500 vs JSON parse vs timeout).\n if (pagesOk === 0) {\n const summary =\n pageErrors.length === 1\n ? pageErrors[0]!\n : `all ${windows.length} ledger pages failed (first error: ${pageErrors[0] ?? 'unknown'})`;\n return { ok: false, error: summary };\n }\n\n // Dedup by normalised asserts — when the same theme appears in adjacent\n // windows the model often emits parallel claims.\n const seen = new Set<string>();\n const drafts: DraftClaim[] = [];\n for (const d of allDrafts) {\n const key = d.asserts.toLowerCase().replace(/\\s+/g, ' ').trim();\n if (seen.has(key)) continue;\n seen.add(key);\n drafts.push(d);\n }\n\n if (drafts.length === 0) {\n return { ok: false, error: 'Ollama returned no usable claims (all missing evidence_excerpt_ids)' };\n }\n\n const method =\n windows.length > 1 ? 'ollama_intern_propositional_paged' : 'ollama_intern_propositional';\n return { ok: true, claims: drafts, method };\n }\n}\n","import type { ClaimExtractorAdapter } from '../types.js';\nimport { HeuristicClaimExtractor } from './heuristic.js';\nimport { OllamaInternClaimExtractor } from './ollama-intern.js';\n\nexport { HeuristicClaimExtractor } from './heuristic.js';\nexport { OllamaInternClaimExtractor } from './ollama-intern.js';\n\nexport function defaultClaimExtractors(): ClaimExtractorAdapter[] {\n return [new OllamaInternClaimExtractor(), new HeuristicClaimExtractor()];\n}\n\nexport async function pickClaimExtractor(\n extractors: ClaimExtractorAdapter[],\n): Promise<ClaimExtractorAdapter> {\n for (const e of extractors) {\n if (await e.available()) return e;\n }\n throw new Error(\n 'No claim extractor available. The HeuristicClaimExtractor should always be available — this indicates a bug.',\n );\n}\n","import { z } from 'zod';\n\nimport { EXCERPT_ID_PATTERN } from '../sources/excerpts/schema.js';\n\nexport const ConfidenceSchema = z.enum(['low', 'medium', 'high']);\n\nexport const ClaimExtractorSchema = z.enum(['heuristic', 'ollama-intern']);\n\nexport const ReviewStateSchema = z.enum([\n 'candidate',\n 'gated',\n 'reviewed',\n 'rejected',\n 'accepted',\n]);\n\nexport const ClaimSchema = z.object({\n claim_id: z.string().regex(/^clm_[a-f0-9]{12}_(heuristic|ollama_intern)_\\d+$/),\n section_id: z.string().regex(/^[0-9]{2}-[a-z0-9-]+$/),\n source_ids: z\n .array(z.string().regex(/^src_[a-f0-9]{12}$/))\n .min(1, 'every claim must reference at least one source_id'),\n source_hashes: z.array(z.string().regex(/^[a-f0-9]{64}$/)),\n asserts: z.string().min(1),\n scope: z.string().nullable(),\n not: z.string().nullable(),\n // Span-first extraction: the model picks excerpt IDs from the deterministic\n // ledger; research-os copies the literal text into evidence_excerpt. Models\n // may interpret source spans; they may not author evidence spans.\n // Allowed empty for legacy claims that pre-date span-first extraction —\n // those should be re-extracted; new writes always populate at least one ID.\n evidence_excerpt_ids: z.array(z.string().regex(EXCERPT_ID_PATTERN)).default([]),\n evidence_excerpt: z.string().min(1),\n evidence_location: z.string().nullable(),\n confidence: ConfidenceSchema,\n extractor: ClaimExtractorSchema,\n extraction_method: z.string().min(1),\n created_at: z.string(),\n review_state: ReviewStateSchema,\n});\n\nexport type Claim = z.infer<typeof ClaimSchema>;\n","import { existsSync } from 'node:fs';\nimport { appendFile, mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { join, resolve } from 'node:path';\n\nimport {\n NoSourcesGatheredError,\n PackNotFoundError,\n SectionNotFoundError,\n} from '../errors.js';\nimport { RESEARCH_OS_VERSION } from '../index.js';\nimport {\n buildExcerptIndex,\n EXCERPT_ID_PATTERN,\n loadOrBuildLedger,\n type Excerpt,\n} from '../sources/excerpts/index.js';\nimport {\n FetchReceiptSchema,\n SourceCardSchema,\n type FetchReceipt,\n type SourceCard,\n} from '../sources/schema.js';\nimport { defaultClaimExtractors, pickClaimExtractor } from './extractors/index.js';\nimport { ClaimSchema, type Claim } from './schema.js';\nimport type {\n ClaimExtractor,\n DraftClaim,\n ExtractClaimsOptions,\n ExtractClaimsSummary,\n} from './types.js';\n\nconst MIN_EXCERPT_LEN_FOR_GROUNDING = 8;\nconst EVIDENCE_EXCERPT_JOIN = ' … ';\nconst EVIDENCE_EXCERPT_MAX_CHARS = 1200;\n\nfunction normalize(text: string): string {\n return text.replace(/<[^>]+>/g, ' ').replace(/\\s+/g, ' ').toLowerCase().trim();\n}\n\n// Legacy text-substring grounding check, retained for callers that still need it\n// (e.g. reviewer post-checks). Span-first extraction does NOT use this — claims\n// are grounded by excerpt-id resolution against the ledger instead.\nexport function evidenceGrounded(excerpt: string, rawText: string | null): boolean {\n if (!rawText) return false;\n const e = normalize(excerpt);\n if (e.length < MIN_EXCERPT_LEN_FOR_GROUNDING) return false;\n return normalize(rawText).includes(e);\n}\n\nconst EXTRACTOR_ID_PART: Record<ClaimExtractor, string> = {\n heuristic: 'heuristic',\n 'ollama-intern': 'ollama_intern',\n};\n\ninterface SectionSourceEntry {\n source_id: string;\n}\n\nasync function readSectionSourceIds(\n packPath: string,\n sectionId: string,\n): Promise<string[]> {\n const path = join(packPath, 'sections', sectionId, 'sources.jsonl');\n if (!existsSync(path)) return [];\n const text = await readFile(path, 'utf8');\n const ids: string[] = [];\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n const entry = JSON.parse(line) as SectionSourceEntry;\n if (typeof entry.source_id === 'string') ids.push(entry.source_id);\n } catch {\n /* skip malformed line */\n }\n }\n return ids;\n}\n\nasync function readSourceCard(packPath: string, sourceId: string): Promise<SourceCard | null> {\n const path = join(packPath, 'evidence', 'source-cards', `${sourceId}.json`);\n if (!existsSync(path)) return null;\n const text = await readFile(path, 'utf8');\n return SourceCardSchema.parse(JSON.parse(text));\n}\n\nasync function findLatestReceipt(\n packPath: string,\n sourceId: string,\n): Promise<FetchReceipt | null> {\n const path = join(packPath, 'evidence', 'fetch-log.jsonl');\n if (!existsSync(path)) return null;\n const text = await readFile(path, 'utf8');\n let latest: FetchReceipt | null = null;\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n const r = FetchReceiptSchema.parse(JSON.parse(line));\n if (r.source_id !== sourceId) continue;\n if (r.fetch_outcome !== 'ok') continue;\n if (!latest || r.fetched_at > latest.fetched_at) latest = r;\n } catch {\n /* skip malformed */\n }\n }\n return latest;\n}\n\nasync function readExistingClaimIds(\n packPath: string,\n sectionId: string,\n): Promise<Set<string>> {\n const path = join(packPath, 'sections', sectionId, 'claims.jsonl');\n if (!existsSync(path)) return new Set();\n const text = await readFile(path, 'utf8');\n const set = new Set<string>();\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n const obj = JSON.parse(line) as { claim_id?: string };\n if (typeof obj.claim_id === 'string') set.add(obj.claim_id);\n } catch {\n /* skip */\n }\n }\n return set;\n}\n\ninterface ResolveResult {\n ok: boolean;\n evidenceText: string;\n resolvedIds: string[];\n failureMode: 'excerpt_id_missing' | 'excerpt_id_malformed' | null;\n}\n\nfunction resolveExcerpts(\n rawIds: string[],\n index: Map<string, Excerpt>,\n): ResolveResult {\n if (!Array.isArray(rawIds) || rawIds.length === 0) {\n return { ok: false, evidenceText: '', resolvedIds: [], failureMode: 'excerpt_id_missing' };\n }\n const resolvedIds: string[] = [];\n const texts: string[] = [];\n for (const idRaw of rawIds) {\n const id = String(idRaw).trim();\n if (!EXCERPT_ID_PATTERN.test(id)) {\n return { ok: false, evidenceText: '', resolvedIds: [], failureMode: 'excerpt_id_malformed' };\n }\n const ex = index.get(id);\n if (!ex) {\n return { ok: false, evidenceText: '', resolvedIds: [], failureMode: 'excerpt_id_missing' };\n }\n if (!resolvedIds.includes(id)) {\n resolvedIds.push(id);\n texts.push(ex.text);\n }\n }\n let combined = texts.join(EVIDENCE_EXCERPT_JOIN);\n if (combined.length > EVIDENCE_EXCERPT_MAX_CHARS) {\n combined = combined.slice(0, EVIDENCE_EXCERPT_MAX_CHARS - 2).trimEnd() + ' …';\n }\n if (combined.length === 0) {\n return { ok: false, evidenceText: '', resolvedIds: [], failureMode: 'excerpt_id_missing' };\n }\n return { ok: true, evidenceText: combined, resolvedIds, failureMode: null };\n}\n\nfunction buildClaim(args: {\n draft: DraftClaim;\n evidenceText: string;\n resolvedExcerptIds: string[];\n index: number;\n sectionId: string;\n sourceId: string;\n sourceHash: string | null;\n extractor: ClaimExtractor;\n extractionMethod: string;\n}): Claim {\n const {\n draft,\n evidenceText,\n resolvedExcerptIds,\n index,\n sectionId,\n sourceId,\n sourceHash,\n extractor,\n extractionMethod,\n } = args;\n const idPart = EXTRACTOR_ID_PART[extractor];\n const claimId = `clm_${sourceId.replace(/^src_/, '')}_${idPart}_${index + 1}`;\n return ClaimSchema.parse({\n claim_id: claimId,\n section_id: sectionId,\n source_ids: [sourceId],\n source_hashes: sourceHash ? [sourceHash] : [],\n asserts: draft.asserts,\n scope: draft.scope,\n not: draft.not,\n evidence_excerpt_ids: resolvedExcerptIds,\n evidence_excerpt: evidenceText,\n evidence_location: draft.evidence_location,\n confidence: draft.confidence,\n extractor,\n extraction_method: extractionMethod,\n created_at: new Date().toISOString(),\n review_state: 'candidate',\n });\n}\n\nexport async function extract(options: ExtractClaimsOptions): Promise<ExtractClaimsSummary> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n if (!existsSync(join(packPath, 'research.yaml'))) throw new PackNotFoundError(packPath);\n if (!existsSync(join(packPath, 'sections', options.sectionId)))\n throw new SectionNotFoundError(options.sectionId);\n\n const sourceIds = await readSectionSourceIds(packPath, options.sectionId);\n if (sourceIds.length === 0) throw new NoSourcesGatheredError(options.sectionId);\n\n const adapters = options.extractors ?? defaultClaimExtractors();\n const extractor = await pickClaimExtractor(adapters);\n\n const claimsPath = join(packPath, 'sections', options.sectionId, 'claims.jsonl');\n const existingIds = await readExistingClaimIds(packPath, options.sectionId);\n\n const summary: ExtractClaimsSummary = {\n sectionId: options.sectionId,\n extractor: extractor.name,\n extractionMethod: '',\n sourcesProcessed: 0,\n sourcesSkipped: 0,\n sourcesFailed: 0,\n excerptLedgersBuilt: 0,\n claimsAdded: 0,\n claimsDeduped: 0,\n claimsRejectedUngrounded: 0,\n claimsRejectedExcerptIdMissing: 0,\n claimsRejectedExcerptIdMalformed: 0,\n claimsRejectedScopeMissing: 0,\n claimsRejectedExtractorParaphrase: 0,\n claimIds: [],\n failures: [],\n };\n\n for (const sourceId of sourceIds) {\n const card = await readSourceCard(packPath, sourceId);\n if (!card) {\n summary.sourcesSkipped += 1;\n continue;\n }\n const receipt = await findLatestReceipt(packPath, sourceId);\n let rawText: string | null = null;\n if (receipt?.raw_text_path) {\n const raw = join(packPath, receipt.raw_text_path);\n if (existsSync(raw)) {\n rawText = await readFile(raw, 'utf8');\n }\n }\n\n const ledger = await loadOrBuildLedger({\n packPath,\n sourceCard: card,\n sourceHash: receipt?.sha256 ?? null,\n rawText,\n });\n if (ledger.built) summary.excerptLedgersBuilt += 1;\n\n if (ledger.excerpts.length === 0) {\n // No spans available — extractor cannot produce span-first claims.\n summary.sourcesSkipped += 1;\n continue;\n }\n\n const result = await extractor.extract({\n sourceCard: card,\n sourceHash: receipt?.sha256 ?? null,\n excerpts: ledger.excerpts,\n });\n\n if (!result.ok) {\n summary.sourcesFailed += 1;\n summary.failures.push({ source_id: sourceId, reason: result.error });\n continue;\n }\n\n summary.sourcesProcessed += 1;\n summary.extractionMethod = result.method;\n\n const excerptIndex = buildExcerptIndex(ledger.excerpts);\n\n let writtenIndex = 0;\n for (let i = 0; i < result.claims.length; i += 1) {\n const draft = result.claims[i]!;\n const resolved = resolveExcerpts(draft.evidence_excerpt_ids, excerptIndex);\n if (!resolved.ok) {\n summary.claimsRejectedUngrounded += 1;\n if (resolved.failureMode === 'excerpt_id_missing') {\n summary.claimsRejectedExcerptIdMissing += 1;\n } else if (resolved.failureMode === 'excerpt_id_malformed') {\n summary.claimsRejectedExcerptIdMalformed += 1;\n }\n continue;\n }\n const claim = buildClaim({\n draft,\n evidenceText: resolved.evidenceText,\n resolvedExcerptIds: resolved.resolvedIds,\n index: writtenIndex,\n sectionId: options.sectionId,\n sourceId,\n sourceHash: receipt?.sha256 ?? null,\n extractor: extractor.name,\n extractionMethod: result.method,\n });\n writtenIndex += 1;\n if (existingIds.has(claim.claim_id)) {\n summary.claimsDeduped += 1;\n continue;\n }\n await appendFile(claimsPath, JSON.stringify(claim) + '\\n', 'utf8');\n existingIds.add(claim.claim_id);\n summary.claimsAdded += 1;\n summary.claimIds.push(claim.claim_id);\n }\n }\n\n // Persist a small extraction receipt next to the section's other audit\n // outputs. The section report reads this for the Extraction panel.\n const receipt = {\n receipt_id: `cle_${Date.now()}_${options.sectionId}`,\n section_id: options.sectionId,\n extracted_at: new Date().toISOString(),\n research_os_version: RESEARCH_OS_VERSION,\n extractor: summary.extractor,\n extraction_method: summary.extractionMethod,\n sources_processed: summary.sourcesProcessed,\n sources_skipped: summary.sourcesSkipped,\n sources_failed: summary.sourcesFailed,\n excerpt_ledgers_built: summary.excerptLedgersBuilt,\n claims_added: summary.claimsAdded,\n claims_deduped: summary.claimsDeduped,\n claims_rejected_ungrounded: summary.claimsRejectedUngrounded,\n claims_rejected_excerpt_id_missing: summary.claimsRejectedExcerptIdMissing,\n claims_rejected_excerpt_id_malformed: summary.claimsRejectedExcerptIdMalformed,\n failures: summary.failures.map((f) => ({\n source_id: f.source_id,\n reason: f.reason,\n // Tag transport / parse failures so the report can bucket them.\n kind: /not valid JSON/i.test(f.reason)\n ? 'extractor_invalid_json'\n : /aborted|timeout/i.test(f.reason)\n ? 'extractor_timeout'\n : /HTTP \\d{3}/i.test(f.reason)\n ? 'extractor_http_error'\n : 'extractor_other',\n })),\n };\n const auditsDir = join(packPath, 'audits');\n await mkdir(auditsDir, { recursive: true });\n await writeFile(\n join(auditsDir, `${options.sectionId}-claim-extract.json`),\n JSON.stringify(receipt, null, 2),\n 'utf8',\n );\n\n return summary;\n}\n","import { z } from 'zod';\n\n// A claim density audit reports how dense and redundant a section's\n// candidate claim ledger is, BEFORE review runs. It surfaces signals the\n// reviewer can route into claim_overproduction findings (or that a human\n// can use to decide whether to consolidate the ledger by hand).\n//\n// Span-first + paged extraction can yield individually-grounded but\n// collectively-noisy claim sets. This audit measures that without\n// touching the canonical artifacts.\n\nexport const PerSourceDensitySchema = z.object({\n source_id: z.string().regex(/^src_[a-f0-9]{12}$/),\n publisher: z.string().nullable(),\n source_word_count: z.number().int().nonnegative(),\n claim_count: z.number().int().nonnegative(),\n claims_per_1k_words: z.number(),\n share_of_section: z.number(), // 0..1\n weak_scope_count: z.number().int().nonnegative(),\n generic_scope_count: z.number().int().nonnegative(),\n});\n\nexport const NearDuplicateClusterSchema = z.object({\n representative_assert: z.string(),\n member_count: z.number().int().nonnegative(),\n claim_ids: z.array(z.string().regex(/^clm_[a-f0-9]{12}_(heuristic|ollama_intern)_\\d+$/)),\n});\n\nexport const DensityFlagSchema = z.object({\n type: z.enum([\n 'source_dominance',\n 'high_per_word_density',\n 'large_near_duplicate_cluster',\n 'weak_scope_majority',\n ]),\n severity: z.enum(['info', 'warn', 'block']),\n message: z.string(),\n affects_source_ids: z.array(z.string().regex(/^src_[a-f0-9]{12}$/)).default([]),\n affects_claim_ids: z\n .array(z.string().regex(/^clm_[a-f0-9]{12}_(heuristic|ollama_intern)_\\d+$/))\n .default([]),\n});\n\nexport const ClaimDensityAuditSchema = z.object({\n audit_id: z.string().regex(/^cda_[0-9]+_[a-z0-9-]+$/),\n section_id: z.string().regex(/^[0-9]{2}-[a-z0-9-]+$/),\n audited_at: z.string(),\n research_os_version: z.string(),\n candidate_claim_count: z.number().int().nonnegative(),\n source_count: z.number().int().nonnegative(),\n total_source_word_count: z.number().int().nonnegative(),\n claims_per_1k_words: z.number(),\n weak_scope_count: z.number().int().nonnegative(),\n generic_scope_count: z.number().int().nonnegative(),\n per_source: z.array(PerSourceDensitySchema),\n near_duplicate_clusters: z.array(NearDuplicateClusterSchema),\n flags: z.array(DensityFlagSchema),\n});\n\nexport type PerSourceDensity = z.infer<typeof PerSourceDensitySchema>;\nexport type NearDuplicateCluster = z.infer<typeof NearDuplicateClusterSchema>;\nexport type DensityFlag = z.infer<typeof DensityFlagSchema>;\nexport type ClaimDensityAudit = z.infer<typeof ClaimDensityAuditSchema>;\n","import { existsSync } from 'node:fs';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { join, resolve } from 'node:path';\n\nimport { PackNotFoundError, SectionNotFoundError } from '../../errors.js';\nimport { RESEARCH_OS_VERSION } from '../../index.js';\nimport {\n FetchReceiptSchema,\n SourceCardSchema,\n type FetchReceipt,\n type SourceCard,\n} from '../../sources/schema.js';\nimport { ClaimSchema, type Claim } from '../schema.js';\nimport {\n ClaimDensityAuditSchema,\n type ClaimDensityAudit,\n type DensityFlag,\n type NearDuplicateCluster,\n type PerSourceDensity,\n} from './schema.js';\n\nexport interface AuditDensityOptions {\n sectionId: string;\n packPath?: string;\n now?: () => Date;\n}\n\nexport interface AuditDensityResult {\n audit: ClaimDensityAudit;\n jsonPath: string;\n markdownPath: string;\n}\n\nconst NEAR_DUP_CLUSTER_MIN = 3;\nconst SOURCE_DOMINANCE_RATIO = 0.4;\nconst SOURCE_DOMINANCE_MIN_TOTAL = 10;\nconst SOURCE_DOMINANCE_MIN_PER_SOURCE = 8;\nconst HIGH_DENSITY_PER_1K = 5;\nconst WEAK_SCOPE_MAJORITY_RATIO = 0.5;\n\nfunction normalize(s: string): string {\n return s\n .replace(/<[^>]+>/g, ' ')\n .replace(/\\s+/g, ' ')\n .toLowerCase()\n .replace(/[^a-z0-9 ]+/g, ' ')\n .replace(/\\s+/g, ' ')\n .trim();\n}\n\nfunction countWords(text: string): number {\n if (!text) return 0;\n return normalize(text).split(' ').filter((w) => w.length > 0).length;\n}\n\nasync function readClaims(packPath: string, sectionId: string): Promise<Claim[]> {\n const path = join(packPath, 'sections', sectionId, 'claims.jsonl');\n if (!existsSync(path)) return [];\n const text = await readFile(path, 'utf8');\n const out: Claim[] = [];\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n out.push(ClaimSchema.parse(JSON.parse(line)));\n } catch {\n /* skip malformed line */\n }\n }\n return out;\n}\n\nasync function readSourceCards(\n packPath: string,\n sourceIds: string[],\n): Promise<Map<string, SourceCard>> {\n const out = new Map<string, SourceCard>();\n for (const sid of sourceIds) {\n const p = join(packPath, 'evidence', 'source-cards', `${sid}.json`);\n if (!existsSync(p)) continue;\n try {\n out.set(sid, SourceCardSchema.parse(JSON.parse(await readFile(p, 'utf8'))));\n } catch {\n /* skip malformed */\n }\n }\n return out;\n}\n\nasync function readLatestReceipts(packPath: string): Promise<Map<string, FetchReceipt>> {\n const out = new Map<string, FetchReceipt>();\n const path = join(packPath, 'evidence', 'fetch-log.jsonl');\n if (!existsSync(path)) return out;\n const text = await readFile(path, 'utf8');\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n const r = FetchReceiptSchema.parse(JSON.parse(line));\n if (r.fetch_outcome !== 'ok') continue;\n const prev = out.get(r.source_id);\n if (!prev || prev.fetched_at < r.fetched_at) out.set(r.source_id, r);\n } catch {\n /* skip */\n }\n }\n return out;\n}\n\nasync function readRawText(packPath: string, receipt: FetchReceipt): Promise<string | null> {\n if (!receipt.raw_text_path) return null;\n const p = join(packPath, receipt.raw_text_path);\n if (!existsSync(p)) return null;\n return await readFile(p, 'utf8');\n}\n\n// A claim's scope is \"weak\" when scope is null AND not is null AND asserts > 40 chars.\nfunction isWeakScope(claim: Claim): boolean {\n return claim.scope === null && claim.not === null && claim.asserts.length > 40;\n}\n\n// A claim's scope is \"generic source\" when scope is non-null but quotes the\n// source title or topic without adding situational context. Heuristic: scope\n// length is short AND a substantial fraction of the scope tokens appear in the\n// source-card title (case-insensitive).\nfunction isGenericScope(claim: Claim, sourceTitle: string | null): boolean {\n if (!claim.scope || !sourceTitle) return false;\n if (claim.scope.length > 80) return false;\n const titleTokens = new Set(normalize(sourceTitle).split(' ').filter((t) => t.length > 3));\n const scopeTokens = normalize(claim.scope).split(' ').filter((t) => t.length > 3);\n if (scopeTokens.length === 0) return false;\n const overlap = scopeTokens.filter((t) => titleTokens.has(t)).length;\n return overlap / scopeTokens.length >= 0.5;\n}\n\nfunction buildClusters(claims: Claim[]): NearDuplicateCluster[] {\n const buckets = new Map<string, Claim[]>();\n for (const c of claims) {\n const key = normalize(c.asserts);\n if (key.length === 0) continue;\n const arr = buckets.get(key) ?? [];\n arr.push(c);\n buckets.set(key, arr);\n }\n const clusters: NearDuplicateCluster[] = [];\n for (const [, members] of buckets) {\n if (members.length >= NEAR_DUP_CLUSTER_MIN) {\n clusters.push({\n representative_assert: members[0]!.asserts.slice(0, 240),\n member_count: members.length,\n claim_ids: members.map((m) => m.claim_id),\n });\n }\n }\n // Sort largest cluster first.\n clusters.sort((a, b) => b.member_count - a.member_count);\n return clusters;\n}\n\nfunction buildFlags(audit: Omit<ClaimDensityAudit, 'flags'>): DensityFlag[] {\n const flags: DensityFlag[] = [];\n // source_dominance\n for (const s of audit.per_source) {\n if (\n s.claim_count >= 30 ||\n (audit.candidate_claim_count >= SOURCE_DOMINANCE_MIN_TOTAL &&\n s.claim_count >= SOURCE_DOMINANCE_MIN_PER_SOURCE &&\n s.share_of_section >= SOURCE_DOMINANCE_RATIO)\n ) {\n const severity = s.claim_count >= 50 || s.share_of_section >= 0.6 ? 'block' : 'warn';\n flags.push({\n type: 'source_dominance',\n severity,\n message: `Source ${s.source_id} contributes ${s.claim_count} of ${audit.candidate_claim_count} claims (${(s.share_of_section * 100).toFixed(0)}% of section).`,\n affects_source_ids: [s.source_id],\n affects_claim_ids: [],\n });\n }\n }\n // high_per_word_density (per-source)\n for (const s of audit.per_source) {\n if (s.source_word_count > 0 && s.claims_per_1k_words >= HIGH_DENSITY_PER_1K) {\n flags.push({\n type: 'high_per_word_density',\n severity: 'warn',\n message: `Source ${s.source_id} has ${s.claims_per_1k_words.toFixed(1)} claims per 1k source words — likely over-atomization.`,\n affects_source_ids: [s.source_id],\n affects_claim_ids: [],\n });\n }\n }\n // weak_scope_majority\n if (\n audit.candidate_claim_count > 0 &&\n audit.weak_scope_count / audit.candidate_claim_count >= WEAK_SCOPE_MAJORITY_RATIO\n ) {\n flags.push({\n type: 'weak_scope_majority',\n severity: 'warn',\n message: `${audit.weak_scope_count} of ${audit.candidate_claim_count} claims (${((audit.weak_scope_count / audit.candidate_claim_count) * 100).toFixed(0)}%) carry no scope and no not constraint.`,\n affects_source_ids: [],\n affects_claim_ids: [],\n });\n }\n return flags;\n}\n\nfunction buildMarkdown(audit: ClaimDensityAudit): string {\n const lines: string[] = [];\n lines.push(`# Claim density audit: ${audit.section_id}`);\n lines.push('');\n lines.push(`- **Audit ID:** \\`${audit.audit_id}\\``);\n lines.push(`- **Audited at:** ${audit.audited_at}`);\n lines.push(`- **research-os version:** ${audit.research_os_version}`);\n lines.push(`- **Candidate claims:** ${audit.candidate_claim_count}`);\n lines.push(`- **Sources:** ${audit.source_count}`);\n lines.push(`- **Total source words:** ${audit.total_source_word_count.toLocaleString()}`);\n lines.push(`- **Claims per 1k source words (section):** ${audit.claims_per_1k_words.toFixed(2)}`);\n lines.push(`- **Weak-scope claims (scope=null, not=null, substantive asserts):** ${audit.weak_scope_count}`);\n lines.push(`- **Generic-scope claims (scope mirrors source title):** ${audit.generic_scope_count}`);\n lines.push('');\n\n lines.push(`## Flags (${audit.flags.length})`);\n lines.push('');\n if (audit.flags.length === 0) {\n lines.push('_No density flags raised. Section claim ledger looks proportionate._');\n } else {\n lines.push('| Type | Severity | Message |');\n lines.push('|---|---|---|');\n for (const f of audit.flags) {\n lines.push(`| \\`${f.type}\\` | ${f.severity} | ${f.message.replace(/\\|/g, '\\\\|')} |`);\n }\n }\n lines.push('');\n\n lines.push(`## Per source (${audit.per_source.length})`);\n lines.push('');\n if (audit.per_source.length === 0) {\n lines.push('_No sources contributed claims._');\n } else {\n lines.push('| Source | Words | Claims | Per 1k words | Share | Weak scope | Generic scope |');\n lines.push('|---|---:|---:|---:|---:|---:|---:|');\n for (const s of audit.per_source) {\n lines.push(\n `| \\`${s.source_id}\\`${s.publisher ? ` (${s.publisher})` : ''} | ${s.source_word_count.toLocaleString()} | ${s.claim_count} | ${s.claims_per_1k_words.toFixed(2)} | ${(s.share_of_section * 100).toFixed(0)}% | ${s.weak_scope_count} | ${s.generic_scope_count} |`,\n );\n }\n }\n lines.push('');\n\n lines.push(`## Near-duplicate clusters (>= ${NEAR_DUP_CLUSTER_MIN} members) — ${audit.near_duplicate_clusters.length}`);\n lines.push('');\n if (audit.near_duplicate_clusters.length === 0) {\n lines.push('_No near-duplicate clusters detected._');\n } else {\n lines.push('Each row is a cluster of claims whose normalised assertions collapse to the same key.');\n lines.push('');\n lines.push('| Members | Representative assertion |');\n lines.push('|---:|---|');\n for (const c of audit.near_duplicate_clusters) {\n lines.push(`| ${c.member_count} | ${c.representative_assert.replace(/\\|/g, '\\\\|')} |`);\n }\n }\n lines.push('');\n lines.push('---');\n lines.push('');\n lines.push('_This audit is read-only. The reviewer (Link 7) decides which claims are accepted, rejected, or flagged for collapse via `claim_overproduction` findings._');\n return lines.join('\\n');\n}\n\nexport async function auditDensity(\n options: AuditDensityOptions,\n): Promise<AuditDensityResult> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n if (!existsSync(join(packPath, 'research.yaml'))) throw new PackNotFoundError(packPath);\n if (!existsSync(join(packPath, 'sections', options.sectionId)))\n throw new SectionNotFoundError(options.sectionId);\n\n const claims = await readClaims(packPath, options.sectionId);\n const allSourceIds = Array.from(\n new Set(claims.flatMap((c) => c.source_ids)),\n ).sort();\n const cards = await readSourceCards(packPath, allSourceIds);\n const receipts = await readLatestReceipts(packPath);\n\n // Source word counts via raw text (preferred) or fallback to source-card asserts.\n const wordsBySource = new Map<string, number>();\n for (const sid of allSourceIds) {\n let words = 0;\n const r = receipts.get(sid);\n if (r) {\n const raw = await readRawText(packPath, r);\n if (raw) words = countWords(raw);\n }\n if (words === 0) {\n const card = cards.get(sid);\n if (card) words = countWords(card.asserts);\n }\n wordsBySource.set(sid, words);\n }\n\n // Per-source aggregations.\n const perSource: PerSourceDensity[] = [];\n let totalWords = 0;\n let weakTotal = 0;\n let genericTotal = 0;\n for (const sid of allSourceIds) {\n const claimsHere = claims.filter((c) => c.source_ids.includes(sid));\n const words = wordsBySource.get(sid) ?? 0;\n totalWords += words;\n const card = cards.get(sid) ?? null;\n const weak = claimsHere.filter(isWeakScope).length;\n const generic = claimsHere.filter((c) => isGenericScope(c, card?.title ?? null)).length;\n weakTotal += weak;\n genericTotal += generic;\n perSource.push({\n source_id: sid,\n publisher: card?.publisher ?? null,\n source_word_count: words,\n claim_count: claimsHere.length,\n claims_per_1k_words: words > 0 ? (claimsHere.length / words) * 1000 : 0,\n share_of_section: claims.length > 0 ? claimsHere.length / claims.length : 0,\n weak_scope_count: weak,\n generic_scope_count: generic,\n });\n }\n perSource.sort((a, b) => b.claim_count - a.claim_count);\n\n const clusters = buildClusters(claims);\n\n const stamp = (options.now ?? (() => new Date()))();\n const auditId = `cda_${stamp.getTime()}_${options.sectionId}`;\n\n const partial: Omit<ClaimDensityAudit, 'flags'> = {\n audit_id: auditId,\n section_id: options.sectionId,\n audited_at: stamp.toISOString(),\n research_os_version: RESEARCH_OS_VERSION,\n candidate_claim_count: claims.length,\n source_count: allSourceIds.length,\n total_source_word_count: totalWords,\n claims_per_1k_words: totalWords > 0 ? (claims.length / totalWords) * 1000 : 0,\n weak_scope_count: weakTotal,\n generic_scope_count: genericTotal,\n per_source: perSource,\n near_duplicate_clusters: clusters,\n };\n // Also flag clusters of >= NEAR_DUP_CLUSTER_MIN as a section-level signal.\n const clusterFlags: DensityFlag[] = clusters.map((c) => ({\n type: 'large_near_duplicate_cluster',\n severity: c.member_count >= 6 ? 'block' : 'warn',\n message: `Cluster of ${c.member_count} claims share a normalised assertion: \"${c.representative_assert.slice(0, 120)}\".`,\n affects_source_ids: [],\n affects_claim_ids: c.claim_ids,\n }));\n const flags = [...buildFlags(partial), ...clusterFlags];\n const audit: ClaimDensityAudit = ClaimDensityAuditSchema.parse({ ...partial, flags });\n\n // Write audits/<section>-claim-density.{json,md}.\n const auditsDir = join(packPath, 'audits');\n await mkdir(auditsDir, { recursive: true });\n const jsonPath = join(auditsDir, `${options.sectionId}-claim-density.json`);\n const markdownPath = join(auditsDir, `${options.sectionId}-claim-density.md`);\n await writeFile(jsonPath, JSON.stringify(audit, null, 2), 'utf8');\n await writeFile(markdownPath, buildMarkdown(audit), 'utf8');\n\n return { audit, jsonPath, markdownPath };\n}\n","export { auditDensity, type AuditDensityOptions, type AuditDensityResult } from './run.js';\nexport {\n ClaimDensityAuditSchema,\n PerSourceDensitySchema,\n NearDuplicateClusterSchema,\n DensityFlagSchema,\n type ClaimDensityAudit,\n type PerSourceDensity,\n type NearDuplicateCluster,\n type DensityFlag,\n} from './schema.js';\n","export { extract, evidenceGrounded } from './extract.js';\nexport {\n auditDensity,\n ClaimDensityAuditSchema,\n PerSourceDensitySchema,\n NearDuplicateClusterSchema,\n DensityFlagSchema,\n type ClaimDensityAudit,\n type PerSourceDensity,\n type NearDuplicateCluster,\n type DensityFlag,\n type AuditDensityOptions,\n type AuditDensityResult,\n} from './density/index.js';\nexport {\n HeuristicClaimExtractor,\n OllamaInternClaimExtractor,\n defaultClaimExtractors,\n pickClaimExtractor,\n} from './extractors/index.js';\nexport {\n ClaimSchema,\n ConfidenceSchema,\n ClaimExtractorSchema,\n ReviewStateSchema,\n type Claim,\n} from './schema.js';\nexport type {\n ClaimExtractor,\n ClaimExtractorAdapter,\n ClaimExtractionInput,\n ClaimExtractionResult,\n Confidence,\n DraftClaim,\n ExtractClaimsOptions,\n ExtractClaimsSummary,\n ReviewState,\n SourceFetchPair,\n} from './types.js';\n","import { z } from 'zod';\n\nexport const ContradictionTypeSchema = z.enum([\n 'direct_conflict',\n 'scope_conflict',\n 'temporal_conflict',\n 'definition_conflict',\n 'evidence_conflict',\n 'overgeneralization_risk',\n]);\n\nexport const SeveritySchema = z.enum(['low', 'medium', 'high', 'blocking']);\n\nexport const OverlapAssessmentSchema = z.enum([\n 'fully_overlapping',\n 'partially_overlapping',\n 'non_overlapping',\n 'unknown',\n]);\n\nexport const ContradictionDetectorSchema = z.enum(['heuristic', 'ollama-intern']);\n\nexport const ContradictionStatusSchema = z.enum([\n 'unresolved',\n 'reconciled',\n 'preserved_deliberately',\n 'rejected',\n]);\n\nexport const ContradictionConfidenceSchema = z.enum(['low', 'medium', 'high']);\n\nexport const ContradictionSchema = z.object({\n contradiction_id: z.string().regex(/^cnt_[a-f0-9]{12}_(heuristic|ollama_intern)$/),\n section_id: z.string().regex(/^[0-9]{2}-[a-z0-9-]+$/),\n claim_ids: z\n .array(z.string().regex(/^clm_[a-f0-9]{12}_(heuristic|ollama_intern)_\\d+$/))\n .length(2, 'contradictions are pair-wise in v0.1'),\n source_ids: z.array(z.string().regex(/^src_[a-f0-9]{12}$/)).min(1),\n type: ContradictionTypeSchema,\n summary: z.string().min(1),\n scope_analysis: z.string(),\n overlap_assessment: OverlapAssessmentSchema,\n severity: SeveritySchema,\n confidence: ContradictionConfidenceSchema,\n detector: ContradictionDetectorSchema,\n detection_method: z.string().min(1),\n evidence: z.string(),\n status: ContradictionStatusSchema,\n created_at: z.string(),\n});\n\nexport type Contradiction = z.infer<typeof ContradictionSchema>;\n","import type { OverlapAssessment } from './types.js';\n\nconst STOP_WORDS = new Set([\n 'a', 'an', 'the', 'and', 'or', 'but', 'of', 'in', 'on', 'at', 'to', 'from',\n 'for', 'by', 'with', 'as', 'is', 'are', 'was', 'were', 'be', 'been', 'being',\n 'this', 'that', 'these', 'those', 'it', 'its', 'their', 'them', 'they',\n 'has', 'have', 'had', 'do', 'does', 'did', 'will', 'would', 'should', 'could',\n 'than', 'then', 'so', 'such', 'into', 'about', 'above', 'below', 'across',\n]);\n\nconst NEGATION_PATTERN =\n /\\b(not|never|no|none|cannot|can't|won't|don't|doesn't|isn't|aren't|wasn't|weren't|nothing|neither|nor)\\b/i;\n\nexport function tokenize(text: string): string[] {\n const matches = text.toLowerCase().match(/[a-z0-9]+/g);\n if (!matches) return [];\n return matches.filter((t) => !STOP_WORDS.has(t) && t.length > 2);\n}\n\nexport function jaccardSimilarity(a: string, b: string): number {\n const tokA = new Set(tokenize(a));\n const tokB = new Set(tokenize(b));\n if (tokA.size === 0 || tokB.size === 0) return 0;\n let intersection = 0;\n for (const t of tokA) if (tokB.has(t)) intersection += 1;\n const union = new Set([...tokA, ...tokB]).size;\n return intersection / union;\n}\n\nexport function hasNegation(text: string): boolean {\n return NEGATION_PATTERN.test(text);\n}\n\nexport function assessScopeOverlap(\n a: string | null,\n b: string | null,\n): OverlapAssessment {\n if (a === null && b === null) return 'unknown';\n if (a === null || b === null) return 'non_overlapping';\n const sim = jaccardSimilarity(a, b);\n if (sim >= 0.7) return 'fully_overlapping';\n if (sim >= 0.3) return 'partially_overlapping';\n return 'non_overlapping';\n}\n","import type { Claim } from '../../claims/schema.js';\nimport {\n assessScopeOverlap,\n hasNegation,\n jaccardSimilarity,\n} from '../scope.js';\nimport type {\n ContradictionDetector,\n DetectionResult,\n DraftContradiction,\n PairedDraft,\n} from '../types.js';\n\nconst TOKEN_OVERLAP_DIRECT_THRESHOLD = 0.5;\nconst TOKEN_OVERLAP_OVERGEN_THRESHOLD = 0.4;\n\nfunction compare(a: Claim, b: Claim): DraftContradiction | null {\n const overlap = assessScopeOverlap(a.scope, b.scope);\n const sim = jaccardSimilarity(a.asserts, b.asserts);\n const negA = hasNegation(a.asserts);\n const negB = hasNegation(b.asserts);\n const negationMismatch = negA !== negB;\n\n const oneScopedOneUniversal = (a.scope === null) !== (b.scope === null);\n if (oneScopedOneUniversal && sim >= TOKEN_OVERLAP_OVERGEN_THRESHOLD) {\n const universalSide = a.scope === null ? 'A' : 'B';\n const scopedSide = a.scope === null ? 'B' : 'A';\n const scopedScope = a.scope ?? b.scope!;\n return {\n type: 'overgeneralization_risk',\n summary: `Claim ${universalSide} appears to make a universal assertion while claim ${scopedSide} is contextually scoped to \"${scopedScope}\". Promotion of contextual claims to universal rules is the failure mode this gate is designed to catch.`,\n scope_analysis: `Claim ${scopedSide} has scope \"${scopedScope}\". Claim ${universalSide} has no recorded scope. The two assertions share key tokens (jaccard=${sim.toFixed(2)}), suggesting they address the same subject — but at incompatible levels of generality.`,\n overlap_assessment: overlap,\n severity: 'medium',\n confidence: sim >= 0.7 ? 'medium' : 'low',\n evidence: 'Asserts overlap on substantive tokens; scope-tagging is asymmetric (one universal, one specific).',\n };\n }\n\n if (\n sim >= TOKEN_OVERLAP_DIRECT_THRESHOLD &&\n negationMismatch &&\n (overlap === 'fully_overlapping' ||\n overlap === 'partially_overlapping' ||\n overlap === 'unknown')\n ) {\n return {\n type: 'direct_conflict',\n summary: `Claims share core terms but one negates a proposition the other affirms.`,\n scope_analysis: `Scope overlap assessed as ${overlap}; assertions disagree on a negated proposition (jaccard=${sim.toFixed(2)}).`,\n overlap_assessment: overlap,\n severity: 'medium',\n confidence: sim >= 0.75 ? 'medium' : 'low',\n evidence: 'Token similarity suggests the same subject. Negation marker mismatch suggests opposing positions on it.',\n };\n }\n\n return null;\n}\n\nexport class HeuristicContradictionDetector implements ContradictionDetector {\n readonly name = 'heuristic' as const;\n\n async available(): Promise<boolean> {\n return true;\n }\n\n async detect(claims: Claim[]): Promise<DetectionResult> {\n const drafts: PairedDraft[] = [];\n for (let i = 0; i < claims.length; i += 1) {\n for (let j = i + 1; j < claims.length; j += 1) {\n const a = claims[i]!;\n const b = claims[j]!;\n const draft = compare(a, b);\n if (draft) drafts.push({ claim_a: a, claim_b: b, draft });\n }\n }\n return { ok: true, drafts, method: 'heuristic_similarity_negation' };\n }\n}\n","import { normalizeOllamaHost } from '../../sources/extractors/ollama-intern.js';\nimport type { Claim } from '../../claims/schema.js';\nimport type {\n ContradictionDetector,\n ContradictionType,\n DetectionResult,\n DraftContradiction,\n OverlapAssessment,\n PairedDraft,\n Severity,\n} from '../types.js';\n\nconst DEFAULT_HOST = 'http://localhost:11434';\nconst DEFAULT_MODEL = 'hermes3:8b';\nconst DEFAULT_TIMEOUT_MS = 120_000;\n\nconst SYSTEM_PROMPT = `You are detecting tension between two atomic claims from a research pack.\n\nReturn ONE JSON object. If there is no contradiction, return {\"type\": \"none\"}.\n\nIf there IS a contradiction:\n{\n \"type\": \"direct_conflict\" | \"scope_conflict\" | \"temporal_conflict\" | \"definition_conflict\" | \"evidence_conflict\" | \"overgeneralization_risk\",\n \"summary\": \"ONE sentence describing the tension\",\n \"scope_analysis\": \"ONE sentence on whether and how the claims' scopes overlap\",\n \"overlap_assessment\": \"fully_overlapping\" | \"partially_overlapping\" | \"non_overlapping\" | \"unknown\",\n \"severity\": \"low\" | \"medium\" | \"high\" | \"blocking\",\n \"confidence\": \"low\" | \"medium\" | \"high\",\n \"evidence\": \"what specifically about the two claims signals the tension\"\n}\n\nHard rules:\n- direct_conflict requires overlapping scopes. If scopes do not overlap, choose scope_conflict, temporal_conflict, definition_conflict, evidence_conflict, or \"none\".\n- overgeneralization_risk fires when one claim appears to widen a contextual assertion into a universal rule without evidence. The publish-policy-promoted-from-role-os-rollout failure mode is the canonical example.\n- Be conservative. If the tension is unclear, return \"none\".\n- Do not invent claims. Only assess what is given.\n- Do not decide which claim is true.`;\n\ninterface ChatResponse {\n message?: { content?: string };\n response?: string;\n}\n\nconst VALID_TYPES: ContradictionType[] = [\n 'direct_conflict',\n 'scope_conflict',\n 'temporal_conflict',\n 'definition_conflict',\n 'evidence_conflict',\n 'overgeneralization_risk',\n];\n\nconst VALID_OVERLAPS: OverlapAssessment[] = [\n 'fully_overlapping',\n 'partially_overlapping',\n 'non_overlapping',\n 'unknown',\n];\n\nconst VALID_SEVERITIES: Severity[] = ['low', 'medium', 'high', 'blocking'];\n\nconst VALID_CONFIDENCES = ['low', 'medium', 'high'] as const;\ntype ValidConfidence = (typeof VALID_CONFIDENCES)[number];\n\nfunction asEnum<T extends string>(value: unknown, allowed: readonly T[], fallback: T): T {\n return typeof value === 'string' && (allowed as readonly string[]).includes(value)\n ? (value as T)\n : fallback;\n}\n\nfunction asString(value: unknown, fallback: string): string {\n return typeof value === 'string' && value.trim().length > 0 ? value.trim() : fallback;\n}\n\nexport interface OllamaContradictionConfig {\n host?: string;\n model?: string;\n timeoutMs?: number;\n fetchImpl?: typeof fetch;\n}\n\nexport class OllamaInternContradictionDetector implements ContradictionDetector {\n readonly name = 'ollama-intern' as const;\n private readonly host: string;\n readonly model: string;\n private readonly timeoutMs: number;\n private readonly fetchImpl: typeof fetch;\n\n constructor(config: OllamaContradictionConfig = {}) {\n this.host = normalizeOllamaHost(config.host ?? process.env.OLLAMA_HOST ?? DEFAULT_HOST);\n this.model = config.model ?? process.env.OLLAMA_INTERN_MODEL ?? DEFAULT_MODEL;\n this.timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n this.fetchImpl = config.fetchImpl ?? globalThis.fetch;\n }\n\n async available(): Promise<boolean> {\n try {\n const ctrl = new AbortController();\n const t = setTimeout(() => ctrl.abort(), 1500);\n const res = await this.fetchImpl(`${this.host}/api/tags`, { signal: ctrl.signal });\n clearTimeout(t);\n if (!res.ok) return false;\n const body = (await res.json()) as { models?: Array<{ name: string }> };\n const names = (body.models ?? []).map((m) => m.name);\n const family = this.model.split(':')[0] ?? this.model;\n return names.some(\n (n) => n === this.model || n === family || n.startsWith(`${family}:`),\n );\n } catch {\n return false;\n }\n }\n\n private formatClaim(label: string, claim: Claim): string {\n return [\n `Claim ${label} (${claim.claim_id}):`,\n ` asserts: ${claim.asserts}`,\n ` scope: ${claim.scope ?? 'null'}`,\n ` not: ${claim.not ?? 'null'}`,\n ` evidence_excerpt: ${claim.evidence_excerpt}`,\n ` source_ids: ${claim.source_ids.join(', ')}`,\n ].join('\\n');\n }\n\n private async classifyPair(a: Claim, b: Claim): Promise<DraftContradiction | null> {\n const userMsg = [this.formatClaim('A', a), '', this.formatClaim('B', b)].join('\\n');\n\n const ctrl = new AbortController();\n const t = setTimeout(() => ctrl.abort(), this.timeoutMs);\n let body: ChatResponse;\n try {\n const res = await this.fetchImpl(`${this.host}/api/chat`, {\n method: 'POST',\n signal: ctrl.signal,\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n model: this.model,\n stream: false,\n format: 'json',\n // Override Ollama's default 4096 context for the same reason as\n // the claim extractor — pairwise prompts with full claim+scope+\n // not+evidence_excerpt can exceed 4K on dense fields.\n options: { num_ctx: 8192 },\n messages: [\n { role: 'system', content: SYSTEM_PROMPT },\n { role: 'user', content: userMsg },\n ],\n }),\n });\n if (!res.ok) return null;\n body = (await res.json()) as ChatResponse;\n } catch {\n return null;\n } finally {\n clearTimeout(t);\n }\n\n const text = body.message?.content ?? body.response ?? '';\n let parsed: Record<string, unknown>;\n try {\n parsed = JSON.parse(text) as Record<string, unknown>;\n } catch {\n return null;\n }\n\n if (parsed.type === 'none' || !parsed.type) return null;\n\n const type = asEnum<ContradictionType>(parsed.type, VALID_TYPES, 'direct_conflict');\n if (!VALID_TYPES.includes(parsed.type as ContradictionType)) return null;\n\n return {\n type,\n summary: asString(parsed.summary, '(no summary)'),\n scope_analysis: asString(parsed.scope_analysis, ''),\n overlap_assessment: asEnum<OverlapAssessment>(\n parsed.overlap_assessment,\n VALID_OVERLAPS,\n 'unknown',\n ),\n severity: asEnum<Severity>(parsed.severity, VALID_SEVERITIES, 'low'),\n confidence: asEnum<ValidConfidence>(parsed.confidence, VALID_CONFIDENCES, 'low'),\n evidence: asString(parsed.evidence, ''),\n };\n }\n\n async detect(claims: Claim[]): Promise<DetectionResult> {\n // Prefilter: only LLM-classify pairs that look like potential tensions.\n // For dense sections (50+ claims) full N² is feasible but expensive; for\n // huge sections it's outright intractable. The prefilter is a token\n // Jaccard score plus a scope-overlap signal — both cheap and\n // deterministic. Pairs failing the prefilter contribute nothing to the\n // final ledger; the model never sees them.\n const candidatePairs = candidateContradictionPairs(claims);\n const drafts: PairedDraft[] = [];\n for (const [i, j] of candidatePairs) {\n const a = claims[i]!;\n const b = claims[j]!;\n const draft = await this.classifyPair(a, b);\n if (draft) drafts.push({ claim_a: a, claim_b: b, draft });\n }\n return {\n ok: true,\n drafts,\n method:\n candidatePairs.length === (claims.length * (claims.length - 1)) / 2\n ? 'ollama_intern_pairwise_classification'\n : 'ollama_intern_prefiltered_pairwise_classification',\n };\n }\n}\n\n// Deterministic prefilter for which claim pairs are worth LLM classification.\n// Returns pair indices [i,j] (i < j). A pair qualifies if EITHER:\n// - normalised-asserts token Jaccard >= 0.25 (similar topic — potential\n// tension worth checking), OR\n// - scopes both non-null AND share >= 1 token of length > 3 (claims about\n// the same scope are the canonical site of contradiction)\n// A claim with empty asserts is never paired.\nexport function candidateContradictionPairs(claims: Claim[]): Array<[number, number]> {\n const SIM_THRESHOLD = 0.25;\n const tokenSets: Array<Set<string>> = claims.map((c) =>\n tokenSet(c.asserts),\n );\n const scopeTokens: Array<Set<string>> = claims.map((c) =>\n c.scope ? tokenSet(c.scope) : new Set<string>(),\n );\n\n const out: Array<[number, number]> = [];\n for (let i = 0; i < claims.length; i += 1) {\n if (tokenSets[i]!.size === 0) continue;\n for (let j = i + 1; j < claims.length; j += 1) {\n if (tokenSets[j]!.size === 0) continue;\n const sim = jaccard(tokenSets[i]!, tokenSets[j]!);\n if (sim >= SIM_THRESHOLD) {\n out.push([i, j]);\n continue;\n }\n // Scope-overlap fallback.\n const aScope = scopeTokens[i]!;\n const bScope = scopeTokens[j]!;\n if (aScope.size > 0 && bScope.size > 0) {\n let shared = 0;\n for (const t of aScope) if (bScope.has(t)) shared += 1;\n if (shared >= 1) out.push([i, j]);\n }\n }\n }\n return out;\n}\n\nfunction tokenSet(s: string): Set<string> {\n const out = new Set<string>();\n for (const tok of s\n .toLowerCase()\n .replace(/[^a-z0-9 ]+/g, ' ')\n .split(/\\s+/)) {\n if (tok.length > 3) out.add(tok);\n }\n return out;\n}\n\nfunction jaccard(a: Set<string>, b: Set<string>): number {\n if (a.size === 0 && b.size === 0) return 0;\n let inter = 0;\n for (const t of a) if (b.has(t)) inter += 1;\n const union = a.size + b.size - inter;\n return union === 0 ? 0 : inter / union;\n}\n","import type { ContradictionDetector } from '../types.js';\nimport { HeuristicContradictionDetector } from './heuristic.js';\nimport { OllamaInternContradictionDetector } from './ollama-intern.js';\n\nexport { HeuristicContradictionDetector } from './heuristic.js';\nexport { OllamaInternContradictionDetector } from './ollama-intern.js';\n\nexport function defaultContradictionDetectors(): ContradictionDetector[] {\n return [new OllamaInternContradictionDetector(), new HeuristicContradictionDetector()];\n}\n\nexport async function pickContradictionDetector(\n detectors: ContradictionDetector[],\n): Promise<ContradictionDetector> {\n for (const d of detectors) {\n if (await d.available()) return d;\n }\n throw new Error(\n 'No contradiction detector available. The HeuristicContradictionDetector should always be available — this indicates a bug.',\n );\n}\n","import type { Contradiction } from './schema.js';\n\nexport function renderMarkdownView(args: {\n sectionId: string;\n candidateClaims: number;\n contradictions: Contradiction[];\n detector: string;\n detectionMethod: string;\n}): string {\n const { sectionId, candidateClaims, contradictions, detector, detectionMethod } = args;\n const lines: string[] = [];\n lines.push(`# Contradictions: ${sectionId}`);\n lines.push('');\n if (contradictions.length === 0) {\n lines.push(\n `No contradiction candidates detected by ${detector} (${detectionMethod}) over ${candidateClaims} candidate claim${candidateClaims === 1 ? '' : 's'}.`,\n );\n lines.push('');\n lines.push(\n `Detection methods are not exhaustive. Adversarial review may surface tensions the detector missed. A clean section is a valid result, not proof of completeness.`,\n );\n return lines.join('\\n') + '\\n';\n }\n\n lines.push(\n `${contradictions.length} contradiction candidate${contradictions.length === 1 ? '' : 's'} detected by ${detector} (${detectionMethod}) over ${candidateClaims} candidate claim${candidateClaims === 1 ? '' : 's'}.`,\n );\n lines.push('');\n lines.push(\n 'Status: all unresolved. The gate engine determines whether unresolved contradictions block synthesis. The adversarial reviewer determines whether each contradiction is real, weak, or misclassified. This view is the map, not the judgment.',\n );\n lines.push('');\n lines.push('---');\n lines.push('');\n\n for (const c of contradictions) {\n lines.push(`## ${c.contradiction_id}: ${c.type}`);\n lines.push('');\n lines.push(`- **Severity:** ${c.severity}`);\n lines.push(`- **Confidence:** ${c.confidence}`);\n lines.push(`- **Status:** ${c.status}`);\n lines.push(`- **Overlap:** ${c.overlap_assessment}`);\n lines.push(`- **Detector:** ${c.detector} (${c.detection_method})`);\n lines.push('');\n lines.push(`**Claims:** \\`${c.claim_ids.join('`, `')}\\``);\n lines.push(`**Sources:** \\`${c.source_ids.join('`, `')}\\``);\n lines.push('');\n lines.push(`**Summary:** ${c.summary}`);\n lines.push('');\n if (c.scope_analysis) {\n lines.push(`**Scope analysis:** ${c.scope_analysis}`);\n lines.push('');\n }\n if (c.evidence) {\n lines.push(`**Evidence:** ${c.evidence}`);\n lines.push('');\n }\n lines.push('---');\n lines.push('');\n }\n return lines.join('\\n');\n}\n","import { z } from 'zod';\n\n// Triage is the deterministic / semi-deterministic shaping pass between\n// extraction and review. It does NOT mutate claims.jsonl. Triage decisions\n// live in their own append-only ledger and downstream commands (contradict,\n// review) can opt into reading only the selected_for_review subset via\n// --triaged-only.\n//\n// Law #13 (the law this module enforces):\n// Extraction may overproduce; synthesis may not inherit abundance.\n// Claim abundance is not research quality. Claims must be triaged before\n// they can compete for synthesis.\n\nexport const TriageDecisionSchema = z.enum([\n // Passes triage and is forwarded to review.\n 'selected_for_review',\n // Parked: kept on the canonical ledger as research truth, but not advanced.\n 'parked_duplicate',\n 'parked_overdense_source',\n 'parked_weak_scope',\n 'parked_low_value',\n // Routed for repair before re-triage.\n 'needs_scope_repair',\n 'needs_human_review',\n]);\n\nexport const ClaimTriageSchema = z.object({\n triage_id: z.string().regex(/^tri_[a-f0-9]{12}$/),\n claim_id: z.string().regex(/^clm_[a-f0-9]{12}_(heuristic|ollama_intern)_\\d+$/),\n section_id: z.string().regex(/^[0-9]{2}-[a-z0-9-]+$/),\n decision: TriageDecisionSchema,\n reason: z.string().min(1),\n // Rank among selected_for_review claims (1 = highest priority). null for\n // any non-selected decision.\n rank: z.number().int().positive().nullable(),\n // Quality score [0..1] used to sort. Stable. Higher = better.\n quality_score: z.number().min(0).max(1),\n triage_method: z.string().min(1),\n created_at: z.string(),\n});\n\nexport const TriageSummarySchema = z.object({\n summary_id: z.string().regex(/^tris_[0-9]+_[a-z0-9-]+$/),\n section_id: z.string().regex(/^[0-9]{2}-[a-z0-9-]+$/),\n triaged_at: z.string(),\n research_os_version: z.string(),\n triage_method: z.string(),\n candidate_claims: z.number().int().nonnegative(),\n decisions: z.record(TriageDecisionSchema, z.number().int().nonnegative()),\n per_source_cap: z.number().int().positive(),\n duplicate_clusters_collapsed: z.number().int().nonnegative(),\n selected_count: z.number().int().nonnegative(),\n selected_per_source: z.array(\n z.object({\n source_id: z.string().regex(/^src_[a-f0-9]{12}$/),\n selected: z.number().int().nonnegative(),\n total: z.number().int().nonnegative(),\n }),\n ),\n});\n\nexport type TriageDecision = z.infer<typeof TriageDecisionSchema>;\nexport type ClaimTriage = z.infer<typeof ClaimTriageSchema>;\nexport type TriageSummary = z.infer<typeof TriageSummarySchema>;\n","import { existsSync } from 'node:fs';\nimport { createHash } from 'node:crypto';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { join, resolve } from 'node:path';\n\nimport { PackNotFoundError, SectionNotFoundError } from '../errors.js';\nimport { RESEARCH_OS_VERSION } from '../index.js';\nimport { ClaimSchema, type Claim } from '../claims/schema.js';\nimport {\n ClaimTriageSchema,\n TriageSummarySchema,\n type ClaimTriage,\n type TriageDecision,\n type TriageSummary,\n} from './schema.js';\nimport type { TriageOptions, TriageRunResult } from './types.js';\n\nconst DEFAULT_PER_SOURCE_CAP = 10;\nconst DEFAULT_MIN_ASSERT_CHARS = 30;\n\n\nfunction normaliseAssert(s: string): string {\n return s\n .toLowerCase()\n .replace(/[^a-z0-9 ]+/g, ' ')\n .replace(/\\s+/g, ' ')\n .trim();\n}\n\n// Quality score in [0..1] — purely deterministic from claim fields. Higher\n// is better; ranking is stable.\nfunction qualityScore(claim: Claim): number {\n let score = 0;\n // scope present is the single largest signal (extractor met the law).\n if (claim.scope && claim.scope.length > 0) score += 0.4;\n if (claim.not && claim.not.length > 0) score += 0.2;\n if (claim.confidence === 'high') score += 0.2;\n else if (claim.confidence === 'medium') score += 0.1;\n // Goldilocks asserts length: 60..240 chars rewarded most.\n const len = claim.asserts.length;\n if (len >= 60 && len <= 240) score += 0.15;\n else if (len >= 30 && len < 60) score += 0.05;\n // Multi-excerpt grounding rewards a tiny bit (model crossed spans).\n if (claim.evidence_excerpt_ids.length > 1) score += 0.05;\n return Math.min(1, Math.max(0, score));\n}\n\nfunction makeTriageId(claimId: string): string {\n // 12 hex chars derived from claim_id so re-runs over identical claim\n // produce identical triage_ids — keeps the ledger idempotent.\n return 'tri_' + createHash('sha256').update(claimId).digest('hex').slice(0, 12);\n}\n\nasync function readClaims(packPath: string, sectionId: string): Promise<Claim[]> {\n const path = join(packPath, 'sections', sectionId, 'claims.jsonl');\n if (!existsSync(path)) return [];\n const text = await readFile(path, 'utf8');\n const out: Claim[] = [];\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n out.push(ClaimSchema.parse(JSON.parse(line)));\n } catch {\n /* skip */\n }\n }\n return out;\n}\n\ninterface TriageWorkRow {\n claim: Claim;\n decision: TriageDecision;\n reason: string;\n quality: number;\n rank: number | null;\n}\n\nexport async function triage(options: TriageOptions): Promise<TriageRunResult> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n if (!existsSync(join(packPath, 'research.yaml'))) throw new PackNotFoundError(packPath);\n if (!existsSync(join(packPath, 'sections', options.sectionId)))\n throw new SectionNotFoundError(options.sectionId);\n\n const perSourceCap = options.perSourceCap ?? DEFAULT_PER_SOURCE_CAP;\n const minAssertChars = options.minAssertChars ?? DEFAULT_MIN_ASSERT_CHARS;\n const stamp = (options.now ?? (() => new Date()))();\n const stampIso = stamp.toISOString();\n const stampMs = stamp.getTime();\n\n const claims = await readClaims(packPath, options.sectionId);\n\n // Pass 1 — apply per-claim filters in priority order. The first matching\n // filter wins; downstream filters skip any already-decided row.\n const rows: TriageWorkRow[] = claims.map((claim) => ({\n claim,\n decision: 'selected_for_review',\n reason: '',\n quality: qualityScore(claim),\n rank: null,\n }));\n\n // 1.1 parked_low_value — trivially short asserts (definitional / restating).\n for (const row of rows) {\n if (row.decision !== 'selected_for_review') continue;\n if (row.claim.asserts.length < minAssertChars) {\n row.decision = 'parked_low_value';\n row.reason = `Assert length ${row.claim.asserts.length} chars below the ${minAssertChars}-char floor; treated as definitional or restating.`;\n }\n }\n\n // 1.2 parked_weak_scope — both scope and not are null on a substantive\n // assertion. The reviewer can't even check overgeneralization without scope.\n for (const row of rows) {\n if (row.decision !== 'selected_for_review') continue;\n if (\n row.claim.scope === null &&\n row.claim.not === null &&\n row.claim.asserts.length > 40\n ) {\n row.decision = 'parked_weak_scope';\n row.reason =\n 'Substantive assertion with scope=null and not=null. Without scope/not boundaries the claim cannot earn a synthesis slot.';\n }\n }\n\n // 1.3 needs_scope_repair — scope is missing but `not` is set, OR vice\n // versa. The asymmetric case is recoverable: re-extract or hand-correct.\n for (const row of rows) {\n if (row.decision !== 'selected_for_review') continue;\n if (\n (row.claim.scope === null && row.claim.not !== null) ||\n (row.claim.scope !== null && row.claim.not === null && row.claim.asserts.length > 80)\n ) {\n row.decision = 'needs_scope_repair';\n row.reason = 'Scope or not is missing on a substantive claim; recoverable with a scope-repair pass.';\n }\n }\n\n // Pass 2 — dedupe by normalised asserts. Keep the highest-quality claim\n // in each cluster; park the rest as parked_duplicate. Only run on rows\n // still at selected_for_review.\n const clusters = new Map<string, TriageWorkRow[]>();\n for (const row of rows) {\n if (row.decision !== 'selected_for_review') continue;\n const key = normaliseAssert(row.claim.asserts);\n if (!key) continue;\n const arr = clusters.get(key) ?? [];\n arr.push(row);\n clusters.set(key, arr);\n }\n let duplicateClustersCollapsed = 0;\n for (const [, members] of clusters) {\n if (members.length <= 1) continue;\n duplicateClustersCollapsed += 1;\n // Sort by quality desc, then claim_id asc for determinism.\n members.sort((a, b) => {\n if (b.quality !== a.quality) return b.quality - a.quality;\n return a.claim.claim_id.localeCompare(b.claim.claim_id);\n });\n for (let i = 1; i < members.length; i += 1) {\n const r = members[i]!;\n r.decision = 'parked_duplicate';\n r.reason = `Normalised assertion matches ${members[0]!.claim.claim_id} which has higher quality (${members[0]!.quality.toFixed(2)} vs ${r.quality.toFixed(2)}).`;\n }\n }\n\n // Pass 3 — per-source cap. For each source with too many remaining\n // selected_for_review rows, keep the top perSourceCap by quality and park\n // the rest as parked_overdense_source.\n const stillSelectedBySrc = new Map<string, TriageWorkRow[]>();\n for (const row of rows) {\n if (row.decision !== 'selected_for_review') continue;\n for (const sid of row.claim.source_ids) {\n const arr = stillSelectedBySrc.get(sid) ?? [];\n arr.push(row);\n stillSelectedBySrc.set(sid, arr);\n }\n }\n for (const [sid, list] of stillSelectedBySrc) {\n if (list.length <= perSourceCap) continue;\n list.sort((a, b) => {\n if (b.quality !== a.quality) return b.quality - a.quality;\n return a.claim.claim_id.localeCompare(b.claim.claim_id);\n });\n for (let i = perSourceCap; i < list.length; i += 1) {\n const r = list[i]!;\n // Only mark the row over the cap if it isn't already parked by a\n // different source (a multi-source claim is kept if any of its\n // sources still has cap headroom).\n if (r.decision !== 'selected_for_review') continue;\n r.decision = 'parked_overdense_source';\n r.reason = `Source ${sid} contributed ${list.length} candidates; cap is ${perSourceCap}. This claim's quality (${r.quality.toFixed(2)}) ranks ${i + 1} for the source.`;\n }\n }\n\n // Pass 4 — assign ranks to surviving selected_for_review rows so review\n // can process in priority order.\n const surviving = rows.filter((r) => r.decision === 'selected_for_review');\n surviving.sort((a, b) => {\n if (b.quality !== a.quality) return b.quality - a.quality;\n return a.claim.claim_id.localeCompare(b.claim.claim_id);\n });\n surviving.forEach((r, i) => {\n r.rank = i + 1;\n if (!r.reason) r.reason = `Selected for review at rank ${r.rank} (quality ${r.quality.toFixed(2)}).`;\n });\n\n // Build triage records.\n const records: ClaimTriage[] = rows.map((r) =>\n ClaimTriageSchema.parse({\n triage_id: makeTriageId(r.claim.claim_id),\n claim_id: r.claim.claim_id,\n section_id: options.sectionId,\n decision: r.decision,\n reason: r.reason,\n rank: r.rank,\n quality_score: Number(r.quality.toFixed(4)),\n triage_method: 'research_os_triage_v1',\n created_at: stampIso,\n }),\n );\n\n // Per-source counts for the summary.\n const perSourceTotal = new Map<string, number>();\n const perSourceSelected = new Map<string, number>();\n for (const r of rows) {\n for (const sid of r.claim.source_ids) {\n perSourceTotal.set(sid, (perSourceTotal.get(sid) ?? 0) + 1);\n if (r.decision === 'selected_for_review') {\n perSourceSelected.set(sid, (perSourceSelected.get(sid) ?? 0) + 1);\n }\n }\n }\n const decisions: Record<string, number> = {};\n for (const r of rows) {\n decisions[r.decision] = (decisions[r.decision] ?? 0) + 1;\n }\n\n const summary: TriageSummary = TriageSummarySchema.parse({\n summary_id: `tris_${stampMs}_${options.sectionId}`,\n section_id: options.sectionId,\n triaged_at: stampIso,\n research_os_version: RESEARCH_OS_VERSION,\n triage_method: 'research_os_triage_v1',\n candidate_claims: claims.length,\n decisions,\n per_source_cap: perSourceCap,\n duplicate_clusters_collapsed: duplicateClustersCollapsed,\n selected_count: surviving.length,\n selected_per_source: Array.from(perSourceTotal.entries())\n .map(([source_id, total]) => ({\n source_id,\n selected: perSourceSelected.get(source_id) ?? 0,\n total,\n }))\n .sort((a, b) => b.total - a.total),\n });\n\n // Write outputs.\n const sectionDir = join(packPath, 'sections', options.sectionId);\n const auditsDir = join(packPath, 'audits');\n await mkdir(sectionDir, { recursive: true });\n await mkdir(auditsDir, { recursive: true });\n const triageJsonlPath = join(sectionDir, 'claim-triage.jsonl');\n const triageMarkdownPath = join(sectionDir, 'claim-triage.md');\n const summaryJsonPath = join(auditsDir, `${options.sectionId}-claim-triage.json`);\n\n await writeFile(triageJsonlPath, records.map((r) => JSON.stringify(r)).join('\\n') + '\\n', 'utf8');\n await writeFile(triageMarkdownPath, buildMarkdown(records, summary), 'utf8');\n await writeFile(summaryJsonPath, JSON.stringify(summary, null, 2), 'utf8');\n\n const parkedCount = rows.filter((r) => r.decision.startsWith('parked_')).length;\n const needsRepairCount = rows.filter(\n (r) => r.decision === 'needs_scope_repair' || r.decision === 'needs_human_review',\n ).length;\n\n return {\n triageJsonlPath,\n triageMarkdownPath,\n summaryJsonPath,\n candidateClaims: claims.length,\n selectedCount: surviving.length,\n parkedCount,\n needsRepairCount,\n decisions,\n };\n}\n\n// Read the triage ledger for a section. Used by --triaged-only consumers.\nexport async function readTriagedClaimIds(\n packPath: string,\n sectionId: string,\n): Promise<Set<string>> {\n const path = join(packPath, 'sections', sectionId, 'claim-triage.jsonl');\n const out = new Set<string>();\n if (!existsSync(path)) return out;\n const text = await readFile(path, 'utf8');\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n const r = ClaimTriageSchema.parse(JSON.parse(line));\n if (r.decision === 'selected_for_review') out.add(r.claim_id);\n } catch {\n /* skip */\n }\n }\n return out;\n}\n\nfunction buildMarkdown(records: ClaimTriage[], summary: TriageSummary): string {\n const lines: string[] = [];\n lines.push(`# Claim triage: ${summary.section_id}`);\n lines.push('');\n lines.push(`- **Summary ID:** \\`${summary.summary_id}\\``);\n lines.push(`- **Triaged at:** ${summary.triaged_at}`);\n lines.push(`- **Method:** ${summary.triage_method}`);\n lines.push(`- **Candidate claims:** ${summary.candidate_claims}`);\n lines.push(`- **Selected for review:** ${summary.selected_count}`);\n lines.push(`- **Per-source cap:** ${summary.per_source_cap}`);\n lines.push(`- **Duplicate clusters collapsed:** ${summary.duplicate_clusters_collapsed}`);\n lines.push('');\n lines.push('## Decisions');\n lines.push('');\n lines.push('| Decision | Count |');\n lines.push('|---|---:|');\n for (const [k, v] of Object.entries(summary.decisions)) {\n lines.push(`| \\`${k}\\` | ${v} |`);\n }\n lines.push('');\n lines.push('## Selected per source');\n lines.push('');\n lines.push('| Source | Selected | Total |');\n lines.push('|---|---:|---:|');\n for (const s of summary.selected_per_source) {\n lines.push(`| \\`${s.source_id}\\` | ${s.selected} | ${s.total} |`);\n }\n lines.push('');\n lines.push('## Triage records (compact)');\n lines.push('');\n lines.push('| Rank | Decision | Quality | Claim ID | Reason |');\n lines.push('|---:|---|---:|---|---|');\n // Selected first (in rank order), then everything else grouped by decision.\n const selected = records.filter((r) => r.decision === 'selected_for_review');\n selected.sort((a, b) => (a.rank ?? 0) - (b.rank ?? 0));\n for (const r of selected) {\n lines.push(`| ${r.rank ?? ''} | \\`${r.decision}\\` | ${r.quality_score.toFixed(2)} | \\`${r.claim_id}\\` | ${r.reason.replace(/\\|/g, '\\\\|')} |`);\n }\n const parked = records.filter((r) => r.decision !== 'selected_for_review');\n parked.sort((a, b) => a.decision.localeCompare(b.decision));\n for (const r of parked) {\n lines.push(`| | \\`${r.decision}\\` | ${r.quality_score.toFixed(2)} | \\`${r.claim_id}\\` | ${r.reason.replace(/\\|/g, '\\\\|')} |`);\n }\n lines.push('');\n lines.push('---');\n lines.push('');\n lines.push('_Triage does not mutate `claims.jsonl`. Parked claims remain on the canonical ledger as research truth; they are simply excluded from the next review pass._');\n return lines.join('\\n');\n}\n","import { createHash } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { appendFile, readFile, writeFile } from 'node:fs/promises';\nimport { join, resolve } from 'node:path';\n\nimport { PackNotFoundError, SectionNotFoundError } from '../errors.js';\nimport { ClaimSchema, type Claim } from '../claims/schema.js';\nimport { ContradictionSchema, type Contradiction } from './schema.js';\nimport {\n pickContradictionDetector,\n} from './detectors/index.js';\nimport { HeuristicContradictionDetector } from './detectors/heuristic.js';\nimport { OllamaInternContradictionDetector } from './detectors/ollama-intern.js';\nimport { renderMarkdownView } from './markdown.js';\nimport type {\n ContradictionDetector,\n ContradictionDetectorName,\n MapOptions,\n MapSummary,\n PairedDraft,\n} from './types.js';\n\nconst DETECTOR_ID_PART: Record<ContradictionDetectorName, string> = {\n heuristic: 'heuristic',\n 'ollama-intern': 'ollama_intern',\n};\n\nasync function readCandidateClaims(packPath: string, sectionId: string): Promise<Claim[]> {\n const path = join(packPath, 'sections', sectionId, 'claims.jsonl');\n if (!existsSync(path)) return [];\n const text = await readFile(path, 'utf8');\n const claims: Claim[] = [];\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n const parsed = ClaimSchema.parse(JSON.parse(line));\n if (parsed.review_state !== 'candidate') continue;\n claims.push(parsed);\n }\n return claims;\n}\n\nasync function readExistingContradictions(\n packPath: string,\n sectionId: string,\n): Promise<Contradiction[]> {\n const path = join(packPath, 'sections', sectionId, 'contradictions.jsonl');\n if (!existsSync(path)) return [];\n const text = await readFile(path, 'utf8');\n const list: Contradiction[] = [];\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n list.push(ContradictionSchema.parse(JSON.parse(line)));\n } catch {\n /* skip malformed */\n }\n }\n return list;\n}\n\nfunction pairHash(claimAId: string, claimBId: string): string {\n const sorted = [claimAId, claimBId].sort();\n return createHash('sha256')\n .update(sorted.join('|'))\n .digest('hex')\n .slice(0, 12);\n}\n\nfunction buildContradiction(args: {\n paired: PairedDraft;\n sectionId: string;\n detector: ContradictionDetectorName;\n detectionMethod: string;\n}): Contradiction {\n const { paired, sectionId, detector, detectionMethod } = args;\n const { claim_a, claim_b, draft } = paired;\n const detectorIdPart = DETECTOR_ID_PART[detector];\n const id = `cnt_${pairHash(claim_a.claim_id, claim_b.claim_id)}_${detectorIdPart}`;\n const sourceIds = Array.from(\n new Set<string>([...claim_a.source_ids, ...claim_b.source_ids]),\n );\n return ContradictionSchema.parse({\n contradiction_id: id,\n section_id: sectionId,\n claim_ids: [claim_a.claim_id, claim_b.claim_id].sort(),\n source_ids: sourceIds,\n type: draft.type,\n summary: draft.summary,\n scope_analysis: draft.scope_analysis,\n overlap_assessment: draft.overlap_assessment,\n severity: draft.severity,\n confidence: draft.confidence,\n detector,\n detection_method: detectionMethod,\n evidence: draft.evidence,\n status: 'unresolved',\n created_at: new Date().toISOString(),\n });\n}\n\nconst VALID_DETECTOR_MODES = ['auto', 'heuristic', 'ollama-intern'] as const;\n\nasync function resolveDetector(options: MapOptions): Promise<{\n detector: ContradictionDetector;\n announcement: string;\n}> {\n const mode = options.detectorMode ?? 'auto';\n\n if (!VALID_DETECTOR_MODES.includes(mode as (typeof VALID_DETECTOR_MODES)[number])) {\n throw new Error(\n `contradict map: invalid --detector value \"${mode}\"; valid values are: auto, heuristic, ollama-intern`,\n );\n }\n\n if (mode === 'heuristic') {\n return {\n detector: new HeuristicContradictionDetector(),\n announcement: 'contradict map: using heuristic detector',\n };\n }\n\n if (mode === 'ollama-intern') {\n const d = new OllamaInternContradictionDetector(options.ollamaConfig ?? {});\n if (!(await d.available())) {\n throw new Error(\n `contradict map: ollama-intern detector requested but model ${d.model} is unavailable; aborting (use --detector heuristic to bypass)`,\n );\n }\n return {\n detector: d,\n announcement: `contradict map: using ollama-intern detector with model ${d.model}`,\n };\n }\n\n // auto mode — preserve existing env-var-driven behavior; announce which path ran\n const detectors =\n options.detectors ??\n [\n new OllamaInternContradictionDetector(options.ollamaConfig ?? {}),\n new HeuristicContradictionDetector(),\n ];\n const detector = await pickContradictionDetector(detectors);\n\n if (detector.name === 'ollama-intern') {\n const modelName =\n detector instanceof OllamaInternContradictionDetector\n ? detector.model\n : (process.env.OLLAMA_INTERN_MODEL ?? 'hermes3:8b');\n return {\n detector,\n announcement: `contradict map: using ollama-intern detector with model ${modelName}`,\n };\n }\n\n return {\n detector,\n announcement: 'contradict map: ollama-intern unavailable; using heuristic detector',\n };\n}\n\nexport async function map(options: MapOptions): Promise<MapSummary> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n if (!existsSync(join(packPath, 'research.yaml'))) throw new PackNotFoundError(packPath);\n const sectionDir = join(packPath, 'sections', options.sectionId);\n if (!existsSync(sectionDir)) throw new SectionNotFoundError(options.sectionId);\n\n let candidateClaims = await readCandidateClaims(packPath, options.sectionId);\n if (options.triagedOnly) {\n const { readTriagedClaimIds } = await import('../triage/run.js');\n const allowed = await readTriagedClaimIds(packPath, options.sectionId);\n candidateClaims = candidateClaims.filter((c) => allowed.has(c.claim_id));\n }\n const { detector, announcement } = await resolveDetector(options);\n\n const summary: MapSummary = {\n sectionId: options.sectionId,\n detector: detector.name,\n detectionMethod: '',\n candidateClaims: candidateClaims.length,\n pairsCompared: 0,\n contradictionsAdded: 0,\n contradictionsDeduped: 0,\n contradictionIds: [],\n detectorError: null,\n detectorAnnouncement: announcement,\n };\n\n const ledgerPath = join(sectionDir, 'contradictions.jsonl');\n const mdPath = join(sectionDir, 'contradictions.md');\n\n const existingContradictions = await readExistingContradictions(\n packPath,\n options.sectionId,\n );\n const existingIds = new Set(existingContradictions.map((c) => c.contradiction_id));\n\n if (candidateClaims.length < 2) {\n summary.detectionMethod = 'no_pairs';\n const md = renderMarkdownView({\n sectionId: options.sectionId,\n candidateClaims: candidateClaims.length,\n contradictions: existingContradictions,\n detector: detector.name,\n detectionMethod: 'no_pairs',\n });\n await writeFile(mdPath, md, 'utf8');\n return summary;\n }\n\n const detectionResult = await detector.detect(candidateClaims);\n if (!detectionResult.ok) {\n summary.detectorError = detectionResult.error;\n summary.detectionMethod = 'failed';\n const md = renderMarkdownView({\n sectionId: options.sectionId,\n candidateClaims: candidateClaims.length,\n contradictions: existingContradictions,\n detector: detector.name,\n detectionMethod: 'failed',\n });\n await writeFile(mdPath, md, 'utf8');\n return summary;\n }\n\n summary.detectionMethod = detectionResult.method;\n summary.pairsCompared = (candidateClaims.length * (candidateClaims.length - 1)) / 2;\n\n for (const paired of detectionResult.drafts) {\n const c = buildContradiction({\n paired,\n sectionId: options.sectionId,\n detector: detector.name,\n detectionMethod: detectionResult.method,\n });\n if (existingIds.has(c.contradiction_id)) {\n summary.contradictionsDeduped += 1;\n continue;\n }\n await appendFile(ledgerPath, JSON.stringify(c) + '\\n', 'utf8');\n existingIds.add(c.contradiction_id);\n existingContradictions.push(c);\n summary.contradictionsAdded += 1;\n summary.contradictionIds.push(c.contradiction_id);\n }\n\n const md = renderMarkdownView({\n sectionId: options.sectionId,\n candidateClaims: candidateClaims.length,\n contradictions: existingContradictions,\n detector: detector.name,\n detectionMethod: detectionResult.method,\n });\n await writeFile(mdPath, md, 'utf8');\n\n return summary;\n}\n","import { z } from 'zod';\n\nexport const ResolutionStatusSchema = z.enum([\n 'unresolved',\n 'resolved',\n 'preserved',\n 'rejected',\n]);\n\nexport const ContradictionResolutionSchema = z.object({\n contradiction_id: z.string().min(1),\n status: ResolutionStatusSchema,\n reason: z.string().min(4),\n resolved_at: z.string().min(1),\n resolved_by: z.string().min(1),\n});\n\nexport type ContradictionResolution = z.infer<typeof ContradictionResolutionSchema>;\nexport type ResolutionStatus = z.infer<typeof ResolutionStatusSchema>;\n","import { appendFile, readFile } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\n\nimport { SectionNotFoundError } from '../errors.js';\nimport {\n ContradictionResolutionSchema,\n type ContradictionResolution,\n type ResolutionStatus,\n} from './resolution-schema.js';\n\nexport interface ResolveOptions {\n sectionId: string;\n packPath: string;\n /** Specific contradiction IDs to resolve. Mutually exclusive with `all`. */\n contradictionIds?: string[];\n /** Resolve all currently-unresolved contradictions in the section. */\n all?: boolean;\n /** Target status — cannot be 'unresolved' (use the candidates file for that default). */\n status: Exclude<ResolutionStatus, 'unresolved'>;\n reason: string;\n resolvedBy?: string;\n}\n\nexport interface ResolveResult {\n sectionId: string;\n applied: number;\n skipped: number;\n ledgerPath: string;\n}\n\nfunction latestEffectiveStatuses(ledgerPath: string, text: string): Map<string, string> {\n const entries: Array<{ contradiction_id: string; status: string; resolved_at: string }> = [];\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n const obj = JSON.parse(line) as Record<string, unknown>;\n if (\n typeof obj['contradiction_id'] === 'string' &&\n typeof obj['status'] === 'string' &&\n typeof obj['resolved_at'] === 'string'\n ) {\n entries.push({\n contradiction_id: obj['contradiction_id'],\n status: obj['status'],\n resolved_at: obj['resolved_at'],\n });\n }\n } catch {\n // skip malformed\n }\n }\n entries.sort((a, b) => a.resolved_at.localeCompare(b.resolved_at));\n const map = new Map<string, string>();\n for (const e of entries) map.set(e.contradiction_id, e.status);\n return map;\n}\n\nexport async function resolve(options: ResolveOptions): Promise<ResolveResult> {\n const { sectionId, packPath, contradictionIds, all, status, reason, resolvedBy = 'operator' } = options;\n\n if (reason.length < 4) {\n throw new Error('reason must be at least 4 characters');\n }\n\n const sectionDir = join(packPath, 'sections', sectionId);\n if (!existsSync(sectionDir)) {\n throw new SectionNotFoundError(sectionId);\n }\n\n const candidatesPath = join(sectionDir, 'contradictions.jsonl');\n const ledgerPath = join(sectionDir, 'contradiction-resolutions.jsonl');\n\n // Load known contradiction IDs and their candidate statuses\n const candidates: Array<{ contradiction_id: string; status: string }> = [];\n if (existsSync(candidatesPath)) {\n const text = await readFile(candidatesPath, 'utf8');\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n const obj = JSON.parse(line) as Record<string, unknown>;\n if (typeof obj['contradiction_id'] === 'string') {\n candidates.push({\n contradiction_id: obj['contradiction_id'],\n status: typeof obj['status'] === 'string' ? obj['status'] : 'unresolved',\n });\n }\n } catch {\n // skip malformed\n }\n }\n }\n\n // Load current effective statuses from ledger (latest-wins)\n const existingResolutions = existsSync(ledgerPath)\n ? latestEffectiveStatuses(ledgerPath, await readFile(ledgerPath, 'utf8'))\n : new Map<string, string>();\n\n const knownIds = new Set(candidates.map((c) => c.contradiction_id));\n\n // Determine target IDs\n let targetIds: string[];\n if (all) {\n targetIds = candidates\n .filter((c) => {\n const effective = existingResolutions.get(c.contradiction_id);\n return effective !== undefined ? effective === 'unresolved' : c.status === 'unresolved';\n })\n .map((c) => c.contradiction_id);\n } else {\n targetIds = contradictionIds ?? [];\n }\n\n const resolvedAt = new Date().toISOString();\n let applied = 0;\n let skipped = 0;\n const lines: string[] = [];\n\n for (const cid of targetIds) {\n if (!knownIds.has(cid)) {\n skipped++;\n continue;\n }\n const entry: ContradictionResolution = {\n contradiction_id: cid,\n status,\n reason,\n resolved_at: resolvedAt,\n resolved_by: resolvedBy,\n };\n ContradictionResolutionSchema.parse(entry);\n lines.push(JSON.stringify(entry));\n applied++;\n }\n\n if (lines.length > 0) {\n await appendFile(ledgerPath, lines.join('\\n') + '\\n', 'utf8');\n }\n\n return { sectionId, applied, skipped, ledgerPath };\n}\n","export { map } from './map.js';\nexport { resolve } from './resolve.js';\nexport {\n ContradictionResolutionSchema,\n ResolutionStatusSchema,\n type ContradictionResolution,\n type ResolutionStatus,\n} from './resolution-schema.js';\nexport {\n HeuristicContradictionDetector,\n OllamaInternContradictionDetector,\n defaultContradictionDetectors,\n pickContradictionDetector,\n} from './detectors/index.js';\nexport {\n ContradictionSchema,\n ContradictionTypeSchema,\n SeveritySchema,\n OverlapAssessmentSchema,\n ContradictionStatusSchema,\n ContradictionDetectorSchema,\n ContradictionConfidenceSchema,\n type Contradiction,\n} from './schema.js';\nexport {\n assessScopeOverlap,\n jaccardSimilarity,\n hasNegation,\n tokenize,\n} from './scope.js';\nexport { renderMarkdownView } from './markdown.js';\nexport type {\n ContradictionType,\n Severity,\n ContradictionDetectorName,\n DetectorMode,\n OverlapAssessment,\n ContradictionStatus,\n DraftContradiction,\n PairedDraft,\n DetectionResult,\n ContradictionDetector,\n MapOptions,\n MapSummary,\n} from './types.js';\n","import { z } from 'zod';\n\nexport const FindingCategorySchema = z.enum([\n 'unsupported_claim',\n 'ungrounded_excerpt',\n 'stale_claim',\n 'overgeneralized_claim',\n 'scope_widening',\n 'missing_not_constraint',\n 'source_quality_problem',\n 'source_cluster_monopoly',\n 'unmapped_contradiction',\n 'recommendation_exceeds_evidence',\n 'hidden_synthesis',\n 'definition_drift',\n 'temporal_mismatch',\n // Span-first + paged extraction can yield dense, atomized claim sets that\n // are individually grounded but collectively redundant. The reviewer flags\n // these so synthesis-worthiness — not just structural grounding — decides\n // what reaches synthesis.\n 'claim_overproduction',\n // Per-claim synthesis-worthiness call: this individual claim is grounded\n // and well-formed but does not earn a synthesis slot (low leverage,\n // restating context, definitional boilerplate, etc.). Distinct from\n // claim_overproduction (section/source-level pressure signal): a section\n // can be over-dense without every claim being individually low-value, and\n // a low-value claim can appear in a perfectly-sized section.\n 'valid_but_low_value',\n]);\n\nexport const FindingSeveritySchema = z.enum(['info', 'warn', 'block']);\n\nexport const ReviewerNameSchema = z.enum(['heuristic', 'ollama-intern']);\n\nexport const ReviewDecisionSchema = z.enum([\n 'accepted_for_synthesis',\n 'rejected',\n 'needs_scope_repair',\n 'needs_source_repair',\n 'needs_contradiction_mapping',\n 'needs_human_review',\n]);\n\nexport const ReviewConfidenceSchema = z.enum(['low', 'medium', 'high']);\n\nexport const ReviewFindingSchema = z.object({\n finding_id: z.string().regex(/^fnd_[a-f0-9]{12}$/),\n section_id: z.string().regex(/^[0-9]{2}-[a-z0-9-]+$/),\n claim_ids: z.array(z.string().regex(/^clm_[a-f0-9]{12}_(heuristic|ollama_intern)_\\d+$/)),\n source_ids: z.array(z.string().regex(/^src_[a-f0-9]{12}$/)),\n category: FindingCategorySchema,\n severity: FindingSeveritySchema,\n summary: z.string().min(1),\n evidence: z.string(),\n required_action: z.string(),\n reviewer: ReviewerNameSchema,\n review_method: z.string().min(1),\n confidence: ReviewConfidenceSchema,\n created_at: z.string(),\n});\n\nexport const ClaimReviewSchema = z.object({\n claim_id: z.string().regex(/^clm_[a-f0-9]{12}_(heuristic|ollama_intern)_\\d+$/),\n decision: ReviewDecisionSchema,\n reason: z.string().min(1),\n finding_ids: z.array(z.string()),\n reviewer: ReviewerNameSchema,\n review_method: z.string().min(1),\n created_at: z.string(),\n});\n\nexport const ReviewSnapshotSchema = z.object({\n section_id: z.string().regex(/^[0-9]{2}-[a-z0-9-]+$/),\n reviewer: ReviewerNameSchema,\n review_method: z.string(),\n reviewed_at: z.string(),\n candidate_claims: z.number().int().nonnegative(),\n findings: z.array(ReviewFindingSchema),\n claim_reviews: z.array(ClaimReviewSchema),\n decision_counts: z.record(ReviewDecisionSchema, z.number().int().nonnegative()),\n severity_counts: z.record(FindingSeveritySchema, z.number().int().nonnegative()),\n llm_findings_rejected_ungrounded: z.number().int().nonnegative(),\n promoted_to_reviewed: z.boolean(),\n});\n\nexport type ReviewFinding = z.infer<typeof ReviewFindingSchema>;\nexport type ClaimReview = z.infer<typeof ClaimReviewSchema>;\nexport type ReviewSnapshot = z.infer<typeof ReviewSnapshotSchema>;\n","import type { GateCheckResult, GateInput } from '../types.js';\n\nexport function checkSourceFloor(input: GateInput): GateCheckResult[] {\n const cfg = input.research.gates.source_floor;\n const results: GateCheckResult[] = [];\n const cards = input.sources;\n\n // min_sources\n const sourceCount = cards.length;\n if (sourceCount < cfg.min_sources) {\n results.push({\n family: 'source_floor',\n check: 'min_sources',\n status: 'fail',\n detail: `Found ${sourceCount} source card(s); minimum ${cfg.min_sources} required.`,\n evidence: cards.map((c) => c.source_id),\n blocks_synthesis: true,\n });\n } else {\n results.push({\n family: 'source_floor',\n check: 'min_sources',\n status: 'pass',\n detail: `${sourceCount} source card(s) >= minimum ${cfg.min_sources}.`,\n evidence: [],\n blocks_synthesis: false,\n });\n }\n\n // min_independent_publishers\n const publishers = new Set(\n cards.map((c) => c.publisher).filter((p): p is string => typeof p === 'string'),\n );\n if (publishers.size < cfg.min_independent_publishers) {\n results.push({\n family: 'source_floor',\n check: 'min_independent_publishers',\n status: 'fail',\n detail: `Found ${publishers.size} independent publisher(s); minimum ${cfg.min_independent_publishers} required.`,\n evidence: [...publishers],\n blocks_synthesis: true,\n });\n } else {\n results.push({\n family: 'source_floor',\n check: 'min_independent_publishers',\n status: 'pass',\n detail: `${publishers.size} independent publisher(s) >= minimum ${cfg.min_independent_publishers}.`,\n evidence: [],\n blocks_synthesis: false,\n });\n }\n\n // primary_sources_required\n const primaryCount = cards.filter((c) => c.source_type === 'primary').length;\n if (primaryCount < cfg.primary_sources_required) {\n results.push({\n family: 'source_floor',\n check: 'primary_sources_required',\n status: 'fail',\n detail: `Found ${primaryCount} primary source(s); minimum ${cfg.primary_sources_required} required. Pre-waiver.`,\n evidence: cards.filter((c) => c.source_type === 'primary').map((c) => c.source_id),\n blocks_synthesis: true,\n });\n } else {\n results.push({\n family: 'source_floor',\n check: 'primary_sources_required',\n status: 'pass',\n detail: `${primaryCount} primary source(s) >= minimum ${cfg.primary_sources_required}.`,\n evidence: [],\n blocks_synthesis: false,\n });\n }\n\n // failed-fetches visibility (warn-only; not fatal unless source floor fails)\n const failed = input.receipts.filter((r) => r.fetch_outcome !== 'ok').length;\n if (failed > 0) {\n results.push({\n family: 'source_floor',\n check: 'failed_fetches_visible',\n status: 'warn',\n detail: `${failed} fetch attempt(s) recorded as non-ok in fetch-log.jsonl.`,\n evidence: [],\n blocks_synthesis: false,\n });\n } else {\n results.push({\n family: 'source_floor',\n check: 'failed_fetches_visible',\n status: 'pass',\n detail: `No failed fetches in fetch-log.jsonl.`,\n evidence: [],\n blocks_synthesis: false,\n });\n }\n\n return results;\n}\n","import type { GateCheckResult, GateInput } from '../types.js';\n\nexport function checkClaimIntegrity(input: GateInput): GateCheckResult[] {\n const cfg = input.research.gates.claim_integrity;\n const results: GateCheckResult[] = [];\n const claims = input.candidateClaims;\n const cardIds = new Set(input.sources.map((c) => c.source_id));\n const okReceiptSourceIds = new Set(\n input.receipts.filter((r) => r.fetch_outcome === 'ok').map((r) => r.source_id),\n );\n\n // every_claim_needs_source — schema-enforced, but verify at gate too\n const noSourceIds = claims.filter((c) => c.source_ids.length === 0);\n if (noSourceIds.length > 0) {\n results.push({\n family: 'claim_integrity',\n check: 'every_claim_needs_source',\n status: 'fail',\n detail: `${noSourceIds.length} claim(s) lack source_ids.`,\n evidence: noSourceIds.map((c) => c.claim_id),\n blocks_synthesis: cfg.every_claim_needs_source,\n });\n } else {\n results.push({\n family: 'claim_integrity',\n check: 'every_claim_needs_source',\n status: 'pass',\n detail: `All ${claims.length} candidate claim(s) reference at least one source_id.`,\n evidence: [],\n blocks_synthesis: false,\n });\n }\n\n // no_orphan_claims — claim's source_ids must exist in source-cards\n const orphans = claims.filter((c) => c.source_ids.some((sid) => !cardIds.has(sid)));\n if (orphans.length > 0) {\n results.push({\n family: 'claim_integrity',\n check: 'no_orphan_claims',\n status: 'fail',\n detail: `${orphans.length} claim(s) cite source_id(s) not present in evidence/source-cards/.`,\n evidence: orphans.map((c) => c.claim_id),\n blocks_synthesis: cfg.no_orphan_claims,\n });\n } else {\n results.push({\n family: 'claim_integrity',\n check: 'no_orphan_claims',\n status: 'pass',\n detail: `All claim source_ids resolve to source cards.`,\n evidence: [],\n blocks_synthesis: false,\n });\n }\n\n // source_hashes present\n const noHash = claims.filter((c) => c.source_hashes.length === 0);\n if (noHash.length > 0) {\n results.push({\n family: 'claim_integrity',\n check: 'source_hashes_present',\n status: 'fail',\n detail: `${noHash.length} claim(s) have empty source_hashes — tamper detection cannot anchor to a fetch receipt.`,\n evidence: noHash.map((c) => c.claim_id),\n blocks_synthesis: true,\n });\n } else {\n results.push({\n family: 'claim_integrity',\n check: 'source_hashes_present',\n status: 'pass',\n detail: `All candidate claims carry source_hashes.`,\n evidence: [],\n blocks_synthesis: false,\n });\n }\n\n // evidence_excerpt grounded — schema requires non-empty; here we re-verify\n const noEvidence = claims.filter((c) => c.evidence_excerpt.trim().length === 0);\n if (noEvidence.length > 0) {\n results.push({\n family: 'claim_integrity',\n check: 'evidence_excerpt_present',\n status: 'fail',\n detail: `${noEvidence.length} claim(s) have empty evidence_excerpt.`,\n evidence: noEvidence.map((c) => c.claim_id),\n blocks_synthesis: true,\n });\n } else {\n results.push({\n family: 'claim_integrity',\n check: 'evidence_excerpt_present',\n status: 'pass',\n detail: `All candidate claims carry an evidence_excerpt.`,\n evidence: [],\n blocks_synthesis: false,\n });\n }\n\n // claims must reference a source with a successful fetch receipt\n const missingReceipt = claims.filter((c) => !c.source_ids.some((sid) => okReceiptSourceIds.has(sid)));\n if (missingReceipt.length > 0) {\n results.push({\n family: 'claim_integrity',\n check: 'fetch_receipt_anchored',\n status: 'fail',\n detail: `${missingReceipt.length} claim(s) cite source_id(s) without a successful fetch receipt.`,\n evidence: missingReceipt.map((c) => c.claim_id),\n blocks_synthesis: true,\n });\n } else {\n results.push({\n family: 'claim_integrity',\n check: 'fetch_receipt_anchored',\n status: 'pass',\n detail: `All candidate claims trace to at least one successful fetch receipt.`,\n evidence: [],\n blocks_synthesis: false,\n });\n }\n\n // no_source_cluster_monopoly — claim-level: a claim whose every source traces to one publisher\n if (cfg.no_source_cluster_monopoly && claims.length > 0) {\n const monoClaims: string[] = [];\n for (const claim of claims) {\n const pubs = new Set<string>();\n for (const sid of claim.source_ids) {\n const card = input.sources.find((c) => c.source_id === sid);\n if (card?.publisher) pubs.add(card.publisher);\n }\n if (claim.source_ids.length > 0 && pubs.size <= 1) {\n monoClaims.push(claim.claim_id);\n }\n }\n if (monoClaims.length > claims.length / 2) {\n results.push({\n family: 'claim_integrity',\n check: 'no_source_cluster_monopoly',\n status: 'warn',\n detail: `${monoClaims.length}/${claims.length} claim(s) source from a single publisher. Independent corroboration recommended before synthesis.`,\n evidence: monoClaims,\n blocks_synthesis: false,\n });\n } else {\n results.push({\n family: 'claim_integrity',\n check: 'no_source_cluster_monopoly',\n status: 'pass',\n detail: `${monoClaims.length}/${claims.length} claim(s) source from a single publisher (within tolerance).`,\n evidence: [],\n blocks_synthesis: false,\n });\n }\n }\n\n return results;\n}\n","import type { GateCheckResult, GateInput } from '../types.js';\nimport type { ContradictionResolution } from '../../contradictions/resolution-schema.js';\n\nfunction buildEffectiveStatuses(resolutions: ContradictionResolution[] | undefined): Map<string, string> {\n const map = new Map<string, string>();\n if (!resolutions || resolutions.length === 0) return map;\n const sorted = [...resolutions].sort((a, b) => a.resolved_at.localeCompare(b.resolved_at));\n for (const r of sorted) map.set(r.contradiction_id, r.status);\n return map;\n}\n\nexport function checkScopeIntegrity(input: GateInput): GateCheckResult[] {\n const results: GateCheckResult[] = [];\n const claims = input.candidateClaims;\n\n const universal = claims.filter((c) => c.scope === null);\n const scoped = claims.filter((c) => c.scope !== null);\n const withNot = claims.filter((c) => c.not !== null);\n\n // universal claim warning — claims with scope=null cannot be treated as broad\n if (universal.length > 0) {\n results.push({\n family: 'scope_integrity',\n check: 'no_untagged_universal_claims',\n status: 'warn',\n detail: `${universal.length}/${claims.length} candidate claim(s) have scope=null. These must not be treated as broad-applicability claims downstream — they are scope-undetermined, not scope-universal. Run a richer extractor or add scope manually before synthesis.`,\n evidence: universal.map((c) => c.claim_id),\n blocks_synthesis: false,\n });\n } else if (claims.length > 0) {\n results.push({\n family: 'scope_integrity',\n check: 'no_untagged_universal_claims',\n status: 'pass',\n detail: `Every candidate claim has a non-null scope.`,\n evidence: [],\n blocks_synthesis: false,\n });\n }\n\n // not-constraint preservation — informational warn\n if (claims.length > 0) {\n const ratio = withNot.length / claims.length;\n if (ratio < 0.3) {\n results.push({\n family: 'scope_integrity',\n check: 'not_constraint_present',\n status: 'warn',\n detail: `Only ${withNot.length}/${claims.length} candidate claim(s) carry a 'not' constraint. The 'not' field is the structural defense against overgeneralization; sparse coverage means downstream synthesis must be more cautious.`,\n evidence: claims.filter((c) => c.not === null).map((c) => c.claim_id),\n blocks_synthesis: false,\n });\n } else {\n results.push({\n family: 'scope_integrity',\n check: 'not_constraint_present',\n status: 'pass',\n detail: `${withNot.length}/${claims.length} candidate claim(s) carry a 'not' constraint.`,\n evidence: [],\n blocks_synthesis: false,\n });\n }\n }\n\n // overgeneralization risks from contradictions ledger\n const effectiveStatuses = buildEffectiveStatuses(input.resolutions);\n const overgen = input.contradictions.filter((c) => {\n if (c.type !== 'overgeneralization_risk') return false;\n const eff = effectiveStatuses.get(c.contradiction_id);\n return eff !== undefined ? eff === 'unresolved' : c.status === 'unresolved';\n });\n const overgenBlocking = overgen.filter(\n (c) => c.severity === 'blocking' || c.severity === 'high',\n );\n const overgenWarn = overgen.filter(\n (c) => c.severity === 'medium' || c.severity === 'low',\n );\n\n if (overgenBlocking.length > 0) {\n results.push({\n family: 'scope_integrity',\n check: 'no_blocking_overgeneralization',\n status: 'fail',\n detail: `${overgenBlocking.length} unresolved overgeneralization_risk contradiction(s) at high or blocking severity. Contextual claims appear to be promoted into universal rules without scope-widening evidence.`,\n evidence: overgenBlocking.map((c) => c.contradiction_id),\n blocks_synthesis: true,\n });\n } else {\n results.push({\n family: 'scope_integrity',\n check: 'no_blocking_overgeneralization',\n status: 'pass',\n detail: `No high- or blocking-severity overgeneralization_risk contradictions.`,\n evidence: [],\n blocks_synthesis: false,\n });\n }\n\n if (overgenWarn.length > 0) {\n results.push({\n family: 'scope_integrity',\n check: 'low_severity_overgeneralization',\n status: 'warn',\n detail: `${overgenWarn.length} low/medium-severity overgeneralization_risk contradiction(s) recorded. Adversarial review should classify these before synthesis.`,\n evidence: overgenWarn.map((c) => c.contradiction_id),\n blocks_synthesis: false,\n });\n }\n\n // Scope-widening evidence requirement is checked per claim during contradiction mapping;\n // here we surface the universal-vs-scoped ratio as a synthesis-readiness signal.\n if (claims.length > 0) {\n results.push({\n family: 'scope_integrity',\n check: 'scope_tagging_summary',\n status: 'pass',\n detail: `${scoped.length} scoped, ${universal.length} universal/untagged, ${withNot.length} with 'not' constraint.`,\n evidence: [],\n blocks_synthesis: false,\n });\n }\n\n return results;\n}\n","import type { GateCheckResult, GateInput } from '../types.js';\n\nfunction monthsAgo(iso: string): number | null {\n const d = Date.parse(iso);\n if (Number.isNaN(d)) return null;\n return (Date.now() - d) / (1000 * 60 * 60 * 24 * 30.44);\n}\n\nexport function checkFreshness(input: GateInput): GateCheckResult[] {\n const cfg = input.research.gates.freshness;\n const policy = input.research.freshness;\n const results: GateCheckResult[] = [];\n const cards = input.sources;\n\n if (!policy.required && !cfg.required_for_current_topics) {\n results.push({\n family: 'freshness',\n check: 'policy_applicability',\n status: 'pass',\n detail: `Freshness policy not required for this pack.`,\n evidence: [],\n blocks_synthesis: false,\n });\n return results;\n }\n\n if (cards.length === 0) {\n results.push({\n family: 'freshness',\n check: 'policy_applicability',\n status: 'warn',\n detail: `Freshness policy required but no sources to evaluate.`,\n evidence: [],\n blocks_synthesis: false,\n });\n return results;\n }\n\n const maxAge = policy.max_source_age_months;\n const stale: string[] = [];\n const unknownDate: string[] = [];\n\n for (const card of cards) {\n if (!card.published_at) {\n unknownDate.push(card.source_id);\n continue;\n }\n if (maxAge === null) continue;\n const age = monthsAgo(card.published_at);\n if (age === null) {\n unknownDate.push(card.source_id);\n continue;\n }\n if (age > maxAge) stale.push(card.source_id);\n }\n\n if (stale.length > 0) {\n if (cfg.stale_source_policy === 'fail') {\n results.push({\n family: 'freshness',\n check: 'no_stale_sources',\n status: 'fail',\n detail: `${stale.length} source(s) older than ${maxAge ?? 'unset'} months. Pack policy: fail.`,\n evidence: stale,\n blocks_synthesis: true,\n });\n } else {\n results.push({\n family: 'freshness',\n check: 'no_stale_sources',\n status: 'warn',\n detail: `${stale.length} source(s) older than ${maxAge ?? 'unset'} months. Pack policy: warn.`,\n evidence: stale,\n blocks_synthesis: false,\n });\n }\n } else {\n results.push({\n family: 'freshness',\n check: 'no_stale_sources',\n status: 'pass',\n detail: maxAge === null\n ? `No max_source_age_months configured; per-source recency not evaluated.`\n : `No source older than ${maxAge} months.`,\n evidence: [],\n blocks_synthesis: false,\n });\n }\n\n if (unknownDate.length > 0) {\n results.push({\n family: 'freshness',\n check: 'publication_date_known',\n status: 'warn',\n detail: `${unknownDate.length} source(s) have no parseable published_at. Recency cannot be evaluated for these.`,\n evidence: unknownDate,\n blocks_synthesis: false,\n });\n } else {\n results.push({\n family: 'freshness',\n check: 'publication_date_known',\n status: 'pass',\n detail: `All sources have a recorded published_at date.`,\n evidence: [],\n blocks_synthesis: false,\n });\n }\n\n return results;\n}\n","import type { GateCheckResult, GateInput } from '../types.js';\nimport type { ContradictionResolution } from '../../contradictions/resolution-schema.js';\n\nfunction buildEffectiveStatuses(resolutions: ContradictionResolution[] | undefined): Map<string, string> {\n const map = new Map<string, string>();\n if (!resolutions || resolutions.length === 0) return map;\n const sorted = [...resolutions].sort((a, b) => a.resolved_at.localeCompare(b.resolved_at));\n for (const r of sorted) map.set(r.contradiction_id, r.status);\n return map;\n}\n\nexport function checkContradiction(input: GateInput): GateCheckResult[] {\n const cfg = input.research.gates.contradiction;\n const results: GateCheckResult[] = [];\n const all = input.contradictions;\n const effectiveStatuses = buildEffectiveStatuses(input.resolutions);\n const unresolved = all.filter((c) => {\n const eff = effectiveStatuses.get(c.contradiction_id);\n return eff !== undefined ? eff === 'unresolved' : c.status === 'unresolved';\n });\n const blocking = unresolved.filter(\n (c) => c.severity === 'blocking' || c.severity === 'high',\n );\n\n // unresolved contradictions visibility\n if (unresolved.length > 0) {\n results.push({\n family: 'contradiction',\n check: 'unresolved_visible',\n status: 'warn',\n detail: `${unresolved.length} unresolved contradiction(s) recorded. The contradiction ledger is the audit substrate; the gate engine does not resolve, only surfaces.`,\n evidence: unresolved.map((c) => c.contradiction_id),\n blocks_synthesis: false,\n });\n } else {\n results.push({\n family: 'contradiction',\n check: 'unresolved_visible',\n status: 'pass',\n detail: all.length === 0\n ? `No contradictions recorded. A clean ledger is not proof of completeness — it means the detector found nothing.`\n : `All ${all.length} contradiction(s) recorded are resolved.`,\n evidence: [],\n blocks_synthesis: false,\n });\n }\n\n // blocking contradictions actually block synthesis\n if (cfg.unresolved_contradictions_block_synthesis && blocking.length > 0) {\n results.push({\n family: 'contradiction',\n check: 'unresolved_contradictions_block_synthesis',\n status: 'fail',\n detail: `${blocking.length} unresolved contradiction(s) at high or blocking severity. Synthesis is not eligible until these are reconciled, preserved deliberately, or rejected.`,\n evidence: blocking.map((c) => c.contradiction_id),\n blocks_synthesis: true,\n });\n } else {\n results.push({\n family: 'contradiction',\n check: 'unresolved_contradictions_block_synthesis',\n status: 'pass',\n detail: cfg.unresolved_contradictions_block_synthesis\n ? `No high- or blocking-severity unresolved contradictions.`\n : `Pack policy does not block synthesis on unresolved contradictions; ${blocking.length} high/blocking still recorded for visibility.`,\n evidence: [],\n blocks_synthesis: false,\n });\n }\n\n // contradiction-required check — only if pack policy says so\n if (cfg.required && all.length === 0) {\n results.push({\n family: 'contradiction',\n check: 'contradiction_required_by_policy',\n status: 'warn',\n detail: `Pack policy requires contradiction coverage but no contradictions are recorded. A clean ledger may indicate a thin-source-set rather than genuine consensus. Adversarial review should re-examine.`,\n evidence: [],\n blocks_synthesis: false,\n });\n } else if (cfg.required) {\n results.push({\n family: 'contradiction',\n check: 'contradiction_required_by_policy',\n status: 'pass',\n detail: `Contradiction ledger has ${all.length} entry(ies); policy satisfied.`,\n evidence: [],\n blocks_synthesis: false,\n });\n }\n\n return results;\n}\n","import type { GateCheckResult, GateInput } from '../types.js';\n\nexport function checkSectionBudget(input: GateInput): GateCheckResult[] {\n const cfg = input.research.gates.section_budget;\n const section = input.section;\n const results: GateCheckResult[] = [];\n\n if (!section.max_time_minutes || section.max_time_minutes <= 0) {\n results.push({\n family: 'section_budget',\n check: 'budget_configured',\n status: 'warn',\n detail: `Section has no max_time_minutes configured.`,\n evidence: [section.id],\n blocks_synthesis: false,\n });\n } else {\n results.push({\n family: 'section_budget',\n check: 'budget_configured',\n status: 'pass',\n detail: `Section budget: ${section.max_time_minutes} minute(s). Pack default: ${cfg.max_time_minutes}.`,\n evidence: [],\n blocks_synthesis: false,\n });\n }\n\n results.push({\n family: 'section_budget',\n check: 'runtime_tracking',\n status: 'warn',\n detail: `Runtime tracking not yet implemented in v0.1; configured budget is recorded for future enforcement only. Extension policy (extension_requires_evidence=${cfg.extension_requires_evidence}) is documented but not enforced until actual run timestamps are tracked.`,\n evidence: [],\n blocks_synthesis: false,\n });\n\n return results;\n}\n","import type {\n GateCheckResult,\n GateInput,\n WaiverApplication,\n} from '../types.js';\n\nexport interface WaiverPassResult {\n updatedResults: GateCheckResult[];\n waivers_applied: WaiverApplication[];\n waiver_validation_failures: GateCheckResult[];\n}\n\nexport function applyWaivers(\n input: GateInput,\n results: GateCheckResult[],\n): WaiverPassResult {\n const waiver = input.research.primary_source_waiver;\n const cfg = input.research.gates.source_floor;\n const updated = results.map((r) => ({ ...r }));\n const applied: WaiverApplication[] = [];\n const validationFailures: GateCheckResult[] = [];\n\n if (waiver.status !== 'granted') {\n return { updatedResults: updated, waivers_applied: applied, waiver_validation_failures: validationFailures };\n }\n\n if (!waiver.reason || waiver.reason.trim().length === 0) {\n validationFailures.push({\n family: 'waivers',\n check: 'primary_source_waiver_reason_required',\n status: 'fail',\n detail: `primary_source_waiver.status is \"granted\" but reason is empty. Waiver is invalid; original failures stand.`,\n evidence: [],\n blocks_synthesis: true,\n });\n return { updatedResults: updated, waivers_applied: applied, waiver_validation_failures: validationFailures };\n }\n\n if (waiver.compensating_controls.length === 0) {\n validationFailures.push({\n family: 'waivers',\n check: 'primary_source_waiver_compensating_controls_required',\n status: 'fail',\n detail: `primary_source_waiver.status is \"granted\" but compensating_controls is empty. Waiver is invalid; original failures stand.`,\n evidence: [],\n blocks_synthesis: true,\n });\n return { updatedResults: updated, waivers_applied: applied, waiver_validation_failures: validationFailures };\n }\n\n if (!cfg.primary_source_waiver_allowed) {\n validationFailures.push({\n family: 'waivers',\n check: 'primary_source_waiver_allowed_by_pack',\n status: 'fail',\n detail: `Pack policy gates.source_floor.primary_source_waiver_allowed=false; granted waiver cannot be applied.`,\n evidence: [],\n blocks_synthesis: true,\n });\n return { updatedResults: updated, waivers_applied: applied, waiver_validation_failures: validationFailures };\n }\n\n // Convert primary_sources_required fail → pass_with_waiver\n for (let i = 0; i < updated.length; i += 1) {\n const r = updated[i]!;\n if (\n r.family === 'source_floor' &&\n r.check === 'primary_sources_required' &&\n r.status === 'fail'\n ) {\n const original = r.status;\n updated[i] = {\n ...r,\n status: 'pass_with_waiver',\n detail: `${r.detail} Waiver granted with ${waiver.compensating_controls.length} compensating control(s); converted from fail to pass_with_waiver.`,\n blocks_synthesis: false,\n };\n applied.push({\n family: 'source_floor',\n check: 'primary_sources_required',\n reason: waiver.reason,\n compensating_controls: waiver.compensating_controls,\n original_status: original,\n new_status: 'pass_with_waiver',\n });\n }\n }\n\n return { updatedResults: updated, waivers_applied: applied, waiver_validation_failures: validationFailures };\n}\n","import type { GateCheckResult, GateInput } from '../types.js';\nimport type { ClaimReview } from '../../review/schema.js';\n\nconst MIN_ACCEPTED_CLAIMS = 3;\nconst MIN_ACCEPTED_SOURCES = 2;\n\nexport function checkAcceptedClaimFloor(input: GateInput): GateCheckResult[] {\n const reviews = input.claimReviews;\n\n // Status-wins-by-latest: for each claim_id, the latest review entry wins.\n const latestByClaimId = new Map<string, ClaimReview>();\n for (const r of reviews) {\n const existing = latestByClaimId.get(r.claim_id);\n if (!existing || r.created_at > existing.created_at) {\n latestByClaimId.set(r.claim_id, r);\n }\n }\n\n const acceptedIds = [...latestByClaimId.values()]\n .filter((r) => r.decision === 'accepted_for_synthesis')\n .map((r) => r.claim_id);\n\n const acceptedCount = acceptedIds.length;\n\n // Map claim_id → source_ids from all claims in the section.\n const claimSourceMap = new Map<string, string[]>();\n for (const claim of input.claims) {\n claimSourceMap.set(claim.claim_id, claim.source_ids);\n }\n\n const distinctSources = new Set<string>();\n for (const cid of acceptedIds) {\n for (const sid of claimSourceMap.get(cid) ?? []) {\n distinctSources.add(sid);\n }\n }\n const distinctSourceCount = distinctSources.size;\n\n const belowClaimFloor = acceptedCount < MIN_ACCEPTED_CLAIMS;\n const belowSourceFloor = distinctSourceCount < MIN_ACCEPTED_SOURCES;\n\n if (belowClaimFloor || belowSourceFloor) {\n return [\n {\n family: 'accepted_claim_floor',\n check: 'min_accepted_claims_and_sources',\n status: 'fail',\n detail: `accepted-claim floor violated: ${acceptedCount} accepted claims from ${distinctSourceCount} sources (minimum: ${MIN_ACCEPTED_CLAIMS} claims from ${MIN_ACCEPTED_SOURCES} sources). Waivers cannot bypass evidence existence.`,\n evidence: acceptedIds,\n blocks_synthesis: true,\n },\n ];\n }\n\n return [\n {\n family: 'accepted_claim_floor',\n check: 'min_accepted_claims_and_sources',\n status: 'pass',\n detail: `${acceptedCount} accepted claims from ${distinctSourceCount} distinct sources (minimum: ${MIN_ACCEPTED_CLAIMS} from ${MIN_ACCEPTED_SOURCES}).`,\n evidence: [],\n blocks_synthesis: false,\n },\n ];\n}\n","export { checkSourceFloor } from './source-floor.js';\nexport { checkClaimIntegrity } from './claim-integrity.js';\nexport { checkScopeIntegrity } from './scope-integrity.js';\nexport { checkFreshness } from './freshness.js';\nexport { checkContradiction } from './contradiction.js';\nexport { checkSectionBudget } from './section-budget.js';\nexport { applyWaivers } from './waivers.js';\nexport { checkAcceptedClaimFloor } from './accepted-claim-floor.js';\n","import type { SectionGateResult } from './types.js';\n\nconst STATUS_GLYPH: Record<string, string> = {\n pass: '[PASS]',\n warn: '[WARN]',\n fail: '[FAIL]',\n pass_with_waiver: '[PASS+WAIVER]',\n warn_with_waiver: '[WARN+WAIVER]',\n};\n\nexport function renderGateMarkdown(result: SectionGateResult): string {\n const lines: string[] = [];\n lines.push(`# Gate Result: ${result.section_id}`);\n lines.push('');\n lines.push(`**Verdict:** ${result.verdict.toUpperCase()}`);\n lines.push(`**Synthesis eligible:** ${result.synthesis_eligible ? 'yes' : 'no'}`);\n lines.push(`**Checked at:** ${result.checked_at}`);\n lines.push('');\n lines.push(`> ${result.summary}`);\n lines.push('');\n\n if (result.blocking_reasons.length > 0) {\n lines.push('## Blocking reasons');\n lines.push('');\n for (const r of result.blocking_reasons) {\n lines.push(`- ${r}`);\n }\n lines.push('');\n }\n\n lines.push('## Counts');\n lines.push('');\n lines.push(`- Claims: ${result.claim_counts.total} total, ${result.claim_counts.candidate} candidate, ${result.claim_counts.with_evidence_excerpt} with evidence excerpt, ${result.claim_counts.orphans} orphan`);\n lines.push(`- Sources: ${result.source_counts.total} total (${result.source_counts.primary} primary / ${result.source_counts.secondary} secondary / ${result.source_counts.docs} docs / ${result.source_counts.forum} forum / ${result.source_counts.benchmark} benchmark / ${result.source_counts.unknown} unknown), ${result.source_counts.independent_publishers} independent publishers, ${result.source_counts.failed_fetches} failed fetches`);\n lines.push(`- Contradictions: ${result.contradiction_counts.total} total (${result.contradiction_counts.unresolved} unresolved, ${result.contradiction_counts.blocking} high/blocking)`);\n lines.push(`- Scope integrity: ${result.scope_integrity_summary.scoped_claims} scoped, ${result.scope_integrity_summary.universal_claims} universal/untagged, ${result.scope_integrity_summary.with_not_constraint} with 'not' constraint, ${result.scope_integrity_summary.overgen_risks_total} overgeneralization risk(s) (${result.scope_integrity_summary.overgen_risks_blocking} blocking)`);\n lines.push(`- Freshness: policy ${result.freshness_summary.policy_required ? 'required' : 'not required'}, ${result.freshness_summary.stale_count} stale, ${result.freshness_summary.unknown_date_count} unknown date`);\n lines.push('');\n\n if (result.waivers_applied.length > 0) {\n lines.push('## Waivers applied');\n lines.push('');\n for (const w of result.waivers_applied) {\n lines.push(`### ${w.family}.${w.check}`);\n lines.push('');\n lines.push(`- **Original status:** ${w.original_status}`);\n lines.push(`- **New status:** ${w.new_status}`);\n lines.push(`- **Reason:** ${w.reason}`);\n lines.push(`- **Compensating controls:**`);\n for (const c of w.compensating_controls) {\n lines.push(` - ${c}`);\n }\n lines.push('');\n }\n }\n\n lines.push('## Gate results');\n lines.push('');\n for (const r of result.gate_results) {\n const glyph = STATUS_GLYPH[r.status] ?? `[${r.status.toUpperCase()}]`;\n lines.push(`### ${glyph} ${r.family}.${r.check}`);\n lines.push('');\n lines.push(`${r.detail}`);\n lines.push('');\n lines.push(`*Blocks synthesis:* ${r.blocks_synthesis}`);\n if (r.evidence.length > 0) {\n lines.push('');\n lines.push(`*Evidence:* ${r.evidence.slice(0, 10).map((e) => `\\`${e}\\``).join(', ')}${r.evidence.length > 10 ? ` (+${r.evidence.length - 10} more)` : ''}`);\n }\n lines.push('');\n }\n\n if (result.next_actions.length > 0) {\n lines.push('## Next actions');\n lines.push('');\n for (const a of result.next_actions) {\n lines.push(`- ${a}`);\n }\n lines.push('');\n }\n\n return lines.join('\\n');\n}\n","import { z } from 'zod';\n\nexport const GateFamilySchema = z.enum([\n 'source_floor',\n 'claim_integrity',\n 'scope_integrity',\n 'freshness',\n 'contradiction',\n 'section_budget',\n 'waivers',\n 'accepted_claim_floor',\n]);\n\nexport const GateCheckStatusSchema = z.enum([\n 'pass',\n 'warn',\n 'fail',\n 'pass_with_waiver',\n 'warn_with_waiver',\n]);\n\nexport const VerdictSchema = z.enum(['pass', 'warn', 'fail', 'blocked']);\n\nexport const GateCheckResultSchema = z.object({\n family: GateFamilySchema,\n check: z.string().min(1),\n status: GateCheckStatusSchema,\n detail: z.string(),\n evidence: z.array(z.string()),\n blocks_synthesis: z.boolean(),\n});\n\nexport const WaiverApplicationSchema = z.object({\n family: GateFamilySchema,\n check: z.string().min(1),\n reason: z.string().min(1),\n compensating_controls: z.array(z.string()),\n original_status: GateCheckStatusSchema,\n new_status: GateCheckStatusSchema,\n});\n\nexport const SectionGateResultSchema = z.object({\n section_id: z.string().regex(/^[0-9]{2}-[a-z0-9-]+$/),\n verdict: VerdictSchema,\n summary: z.string(),\n checked_at: z.string(),\n synthesis_eligible: z.boolean(),\n gate_results: z.array(GateCheckResultSchema),\n failures: z.array(GateCheckResultSchema),\n warnings: z.array(GateCheckResultSchema),\n waivers_applied: z.array(WaiverApplicationSchema),\n blocking_reasons: z.array(z.string()),\n claim_counts: z.object({\n total: z.number().int().nonnegative(),\n candidate: z.number().int().nonnegative(),\n with_evidence_excerpt: z.number().int().nonnegative(),\n with_source_hashes: z.number().int().nonnegative(),\n with_scope: z.number().int().nonnegative(),\n with_not: z.number().int().nonnegative(),\n universal_scope_null: z.number().int().nonnegative(),\n orphans: z.number().int().nonnegative(),\n }),\n source_counts: z.object({\n total: z.number().int().nonnegative(),\n primary: z.number().int().nonnegative(),\n secondary: z.number().int().nonnegative(),\n forum: z.number().int().nonnegative(),\n benchmark: z.number().int().nonnegative(),\n docs: z.number().int().nonnegative(),\n unknown: z.number().int().nonnegative(),\n independent_publishers: z.number().int().nonnegative(),\n failed_fetches: z.number().int().nonnegative(),\n }),\n contradiction_counts: z.object({\n total: z.number().int().nonnegative(),\n unresolved: z.number().int().nonnegative(),\n blocking: z.number().int().nonnegative(),\n by_type: z.record(z.string(), z.number().int().nonnegative()),\n }),\n freshness_summary: z.object({\n policy_required: z.boolean(),\n max_source_age_months: z.number().int().nullable(),\n stale_source_policy: z.enum(['warn', 'fail']),\n stale_count: z.number().int().nonnegative(),\n unknown_date_count: z.number().int().nonnegative(),\n }),\n scope_integrity_summary: z.object({\n universal_claims: z.number().int().nonnegative(),\n scoped_claims: z.number().int().nonnegative(),\n with_not_constraint: z.number().int().nonnegative(),\n overgen_risks_total: z.number().int().nonnegative(),\n overgen_risks_blocking: z.number().int().nonnegative(),\n }),\n next_actions: z.array(z.string()),\n});\n\nexport type SectionGateResult = z.infer<typeof SectionGateResultSchema>;\n","import { existsSync } from 'node:fs';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { join, resolve } from 'node:path';\nimport { parse as yamlParse, stringify as yamlStringify } from 'yaml';\n\nimport { PackNotFoundError, SectionNotFoundError } from '../errors.js';\nimport { ResearchYamlSchema, type ResearchYaml } from '../intake/schema.js';\nimport { ClaimSchema, type Claim } from '../claims/schema.js';\nimport { ContradictionSchema, type Contradiction } from '../contradictions/schema.js';\nimport { ContradictionResolutionSchema, type ContradictionResolution } from '../contradictions/resolution-schema.js';\nimport { FetchReceiptSchema, SourceCardSchema, type FetchReceipt, type SourceCard } from '../sources/schema.js';\nimport { ClaimReviewSchema, type ClaimReview } from '../review/schema.js';\n\nimport {\n checkClaimIntegrity,\n checkContradiction,\n checkFreshness,\n checkScopeIntegrity,\n checkSectionBudget,\n checkSourceFloor,\n applyWaivers,\n checkAcceptedClaimFloor,\n} from './checks/index.js';\nimport { renderGateMarkdown } from './markdown.js';\nimport { SectionGateResultSchema } from './schema.js';\nimport type {\n ClaimCounts,\n ContradictionCounts,\n FreshnessSummary,\n GateCheckResult,\n GateInput,\n RunGateOptions,\n ScopeIntegritySummary,\n SectionGateResult,\n SourceCounts,\n Verdict,\n} from './types.js';\n\nasync function readJsonl<T>(\n packPath: string,\n rel: string,\n parse: (raw: unknown) => T,\n): Promise<T[]> {\n const path = join(packPath, rel);\n if (!existsSync(path)) return [];\n const text = await readFile(path, 'utf8');\n const out: T[] = [];\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n out.push(parse(JSON.parse(line)));\n }\n return out;\n}\n\nasync function readSourceCards(packPath: string): Promise<SourceCard[]> {\n const dir = join(packPath, 'evidence', 'source-cards');\n if (!existsSync(dir)) return [];\n const { readdir } = await import('node:fs/promises');\n const entries = await readdir(dir);\n const cards: SourceCard[] = [];\n for (const entry of entries) {\n if (!entry.endsWith('.json')) continue;\n const text = await readFile(join(dir, entry), 'utf8');\n cards.push(SourceCardSchema.parse(JSON.parse(text)));\n }\n return cards;\n}\n\nfunction summarizeClaimCounts(input: GateInput): ClaimCounts {\n const c = input.claims;\n const cand = input.candidateClaims;\n const cardIds = new Set(input.sources.map((s) => s.source_id));\n return {\n total: c.length,\n candidate: cand.length,\n with_evidence_excerpt: cand.filter((x) => x.evidence_excerpt.trim().length > 0).length,\n with_source_hashes: cand.filter((x) => x.source_hashes.length > 0).length,\n with_scope: cand.filter((x) => x.scope !== null).length,\n with_not: cand.filter((x) => x.not !== null).length,\n universal_scope_null: cand.filter((x) => x.scope === null).length,\n orphans: cand.filter((x) => x.source_ids.some((sid) => !cardIds.has(sid))).length,\n };\n}\n\nfunction summarizeSourceCounts(input: GateInput): SourceCounts {\n const cards = input.sources;\n const failed = input.receipts.filter((r) => r.fetch_outcome !== 'ok').length;\n const publishers = new Set(\n cards.map((c) => c.publisher).filter((p): p is string => typeof p === 'string'),\n );\n return {\n total: cards.length,\n primary: cards.filter((c) => c.source_type === 'primary').length,\n secondary: cards.filter((c) => c.source_type === 'secondary').length,\n forum: cards.filter((c) => c.source_type === 'forum').length,\n benchmark: cards.filter((c) => c.source_type === 'benchmark').length,\n docs: cards.filter((c) => c.source_type === 'docs').length,\n unknown: cards.filter((c) => c.source_type === 'unknown').length,\n independent_publishers: publishers.size,\n failed_fetches: failed,\n };\n}\n\nfunction buildEffectiveStatuses(resolutions: ContradictionResolution[] | undefined): Map<string, string> {\n const map = new Map<string, string>();\n if (!resolutions || resolutions.length === 0) return map;\n const sorted = [...resolutions].sort((a, b) => a.resolved_at.localeCompare(b.resolved_at));\n for (const r of sorted) map.set(r.contradiction_id, r.status);\n return map;\n}\n\nfunction isEffectivelyUnresolved(contradictionId: string, rawStatus: string, effectiveStatuses: Map<string, string>): boolean {\n const effective = effectiveStatuses.get(contradictionId);\n return effective !== undefined ? effective === 'unresolved' : rawStatus === 'unresolved';\n}\n\nfunction summarizeContradictionCounts(input: GateInput): ContradictionCounts {\n const all = input.contradictions;\n const effectiveStatuses = buildEffectiveStatuses(input.resolutions);\n const unresolved = all.filter((c) => isEffectivelyUnresolved(c.contradiction_id, c.status, effectiveStatuses));\n const blocking = unresolved.filter(\n (c) => c.severity === 'blocking' || c.severity === 'high',\n );\n const byType: Record<string, number> = {};\n for (const c of all) {\n byType[c.type] = (byType[c.type] ?? 0) + 1;\n }\n return {\n total: all.length,\n unresolved: unresolved.length,\n blocking: blocking.length,\n by_type: byType,\n };\n}\n\nfunction summarizeFreshness(input: GateInput): FreshnessSummary {\n const cfg = input.research.gates.freshness;\n const policy = input.research.freshness;\n const cards = input.sources;\n let stale = 0;\n let unknownDate = 0;\n for (const c of cards) {\n if (!c.published_at) {\n unknownDate += 1;\n continue;\n }\n if (policy.max_source_age_months === null) continue;\n const d = Date.parse(c.published_at);\n if (Number.isNaN(d)) {\n unknownDate += 1;\n continue;\n }\n const ageMonths = (Date.now() - d) / (1000 * 60 * 60 * 24 * 30.44);\n if (ageMonths > policy.max_source_age_months) stale += 1;\n }\n return {\n policy_required: policy.required,\n max_source_age_months: policy.max_source_age_months,\n stale_source_policy: cfg.stale_source_policy,\n stale_count: stale,\n unknown_date_count: unknownDate,\n };\n}\n\nfunction summarizeScopeIntegrity(input: GateInput): ScopeIntegritySummary {\n const cand = input.candidateClaims;\n const effectiveStatuses = buildEffectiveStatuses(input.resolutions);\n const overgen = input.contradictions.filter(\n (c) => c.type === 'overgeneralization_risk' && isEffectivelyUnresolved(c.contradiction_id, c.status, effectiveStatuses),\n );\n const blocking = overgen.filter(\n (c) => c.severity === 'blocking' || c.severity === 'high',\n );\n return {\n universal_claims: cand.filter((c) => c.scope === null).length,\n scoped_claims: cand.filter((c) => c.scope !== null).length,\n with_not_constraint: cand.filter((c) => c.not !== null).length,\n overgen_risks_total: overgen.length,\n overgen_risks_blocking: blocking.length,\n };\n}\n\nfunction deriveVerdict(results: GateCheckResult[]): {\n verdict: Verdict;\n synthesis_eligible: boolean;\n blocking_reasons: string[];\n} {\n const blocking = results.filter((r) => r.blocks_synthesis && (r.status === 'fail' || r.status === 'warn_with_waiver'));\n const fails = results.filter((r) => r.status === 'fail');\n const warns = results.filter((r) => r.status === 'warn' || r.status === 'warn_with_waiver');\n if (blocking.length > 0) {\n return {\n verdict: 'blocked',\n synthesis_eligible: false,\n blocking_reasons: blocking.map((r) => `${r.family}.${r.check}: ${r.detail}`),\n };\n }\n if (fails.length > 0) {\n return { verdict: 'fail', synthesis_eligible: true, blocking_reasons: [] };\n }\n if (warns.length > 0) {\n return { verdict: 'warn', synthesis_eligible: true, blocking_reasons: [] };\n }\n return { verdict: 'pass', synthesis_eligible: true, blocking_reasons: [] };\n}\n\nfunction buildNextActions(results: GateCheckResult[]): string[] {\n const actions: string[] = [];\n for (const r of results) {\n if (r.status === 'fail') {\n switch (r.family) {\n case 'source_floor':\n if (r.check === 'min_sources') actions.push('Run `research-os gather` with additional URLs to reach the minimum source count.');\n else if (r.check === 'min_independent_publishers') actions.push('Add sources from additional publishers to satisfy publisher diversity.');\n else if (r.check === 'primary_sources_required') actions.push('Add primary sources or grant a primary_source_waiver in research.yaml with a reason and compensating_controls.');\n break;\n case 'claim_integrity':\n if (r.check === 'no_orphan_claims') actions.push('Re-run gather for missing source_ids or remove orphan claims from claims.jsonl.');\n else if (r.check === 'fetch_receipt_anchored') actions.push('Re-run gather to produce fresh fetch receipts for the affected claims.');\n else if (r.check === 'source_hashes_present' || r.check === 'evidence_excerpt_present') actions.push('Re-run claim extract; affected claims are missing fields the schema would reject.');\n break;\n case 'scope_integrity':\n if (r.check === 'no_blocking_overgeneralization') actions.push('Reconcile blocking overgeneralization_risk contradictions, or mark them preserved_deliberately with documented rationale.');\n break;\n case 'contradiction':\n if (r.check === 'unresolved_contradictions_block_synthesis') actions.push('Resolve, preserve, or reject blocking contradictions before synthesis.');\n break;\n case 'freshness':\n if (r.check === 'no_stale_sources') actions.push('Replace stale sources with recent ones, or change pack freshness policy if intentional.');\n break;\n case 'waivers':\n actions.push('Fix the waiver entry in research.yaml.primary_source_waiver (reason + compensating_controls + pack policy must allow it).');\n break;\n case 'accepted_claim_floor':\n actions.push('Gather more sources, extract claims, and promote at least 3 claims from at least 2 distinct sources to accepted_for_synthesis via review. Waivers cannot bypass this floor.');\n break;\n default:\n break;\n }\n }\n }\n return Array.from(new Set(actions));\n}\n\nasync function loadResearchYaml(packPath: string): Promise<ResearchYaml> {\n const yamlPath = join(packPath, 'research.yaml');\n if (!existsSync(yamlPath)) throw new PackNotFoundError(packPath);\n const text = await readFile(yamlPath, 'utf8');\n return ResearchYamlSchema.parse(yamlParse(text));\n}\n\nasync function updateSectionStatus(\n packPath: string,\n sectionId: string,\n synthesisEligible: boolean,\n): Promise<void> {\n const yamlPath = join(packPath, 'research.yaml');\n const text = await readFile(yamlPath, 'utf8');\n const research = ResearchYamlSchema.parse(yamlParse(text));\n const idx = research.sections.findIndex((s) => s.id === sectionId);\n if (idx < 0) return;\n const current = research.sections[idx]!;\n // Only upgrade to gated when synthesis-eligible and not already past it.\n if (synthesisEligible) {\n const order = ['draft', 'gathering', 'gated', 'reviewed', 'frozen'] as const;\n const currentRank = order.indexOf(current.status);\n const gatedRank = order.indexOf('gated');\n if (currentRank < gatedRank) {\n research.sections[idx] = { ...current, status: 'gated' };\n await writeFile(yamlPath, yamlStringify(research, { lineWidth: 0 }), 'utf8');\n }\n }\n}\n\nexport async function gate(options: RunGateOptions): Promise<SectionGateResult> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n if (!existsSync(join(packPath, 'research.yaml'))) throw new PackNotFoundError(packPath);\n const sectionDir = join(packPath, 'sections', options.sectionId);\n if (!existsSync(sectionDir)) throw new SectionNotFoundError(options.sectionId);\n const research = await loadResearchYaml(packPath);\n const section = research.sections.find((s) => s.id === options.sectionId);\n if (!section) throw new SectionNotFoundError(options.sectionId);\n\n const claims = await readJsonl<Claim>(packPath, `sections/${options.sectionId}/claims.jsonl`, (r) => ClaimSchema.parse(r));\n const candidateClaims = claims.filter((c) => c.review_state === 'candidate');\n const sources = await readSourceCards(packPath);\n const receipts = await readJsonl<FetchReceipt>(packPath, 'evidence/fetch-log.jsonl', (r) => FetchReceiptSchema.parse(r));\n const contradictions = await readJsonl<Contradiction>(packPath, `sections/${options.sectionId}/contradictions.jsonl`, (r) => ContradictionSchema.parse(r));\n const claimReviews = await readJsonl<ClaimReview>(packPath, `sections/${options.sectionId}/claim-reviews.jsonl`, (r) => ClaimReviewSchema.parse(r));\n const resolutions = await readJsonl<ContradictionResolution>(packPath, `sections/${options.sectionId}/contradiction-resolutions.jsonl`, (r) => ContradictionResolutionSchema.parse(r));\n\n const input: GateInput = {\n research,\n section,\n claims,\n candidateClaims,\n sources,\n receipts,\n contradictions,\n claimReviews,\n resolutions,\n };\n\n const rawResults: GateCheckResult[] = [\n ...checkSourceFloor(input),\n ...checkClaimIntegrity(input),\n ...checkScopeIntegrity(input),\n ...checkFreshness(input),\n ...checkContradiction(input),\n ...checkSectionBudget(input),\n ...checkAcceptedClaimFloor(input),\n ];\n\n const { updatedResults, waivers_applied, waiver_validation_failures } = applyWaivers(input, rawResults);\n const finalResults = [...updatedResults, ...waiver_validation_failures];\n\n const failures = finalResults.filter((r) => r.status === 'fail');\n const warnings = finalResults.filter((r) => r.status === 'warn' || r.status === 'warn_with_waiver');\n const { verdict, synthesis_eligible, blocking_reasons } = deriveVerdict(finalResults);\n\n const result: SectionGateResult = SectionGateResultSchema.parse({\n section_id: options.sectionId,\n verdict,\n summary: buildSummary(verdict, synthesis_eligible, failures.length, warnings.length, waivers_applied.length),\n checked_at: new Date().toISOString(),\n synthesis_eligible,\n gate_results: finalResults,\n failures,\n warnings,\n waivers_applied,\n blocking_reasons,\n claim_counts: summarizeClaimCounts(input),\n source_counts: summarizeSourceCounts(input),\n contradiction_counts: summarizeContradictionCounts(input),\n freshness_summary: summarizeFreshness(input),\n scope_integrity_summary: summarizeScopeIntegrity(input),\n next_actions: buildNextActions(finalResults),\n });\n\n const auditsDir = join(packPath, 'audits');\n await mkdir(auditsDir, { recursive: true });\n await writeFile(\n join(auditsDir, `${options.sectionId}-gate.json`),\n JSON.stringify(result, null, 2),\n 'utf8',\n );\n await writeFile(\n join(auditsDir, `${options.sectionId}-gate.md`),\n renderGateMarkdown(result),\n 'utf8',\n );\n\n await updateSectionStatus(packPath, options.sectionId, synthesis_eligible);\n\n return result;\n}\n\nfunction buildSummary(\n verdict: Verdict,\n eligible: boolean,\n failureCount: number,\n warningCount: number,\n waiverCount: number,\n): string {\n const eligibility = eligible ? 'synthesis-eligible' : 'NOT synthesis-eligible';\n const failurePart = failureCount > 0 ? `${failureCount} failure(s)` : 'no failures';\n const warningPart = warningCount > 0 ? `${warningCount} warning(s)` : 'no warnings';\n const waiverPart = waiverCount > 0 ? `${waiverCount} waiver(s) applied` : 'no waivers';\n return `Verdict: ${verdict}. ${eligibility}. ${failurePart}; ${warningPart}; ${waiverPart}.`;\n}\n","export { gate } from './run.js';\nexport {\n checkSourceFloor,\n checkClaimIntegrity,\n checkScopeIntegrity,\n checkFreshness,\n checkContradiction,\n checkSectionBudget,\n applyWaivers,\n} from './checks/index.js';\nexport { renderGateMarkdown } from './markdown.js';\nexport {\n GateFamilySchema,\n GateCheckStatusSchema,\n VerdictSchema,\n GateCheckResultSchema,\n WaiverApplicationSchema,\n SectionGateResultSchema,\n} from './schema.js';\nexport type {\n GateFamily,\n GateCheckStatus,\n Verdict,\n GateCheckResult,\n WaiverApplication,\n ClaimCounts,\n SourceCounts,\n ContradictionCounts,\n FreshnessSummary,\n ScopeIntegritySummary,\n SectionGateResult,\n GateInput,\n RunGateOptions,\n} from './types.js';\n","// Review profile machinery. Each review run lives under a named profile so\n// A/B reviewer experiments don't silently overwrite the section's effective\n// review state. The \"active\" profile (recorded in\n// sections/<id>/review-active.json) is the one whose decisions canonical\n// consumers see; all other profiles are calibration evidence.\n//\n// Reads gracefully fall back when no profile machinery is set up — the\n// pre-profile dogfood pack continues to work because consumers still read\n// from canonical paths.\n\nimport { existsSync } from 'node:fs';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { z } from 'zod';\n\nexport const DEFAULT_PROFILE = 'default';\n\n// A reviewer-calibration snapshot the promoter recorded at the moment they\n// chose to trust this profile. Optional but strongly encouraged — gate/\n// audit/freeze can use this to explain (not just assert) why the active\n// review state is the active review state.\nexport const PromotionCalibrationSummarySchema = z.object({\n fixture: z.string().nullable().default(null),\n good_false_positive_rate: z.string().nullable().default(null),\n bad_any_flag_recall: z.string().nullable().default(null),\n strict_category_recall: z.string().nullable().default(null),\n unsupported_claim_recall: z.string().nullable().default(null),\n notes: z.string().nullable().default(null),\n});\n\nexport const ReviewActiveSchema = z.object({\n active_profile: z.string().min(1),\n promoted_at: z.string(),\n promoted_method: z.string(),\n promoted_reviewer: z.string(),\n // Free-text reason the profile was promoted. Recorded once at promotion\n // time; not derived from artifacts. Required.\n promotion_reason: z.string().min(8).default('promoted via review-promote without an explicit reason'),\n // Optional calibration evidence captured at promotion time so downstream\n // consumers can see WHY the reviewer was trusted.\n calibration_summary: PromotionCalibrationSummarySchema.nullable().default(null),\n});\n\nexport type PromotionCalibrationSummary = z.infer<typeof PromotionCalibrationSummarySchema>;\nexport type ReviewActive = z.infer<typeof ReviewActiveSchema>;\n\nexport function reviewActivePath(packPath: string, sectionId: string): string {\n return join(packPath, 'sections', sectionId, 'review-active.json');\n}\n\nexport function profileDir(packPath: string, sectionId: string, profile: string): string {\n return join(packPath, 'sections', sectionId, 'reviews', profile);\n}\n\nexport async function readActiveProfile(\n packPath: string,\n sectionId: string,\n): Promise<string> {\n const path = reviewActivePath(packPath, sectionId);\n if (!existsSync(path)) return DEFAULT_PROFILE;\n try {\n const parsed = ReviewActiveSchema.parse(JSON.parse(await readFile(path, 'utf8')));\n return parsed.active_profile;\n } catch {\n return DEFAULT_PROFILE;\n }\n}\n\nexport async function writeActiveProfile(\n packPath: string,\n sectionId: string,\n active: ReviewActive,\n): Promise<void> {\n const path = reviewActivePath(packPath, sectionId);\n await mkdir(join(packPath, 'sections', sectionId), { recursive: true });\n await writeFile(path, JSON.stringify(ReviewActiveSchema.parse(active), null, 2), 'utf8');\n}\n\nexport function isValidProfileName(name: string): boolean {\n return /^[a-z0-9][a-z0-9._-]{0,63}$/.test(name);\n}\n","import type { Claim } from '../../claims/schema.js';\nimport type { Excerpt } from '../../sources/excerpts/schema.js';\nimport type {\n DraftFinding,\n Reviewer,\n ReviewerInput,\n ReviewerResult,\n} from '../types.js';\n\nconst STUB_BRIEF_MARKER = 'This section has not been gathered yet';\nconst MIN_BRIEF_LENGTH_FOR_HIDDEN_SYNTHESIS = 600;\n\n// Same join-separator extract.ts uses when concatenating multi-id excerpts\n// into evidence_excerpt. Stays in sync deliberately.\nconst EVIDENCE_EXCERPT_JOIN = ' … ';\n\nfunction normalize(text: string): string {\n return text.replace(/<[^>]+>/g, ' ').replace(/\\s+/g, ' ').toLowerCase().trim();\n}\n\n// Legacy raw-text substring check, kept for claims that pre-date span-first\n// (evidence_excerpt_ids: []). New claims are validated via the deterministic\n// excerpt ledger in evidenceGroundedViaLedger below.\nfunction evidenceGroundedInRaw(claim: Claim, rawTextBySourceId: Map<string, string>): boolean {\n const excerpt = normalize(claim.evidence_excerpt);\n if (excerpt.length < 8) return false;\n for (const sid of claim.source_ids) {\n const raw = rawTextBySourceId.get(sid);\n if (!raw) continue;\n if (normalize(raw).includes(excerpt)) return true;\n }\n return false;\n}\n\ntype GroundingMode = 'span_first_ok' | 'span_first_fail' | 'legacy';\n\ninterface GroundingResult {\n mode: GroundingMode;\n reason: string;\n}\n\n// Span-first grounding check. The reviewer should NOT re-normalise raw text\n// and substring-search for a copied excerpt — that path produced false\n// positives (claim evidence text differs trivially from raw text after\n// HTML/whitespace normalisation). Instead, validate structurally:\n// 1. Every cited evidence_excerpt_id resolves in the source's ledger.\n// 2. The claim's evidence_excerpt equals the deterministic join of the\n// ledger texts (or a deterministic truncation prefix of that join).\n// Returns 'legacy' if the claim has no evidence_excerpt_ids — those predate\n// span-first and use the raw-text fallback.\nfunction evidenceGroundedViaLedger(\n claim: Claim,\n excerptsBySourceId: Map<string, Map<string, Excerpt>>,\n): GroundingResult {\n if (!claim.evidence_excerpt_ids || claim.evidence_excerpt_ids.length === 0) {\n return { mode: 'legacy', reason: 'pre-span-first claim (no evidence_excerpt_ids)' };\n }\n for (const sid of claim.source_ids) {\n const ledger = excerptsBySourceId.get(sid);\n if (!ledger) continue;\n const allFound = claim.evidence_excerpt_ids.every((id) => ledger.has(id));\n if (!allFound) {\n return {\n mode: 'span_first_fail',\n reason: `One or more evidence_excerpt_ids do not resolve in the ledger for ${sid}`,\n };\n }\n // Deterministic re-derivation of the expected evidence_excerpt.\n const seen = new Set<string>();\n const texts: string[] = [];\n for (const id of claim.evidence_excerpt_ids) {\n if (seen.has(id)) continue;\n seen.add(id);\n texts.push(ledger.get(id)!.text);\n }\n const expected = texts.join(EVIDENCE_EXCERPT_JOIN);\n const actual = claim.evidence_excerpt;\n if (actual === expected) {\n return { mode: 'span_first_ok', reason: 'evidence_excerpt matches the ledger join exactly' };\n }\n // Tolerate the truncation suffix extract.ts adds when the joined text\n // exceeds the per-claim cap.\n if (actual.endsWith(' …') && expected.startsWith(actual.slice(0, -2).trimEnd())) {\n return {\n mode: 'span_first_ok',\n reason: 'evidence_excerpt is a deterministic truncation of the ledger join',\n };\n }\n return {\n mode: 'span_first_fail',\n reason: `evidence_excerpt does not match the deterministic ledger join for ${sid}`,\n };\n }\n return {\n mode: 'span_first_fail',\n reason: 'no ledger available for any cited source',\n };\n}\n\nexport class HeuristicReviewer implements Reviewer {\n readonly name = 'heuristic' as const;\n\n async available(): Promise<boolean> {\n return true;\n }\n\n async review(input: ReviewerInput): Promise<ReviewerResult> {\n const drafts: DraftFinding[] = [];\n const cardIds = new Set(input.sources.map((c) => c.source_id));\n const okReceiptSourceIds = new Set(\n input.receipts.filter((r) => r.fetch_outcome === 'ok').map((r) => r.source_id),\n );\n\n for (const claim of input.candidateClaims) {\n // unsupported_claim — claim cites no source_id that resolves to a card+receipt\n const validCites = claim.source_ids.filter(\n (sid) => cardIds.has(sid) && okReceiptSourceIds.has(sid),\n );\n if (validCites.length === 0) {\n drafts.push({\n category: 'unsupported_claim',\n severity: 'block',\n summary: `Claim ${claim.claim_id} cites no source that resolves to both a source card and a successful fetch receipt.`,\n evidence: `Cited source_ids: ${claim.source_ids.join(', ') || '(none)'}`,\n required_action: 'Re-run gather for the cited sources, or remove the claim.',\n claim_ids: [claim.claim_id],\n source_ids: claim.source_ids,\n confidence: 'high',\n });\n }\n\n // ungrounded_excerpt — span-first grounding check.\n // - Span-first claims (evidence_excerpt_ids non-empty) are validated\n // structurally: every cited ID must resolve in the ledger AND the\n // claim's evidence_excerpt must equal the deterministic ledger join.\n // - Legacy claims (no excerpt IDs) fall back to the raw-text\n // substring check that was the original v0.1 anti-hallucination\n // guard. That path will be removed once all packs migrate.\n if (validCites.length > 0) {\n const grounding = evidenceGroundedViaLedger(claim, input.excerptsBySourceId);\n let ungrounded = false;\n let detail = '';\n if (grounding.mode === 'span_first_fail') {\n ungrounded = true;\n detail = grounding.reason;\n } else if (grounding.mode === 'legacy') {\n if (!evidenceGroundedInRaw(claim, input.rawTextBySourceId)) {\n ungrounded = true;\n detail = 'Legacy claim: evidence_excerpt is not a substring of any cited source raw text';\n }\n }\n if (ungrounded) {\n drafts.push({\n category: 'ungrounded_excerpt',\n severity: 'block',\n summary: `Claim ${claim.claim_id} fails the structural evidence check (${detail}).`,\n evidence: `Excerpt (truncated): ${claim.evidence_excerpt.slice(0, 200)}`,\n required_action: 'Re-extract the claim from the cited source, or remove it.',\n claim_ids: [claim.claim_id],\n source_ids: claim.source_ids,\n confidence: 'high',\n });\n }\n }\n\n // overgeneralized_claim / scope_widening — scope null with substantive asserts\n if (claim.scope === null && claim.asserts.length > 40) {\n drafts.push({\n category: 'overgeneralized_claim',\n severity: 'warn',\n summary: `Claim ${claim.claim_id} has scope=null with a substantive assertion. It cannot be treated as broad without scope-widening evidence.`,\n evidence: `Asserts: ${claim.asserts.slice(0, 200)}`,\n required_action: 'Add an explicit scope tag or restrict the claim to the source\\'s actual scope.',\n claim_ids: [claim.claim_id],\n source_ids: claim.source_ids,\n confidence: 'medium',\n });\n }\n\n // missing_not_constraint\n if (claim.not === null) {\n drafts.push({\n category: 'missing_not_constraint',\n severity: 'info',\n summary: `Claim ${claim.claim_id} has no 'not' constraint recorded.`,\n evidence: `Asserts: ${claim.asserts.slice(0, 160)}`,\n required_action: 'Consider adding a not-constraint to defend against overgeneralization downstream.',\n claim_ids: [claim.claim_id],\n source_ids: claim.source_ids,\n confidence: 'low',\n });\n }\n\n // source_quality_problem — claim with high confidence but weak source type\n const cards = input.sources.filter((c) => claim.source_ids.includes(c.source_id));\n const weakTypes = cards.filter((c) => c.source_type === 'forum' || c.source_type === 'unknown');\n if (claim.confidence === 'high' && weakTypes.length === cards.length && cards.length > 0) {\n drafts.push({\n category: 'source_quality_problem',\n severity: 'warn',\n summary: `Claim ${claim.claim_id} carries confidence=high but every cited source is forum/unknown quality.`,\n evidence: `Source types: ${cards.map((c) => c.source_type).join(', ')}`,\n required_action: 'Lower confidence or add a higher-quality corroborating source.',\n claim_ids: [claim.claim_id],\n source_ids: claim.source_ids,\n confidence: 'medium',\n });\n }\n\n // source_cluster_monopoly — every cited source from one publisher\n const publishers = new Set(\n cards.map((c) => c.publisher).filter((p): p is string => typeof p === 'string'),\n );\n if (cards.length > 0 && publishers.size <= 1 && claim.source_ids.length >= 2) {\n drafts.push({\n category: 'source_cluster_monopoly',\n severity: 'warn',\n summary: `Claim ${claim.claim_id} sources every cite from a single publisher.`,\n evidence: `Publishers: ${[...publishers].join(', ') || '(unknown)'}`,\n required_action: 'Add a citation from an independent publisher or downgrade the claim.',\n claim_ids: [claim.claim_id],\n source_ids: claim.source_ids,\n confidence: 'medium',\n });\n }\n\n // stale_claim — based on freshness policy\n if (input.research.freshness.required && input.research.freshness.max_source_age_months !== null) {\n const maxAge = input.research.freshness.max_source_age_months;\n for (const card of cards) {\n if (!card.published_at) continue;\n const d = Date.parse(card.published_at);\n if (Number.isNaN(d)) continue;\n const ageMonths = (Date.now() - d) / (1000 * 60 * 60 * 24 * 30.44);\n if (ageMonths > maxAge) {\n drafts.push({\n category: 'stale_claim',\n severity: 'warn',\n summary: `Claim ${claim.claim_id} cites a source older than the pack freshness policy (${maxAge} months).`,\n evidence: `Source ${card.source_id} published_at=${card.published_at}.`,\n required_action: 'Replace with a more recent source, or mark the section as not requiring freshness.',\n claim_ids: [claim.claim_id],\n source_ids: [card.source_id],\n confidence: 'medium',\n });\n break;\n }\n }\n }\n\n // unmapped_contradiction — claim is involved in an unresolved contradiction.\n // Check resolution ledger (latest-wins) before falling back to the raw status field.\n const resolvedContradictionIds = new Set<string>();\n if (input.resolutions && input.resolutions.length > 0) {\n const sorted = [...input.resolutions].sort((a, b) => a.resolved_at.localeCompare(b.resolved_at));\n const effectiveMap = new Map<string, string>();\n for (const r of sorted) effectiveMap.set(r.contradiction_id, r.status);\n for (const [cid, status] of effectiveMap) {\n if (status !== 'unresolved') resolvedContradictionIds.add(cid);\n }\n }\n const involved = input.contradictions.filter(\n (c) =>\n c.claim_ids.includes(claim.claim_id) &&\n c.status === 'unresolved' &&\n !resolvedContradictionIds.has(c.contradiction_id),\n );\n const blockingInvolved = involved.filter(\n (c) => c.severity === 'high' || c.severity === 'blocking',\n );\n if (blockingInvolved.length > 0) {\n drafts.push({\n category: 'unmapped_contradiction',\n severity: 'block',\n summary: `Claim ${claim.claim_id} is involved in ${blockingInvolved.length} unresolved high/blocking contradiction(s).`,\n evidence: `Contradiction IDs: ${blockingInvolved.map((c) => c.contradiction_id).join(', ')}`,\n required_action: 'Reconcile, preserve_deliberately, or reject the contradicting claim before synthesis.',\n claim_ids: [claim.claim_id],\n source_ids: claim.source_ids,\n confidence: 'high',\n });\n } else if (involved.length > 0) {\n drafts.push({\n category: 'unmapped_contradiction',\n severity: 'warn',\n summary: `Claim ${claim.claim_id} is involved in ${involved.length} unresolved low/medium-severity contradiction(s).`,\n evidence: `Contradiction IDs: ${involved.map((c) => c.contradiction_id).join(', ')}`,\n required_action: 'Resolve or note the contradiction before relying on the claim.',\n claim_ids: [claim.claim_id],\n source_ids: claim.source_ids,\n confidence: 'medium',\n });\n }\n }\n\n // section-level source_cluster_monopoly — every section source from a single publisher\n if (input.sources.length >= 2 && input.candidateClaims.length > 0) {\n const sectionPublishers = new Set(\n input.sources.map((c) => c.publisher).filter((p): p is string => typeof p === 'string'),\n );\n if (sectionPublishers.size === 1) {\n const [pub] = sectionPublishers;\n drafts.push({\n category: 'source_cluster_monopoly',\n severity: 'warn',\n summary: `Every source for this section traces to a single publisher (${pub}). Claims drawn from this section inherit a publisher-monopoly limitation.`,\n evidence: `Section sources: ${input.sources.length}; distinct publishers: 1 (${pub}).`,\n required_action: 'Add at least one source from an independent publisher before treating these claims as broadly corroborated.',\n claim_ids: input.candidateClaims.map((c) => c.claim_id),\n source_ids: input.sources.map((c) => c.source_id),\n confidence: 'high',\n });\n }\n }\n\n // claim_overproduction — span-first + paged extraction can yield dense\n // claim sets where one source dominates the section, or a cluster of\n // claims share near-identical asserts. We surface BOTH signals so the\n // reviewer can collapse before synthesis treats every grounded span as\n // equally decision-useful. This is structural — interpretive judgement\n // (which claims to keep) belongs to the LLM reviewer or the human.\n if (input.candidateClaims.length > 0) {\n const claimsBySrc = new Map<string, Claim[]>();\n for (const c of input.candidateClaims) {\n for (const sid of c.source_ids) {\n const arr = claimsBySrc.get(sid) ?? [];\n arr.push(c);\n claimsBySrc.set(sid, arr);\n }\n }\n const total = input.candidateClaims.length;\n // Density flag: any source contributing >= 30 claims, OR (when the\n // section has substantive volume — >= 10 total claims and >= 8 from\n // this source) >= 40% of the section's candidate claims.\n // Tiny sections (1-2 claims) never qualify — there's nothing to flag.\n const MIN_TOTAL_FOR_RATIO = 10;\n const MIN_PER_SOURCE_FOR_RATIO = 8;\n for (const [sid, claims] of claimsBySrc.entries()) {\n const ratio = claims.length / Math.max(1, total);\n const ratioFlag =\n total >= MIN_TOTAL_FOR_RATIO &&\n claims.length >= MIN_PER_SOURCE_FOR_RATIO &&\n ratio >= 0.4;\n if (claims.length >= 30 || ratioFlag) {\n const severity = claims.length >= 50 || (ratioFlag && ratio >= 0.6) ? 'block' : 'warn';\n drafts.push({\n category: 'claim_overproduction',\n severity,\n summary: `Source ${sid} contributes ${claims.length} of ${total} candidate claim(s) (${(ratio * 100).toFixed(0)}% of the section). Even if every claim is grounded, the cluster is likely synthesis noise.`,\n evidence: `Top source: ${sid}; claims=${claims.length}; share=${(ratio * 100).toFixed(0)}%.`,\n required_action:\n 'Collapse near-duplicate claims into a smaller set of decision-useful propositions before synthesis.',\n claim_ids: claims.map((c) => c.claim_id),\n source_ids: [sid],\n confidence: 'high',\n });\n }\n }\n // Near-duplicate clustering — group claims by normalised asserts. Any\n // cluster with >= 3 members raises a single finding spanning the cluster.\n const clusters = new Map<string, Claim[]>();\n for (const c of input.candidateClaims) {\n const key = c.asserts.toLowerCase().replace(/[^a-z0-9 ]+/g, ' ').replace(/\\s+/g, ' ').trim();\n const arr = clusters.get(key) ?? [];\n arr.push(c);\n clusters.set(key, arr);\n }\n for (const [, members] of clusters.entries()) {\n if (members.length >= 3) {\n drafts.push({\n category: 'claim_overproduction',\n severity: 'warn',\n summary: `${members.length} claims in this section share a normalised assertion. Likely extractor over-atomization.`,\n evidence: `Sample assert: \"${members[0]!.asserts.slice(0, 140)}\"`,\n required_action:\n 'Keep one representative claim and reject the duplicates, or merge them into a single claim with combined excerpt IDs.',\n claim_ids: members.map((c) => c.claim_id),\n source_ids: Array.from(new Set(members.flatMap((c) => c.source_ids))),\n confidence: 'medium',\n });\n }\n }\n }\n\n // hidden_synthesis — section brief.md has been edited beyond stub state\n if (input.briefText !== null) {\n const isStub = input.briefText.includes(STUB_BRIEF_MARKER);\n if (!isStub && input.briefText.length > MIN_BRIEF_LENGTH_FOR_HIDDEN_SYNTHESIS) {\n drafts.push({\n category: 'hidden_synthesis',\n severity: 'warn',\n summary: `Section brief.md has substantive prose. Verify every assertion in the brief traces to a candidate claim in claims.jsonl.`,\n evidence: `brief.md length: ${input.briefText.length} chars; candidate claims: ${input.candidateClaims.length}.`,\n required_action: 'Audit brief.md sentence-by-sentence against the claim ledger; flag any prose without a backing claim.',\n claim_ids: input.candidateClaims.map((c) => c.claim_id),\n source_ids: [],\n confidence: 'low',\n });\n }\n }\n\n return { ok: true, drafts, method: 'heuristic_field_and_grounding_checks' };\n }\n}\n","import { normalizeOllamaHost } from '../../sources/extractors/ollama-intern.js';\nimport type {\n DraftFinding,\n FindingCategory,\n FindingSeverity,\n Reviewer,\n ReviewerInput,\n ReviewerResult,\n} from '../types.js';\n\nconst DEFAULT_HOST = 'http://localhost:11434';\nconst DEFAULT_MODEL = 'hermes3:8b';\nconst DEFAULT_TIMEOUT_MS = 180_000;\n// Narrow-critic mode runs an aggressive prompt that often triggers extended\n// reasoning (qwen3 thinking, hermes longer chain-of-thought). 10-minute\n// budget per page so the critic can finish on small/mid GPUs.\nconst NARROW_CRITIC_TIMEOUT_MS = 600_000;\n\nconst GENERAL_SYSTEM_PROMPT = `You are an adversarial reviewer for a gated research pack.\n\nYou are given a list of candidate claims with their asserts/scope/not/evidence_excerpt and source IDs. Find INTEGRITY problems. You are NOT here to synthesize; you are here to attack.\n\nLook for:\n- overgeneralized_claim: claim widens beyond what the source supports\n- scope_widening: scope is broader than evidence justifies\n- definition_drift: terms used differently across claims (cite the conflicting claim_ids)\n- recommendation_exceeds_evidence: claim implies an action the source does not support\n- hidden_synthesis: claim asserts a conclusion not present in the cited source\n- temporal_mismatch: claim cites a source from a different time period than its asserts implies\n- claim_overproduction: a cluster of grounded but redundant/atomized claims from one source — collectively synthesis noise. Cite all claim_ids in the cluster on a single finding.\n- valid_but_low_value: this individual claim is grounded but is not synthesis-worthy — restates context, definitional boilerplate, trivia, or low-leverage detail. Cite ONE claim_id per finding.\n\nReturn ONE JSON object: {\"findings\": [...]}.\n\nFor each finding:\n{\n \"category\": one of the LLM-relevant categories above (use exact strings),\n \"severity\": \"info\" | \"warn\" | \"block\",\n \"summary\": ONE sentence,\n \"evidence\": short string referencing the conflicting parts,\n \"required_action\": ONE sentence,\n \"claim_ids\": array of claim_ids that EXIST in the input — do NOT invent IDs,\n \"source_ids\": array of source_ids cited by those claims,\n \"confidence\": \"low\" | \"medium\" | \"high\"\n}\n\nHard rules:\n- Cite ONLY claim_ids and source_ids that appear in the input. Findings with invented IDs are rejected.\n- Do not introduce new facts.\n- Do not synthesize or rewrite claims.\n- Do not assess \"correctness\" of the world; assess integrity of the claim against its source.\n- If you find no problems, return {\"findings\": []}. A clean review is a valid result.`;\n\n// Narrow critic prompt — runs as a SECOND PASS targeting four categories\n// with high precision the general reviewer tends to under-flag (especially\n// unsupported_claim, where calibration showed 0/3 recall on hermes3:8b).\n// This reviewer is deliberately aggressive: err on flagging.\nconst NARROW_CRITIC_SYSTEM_PROMPT = `You are a NARROW CRITIC for a research pack. Your only job is to attack four specific failure modes — be unforgiving.\n\nONLY look for these four categories (ignore everything else):\n- unsupported_claim: the asserts is not directly supported by the evidence_excerpt. If the evidence does not contain the specific concepts/numbers/terms in the asserts, that is unsupported_claim — even if the claim sounds plausible.\n- scope_widening: the asserts uses universal quantifiers (all, every, always, never, must, dominant) but the scope is narrow. Single-source generalisations are scope_widening by default.\n- missing_not_constraint: the asserts is substantive AND has no \\`not\\` boundary, AND the topic plausibly admits universalisation. Flag warn-level.\n- temporal_mismatch: the asserts implies a current/recent state but the scope mentions an old date or stale context.\n\nFor each finding return:\n{\n \"category\": one of the four categories above EXACTLY,\n \"severity\": \"warn\" | \"block\",\n \"summary\": ONE sentence,\n \"evidence\": short quote from asserts/scope/evidence_excerpt that signals the failure,\n \"required_action\": ONE sentence,\n \"claim_ids\": [exactly one claim_id from the input],\n \"source_ids\": [source_ids of that claim],\n \"confidence\": \"low\" | \"medium\" | \"high\"\n}\n\nHard rules:\n- Be unforgiving. If the evidence_excerpt does not directly support the asserts word-for-word, flag it as unsupported_claim.\n- If the asserts has \"all\", \"every\", \"always\", \"never\", \"dominant\", or \"must\" and the scope is narrow, flag scope_widening.\n- DO NOT flag any other category. The general reviewer handles those.\n- Cite ONLY claim_ids that appear in the input. Findings with invented IDs are rejected.\n- Return {\"findings\": []} if and only if every claim is genuinely clean across these four categories.\n\nReturn ONE JSON object: {\"findings\": [...]}.`;\n\nexport type ReviewerMode = 'general' | 'narrow_critic';\n\ninterface ChatResponse {\n message?: { content?: string };\n response?: string;\n}\n\nconst VALID_CATEGORIES: FindingCategory[] = [\n 'overgeneralized_claim',\n 'scope_widening',\n 'definition_drift',\n 'recommendation_exceeds_evidence',\n 'hidden_synthesis',\n 'temporal_mismatch',\n 'claim_overproduction',\n 'valid_but_low_value',\n // The reviewer prompt uses the LLM-relevant subset; heuristic handles the others.\n];\n\nconst VALID_SEVERITIES: FindingSeverity[] = ['info', 'warn', 'block'];\nconst VALID_CONFIDENCES = ['low', 'medium', 'high'] as const;\n\nfunction asEnum<T extends string>(value: unknown, allowed: readonly T[], fallback: T): T {\n return typeof value === 'string' && (allowed as readonly string[]).includes(value)\n ? (value as T)\n : fallback;\n}\n\nfunction asStringArray(v: unknown): string[] {\n return Array.isArray(v)\n ? v.filter((x): x is string => typeof x === 'string').map((s) => s.trim()).filter((s) => s.length > 0)\n : [];\n}\n\nexport interface OllamaReviewerConfig {\n host?: string;\n model?: string;\n timeoutMs?: number;\n // Number of claims per LLM window. Reviewer-side analogue of the\n // extractor's paging: keeps the prompt + response within the model's\n // effective context, and forces per-window claim_id validation so the\n // model can't cite IDs it didn't actually see.\n claimsPerWindow?: number;\n // 'general' (default) uses the broad multi-category prompt. 'narrow_critic'\n // uses the aggressive 4-category prompt designed for the second-pass\n // hardening run that targets unsupported_claim / scope_widening /\n // missing_not_constraint / temporal_mismatch.\n mode?: ReviewerMode;\n fetchImpl?: typeof fetch;\n}\n\nconst DEFAULT_CLAIMS_PER_WINDOW = 30;\n\n// Window an array into N-sized chunks.\nexport function pageClaimsForReview<T>(items: T[], windowSize: number): T[][] {\n if (items.length === 0) return [];\n const out: T[][] = [];\n for (let i = 0; i < items.length; i += windowSize) {\n out.push(items.slice(i, i + windowSize));\n }\n return out;\n}\n\nexport class OllamaInternReviewer implements Reviewer {\n readonly name = 'ollama-intern' as const;\n readonly mode: ReviewerMode;\n private readonly host: string;\n private readonly model: string;\n private readonly timeoutMs: number;\n private readonly claimsPerWindow: number;\n private readonly fetchImpl: typeof fetch;\n\n constructor(config: OllamaReviewerConfig = {}) {\n this.host = normalizeOllamaHost(config.host ?? process.env.OLLAMA_HOST ?? DEFAULT_HOST);\n this.model = config.model ?? process.env.OLLAMA_INTERN_MODEL ?? DEFAULT_MODEL;\n this.mode = config.mode ?? 'general';\n this.timeoutMs =\n config.timeoutMs ??\n (this.mode === 'narrow_critic' ? NARROW_CRITIC_TIMEOUT_MS : DEFAULT_TIMEOUT_MS);\n const envWindow = process.env.OLLAMA_INTERN_REVIEW_WINDOW;\n this.claimsPerWindow =\n config.claimsPerWindow ??\n (envWindow ? parseInt(envWindow, 10) || DEFAULT_CLAIMS_PER_WINDOW : DEFAULT_CLAIMS_PER_WINDOW);\n this.fetchImpl = config.fetchImpl ?? globalThis.fetch;\n }\n\n async available(): Promise<boolean> {\n try {\n const ctrl = new AbortController();\n const t = setTimeout(() => ctrl.abort(), 1500);\n const res = await this.fetchImpl(`${this.host}/api/tags`, { signal: ctrl.signal });\n clearTimeout(t);\n if (!res.ok) return false;\n const body = (await res.json()) as { models?: Array<{ name: string }> };\n const names = (body.models ?? []).map((m) => m.name);\n const family = this.model.split(':')[0] ?? this.model;\n return names.some((n) => n === this.model || n === family || n.startsWith(`${family}:`));\n } catch {\n return false;\n }\n }\n\n // Single-window LLM call. Per-window IDs are validated by the caller so a\n // window-1 finding can't cite a window-2 claim.\n private async reviewOnePage(\n windowClaims: ReviewerInput['candidateClaims'],\n sectionId: string,\n sectionPurpose: string,\n ): Promise<{ ok: true; drafts: DraftFinding[] } | { ok: false; error: string }> {\n const claimsBlock = windowClaims\n .map((c) =>\n [\n `Claim ${c.claim_id}:`,\n ` asserts: ${c.asserts}`,\n ` scope: ${c.scope ?? 'null'}`,\n ` not: ${c.not ?? 'null'}`,\n ` evidence_excerpt: ${c.evidence_excerpt}`,\n ` confidence: ${c.confidence}`,\n ` source_ids: ${c.source_ids.join(', ')}`,\n ].join('\\n'),\n )\n .join('\\n\\n');\n\n const userMsg = `Section: ${sectionId}\\nPurpose: ${sectionPurpose}\\n\\nCANDIDATE CLAIMS:\\n\\n${claimsBlock}`;\n\n const ctrl = new AbortController();\n const t = setTimeout(() => ctrl.abort(), this.timeoutMs);\n let body: ChatResponse;\n try {\n const res = await this.fetchImpl(`${this.host}/api/chat`, {\n method: 'POST',\n signal: ctrl.signal,\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n model: this.model,\n stream: false,\n format: 'json',\n // Ollama defaults num_ctx to 4096 regardless of the model's\n // native window; review prompts with 20+ claims exceed that and\n // get silently truncated, which drops claim_ids and confuses the\n // model. Explicitly request 8K so paged windows fit cleanly.\n options: { num_ctx: 8192 },\n messages: [\n {\n role: 'system',\n content:\n this.mode === 'narrow_critic'\n ? NARROW_CRITIC_SYSTEM_PROMPT\n : GENERAL_SYSTEM_PROMPT,\n },\n { role: 'user', content: userMsg },\n ],\n }),\n });\n if (!res.ok) return { ok: false, error: `Ollama HTTP ${res.status}` };\n body = (await res.json()) as ChatResponse;\n } catch (err) {\n return { ok: false, error: err instanceof Error ? err.message : 'Ollama request failed' };\n } finally {\n clearTimeout(t);\n }\n\n const text = body.message?.content ?? body.response ?? '';\n let parsed: { findings?: unknown };\n try {\n parsed = JSON.parse(text) as { findings?: unknown };\n } catch {\n return { ok: false, error: 'Ollama response was not valid JSON' };\n }\n if (!Array.isArray(parsed.findings)) {\n return { ok: false, error: 'Ollama response did not contain a findings array' };\n }\n\n const drafts: DraftFinding[] = [];\n for (const raw of parsed.findings) {\n if (!raw || typeof raw !== 'object') continue;\n const r = raw as Record<string, unknown>;\n const category = asEnum<FindingCategory>(r.category, VALID_CATEGORIES, 'overgeneralized_claim');\n if (!VALID_CATEGORIES.includes(r.category as FindingCategory)) continue;\n const summary = typeof r.summary === 'string' && r.summary.trim().length > 0 ? r.summary.trim() : null;\n if (!summary) continue;\n drafts.push({\n category,\n severity: asEnum<FindingSeverity>(r.severity, VALID_SEVERITIES, 'warn'),\n summary,\n evidence: typeof r.evidence === 'string' ? r.evidence.trim() : '',\n required_action: typeof r.required_action === 'string' ? r.required_action.trim() : '',\n claim_ids: asStringArray(r.claim_ids),\n source_ids: asStringArray(r.source_ids),\n confidence: asEnum(r.confidence, VALID_CONFIDENCES, 'low'),\n });\n }\n return { ok: true, drafts };\n }\n\n async review(input: ReviewerInput): Promise<ReviewerResult> {\n if (input.candidateClaims.length === 0) {\n return { ok: true, drafts: [], method: 'ollama_intern_adversarial_review' };\n }\n\n const windows = pageClaimsForReview(input.candidateClaims, this.claimsPerWindow);\n const allDrafts: DraftFinding[] = [];\n const pageErrors: string[] = [];\n let pagesOk = 0;\n let rejectedCrossWindow = 0;\n\n for (const windowClaims of windows) {\n const validIds = new Set(windowClaims.map((c) => c.claim_id));\n const page = await this.reviewOnePage(\n windowClaims,\n input.section.id,\n input.section.purpose,\n );\n if (!page.ok) {\n pageErrors.push(page.error);\n continue;\n }\n pagesOk += 1;\n // Per-window claim_id validation: the model only saw `windowClaims`,\n // so any cited ID outside that set is a cross-window hallucination.\n // We trim invalid IDs and drop the finding entirely if no valid IDs\n // remain.\n for (const draft of page.drafts) {\n const kept = draft.claim_ids.filter((id) => validIds.has(id));\n if (kept.length === 0) {\n rejectedCrossWindow += 1;\n continue;\n }\n if (kept.length !== draft.claim_ids.length) rejectedCrossWindow += 1;\n allDrafts.push({ ...draft, claim_ids: kept });\n }\n }\n\n if (pagesOk === 0) {\n return {\n ok: false,\n error:\n pageErrors.length === 1\n ? pageErrors[0]!\n : `all ${windows.length} review pages failed (first: ${pageErrors[0] ?? 'unknown'})`,\n };\n }\n\n // Dedup findings across windows by (category, sorted claim_ids, summary\n // prefix). Adjacent windows can produce parallel findings about the same\n // claim cluster.\n const seen = new Set<string>();\n const drafts: DraftFinding[] = [];\n for (const d of allDrafts) {\n const key = `${d.category}|${[...d.claim_ids].sort().join(',')}|${d.summary.toLowerCase().slice(0, 80)}`;\n if (seen.has(key)) continue;\n seen.add(key);\n drafts.push(d);\n }\n\n const modeTag = this.mode === 'narrow_critic' ? '_narrow_critic' : '';\n const method =\n windows.length > 1\n ? `ollama_intern_adversarial_review_paged${modeTag}`\n : `ollama_intern_adversarial_review${modeTag}`;\n return { ok: true, drafts, method, rejected_ungrounded: rejectedCrossWindow };\n }\n}\n","import type { Reviewer } from '../types.js';\nimport { HeuristicReviewer } from './heuristic.js';\nimport { OllamaInternReviewer } from './ollama-intern.js';\n\nexport { HeuristicReviewer } from './heuristic.js';\nexport { OllamaInternReviewer } from './ollama-intern.js';\n\nexport function defaultReviewers(): Reviewer[] {\n return [new OllamaInternReviewer(), new HeuristicReviewer()];\n}\n\nexport async function pickReviewer(reviewers: Reviewer[]): Promise<Reviewer> {\n for (const r of reviewers) {\n if (await r.available()) return r;\n }\n throw new Error(\n 'No reviewer available. The HeuristicReviewer should always be available — this indicates a bug.',\n );\n}\n","import type { Claim } from '../claims/schema.js';\nimport type { ClaimReview, ReviewFinding } from './schema.js';\nimport type { ReviewDecision, ReviewerName } from './types.js';\n\nconst BLOCK_TO_DECISION: Record<string, ReviewDecision> = {\n ungrounded_excerpt: 'rejected',\n unsupported_claim: 'rejected',\n unmapped_contradiction: 'needs_contradiction_mapping',\n recommendation_exceeds_evidence: 'rejected',\n hidden_synthesis: 'needs_human_review',\n temporal_mismatch: 'needs_source_repair',\n definition_drift: 'needs_source_repair',\n scope_widening: 'needs_scope_repair',\n overgeneralized_claim: 'needs_scope_repair',\n source_quality_problem: 'needs_source_repair',\n source_cluster_monopoly: 'needs_source_repair',\n stale_claim: 'needs_source_repair',\n // Block-level overproduction means the cluster is redundant enough that the\n // reviewer demands human-led collapse before synthesis.\n claim_overproduction: 'needs_human_review',\n // Block-level low-value: explicitly excluded from synthesis. The claim is\n // grounded, but the reviewer is firm that it doesn't earn a slot.\n valid_but_low_value: 'rejected',\n};\n\nconst WARN_TO_DECISION: Record<string, ReviewDecision> = {\n overgeneralized_claim: 'needs_scope_repair',\n scope_widening: 'needs_scope_repair',\n source_quality_problem: 'needs_source_repair',\n source_cluster_monopoly: 'needs_source_repair',\n stale_claim: 'needs_source_repair',\n unmapped_contradiction: 'needs_contradiction_mapping',\n hidden_synthesis: 'needs_human_review',\n recommendation_exceeds_evidence: 'needs_human_review',\n // Warn-level overproduction routes to human review too — the claim itself\n // may be fine; the reviewer is signalling the cluster is synthesis noise.\n claim_overproduction: 'needs_human_review',\n // Warn-level low-value: borderline. Send to human review rather than auto\n // rejecting; the human decides whether to keep on the ledger or exclude.\n valid_but_low_value: 'needs_human_review',\n};\n\nconst DECISION_PRIORITY: ReviewDecision[] = [\n 'rejected',\n 'needs_contradiction_mapping',\n 'needs_source_repair',\n 'needs_scope_repair',\n 'needs_human_review',\n 'accepted_for_synthesis',\n];\n\nfunction pickHighestPriority(decisions: ReviewDecision[]): ReviewDecision {\n for (const d of DECISION_PRIORITY) {\n if (decisions.includes(d)) return d;\n }\n return 'accepted_for_synthesis';\n}\n\nexport function deriveClaimReviews(args: {\n claims: Claim[];\n findings: ReviewFinding[];\n reviewer: ReviewerName;\n reviewMethod: string;\n}): ClaimReview[] {\n const { claims, findings, reviewer, reviewMethod } = args;\n const reviews: ClaimReview[] = [];\n const now = new Date().toISOString();\n\n for (const claim of claims) {\n const claimFindings = findings.filter((f) => f.claim_ids.includes(claim.claim_id));\n if (claimFindings.length === 0) {\n reviews.push({\n claim_id: claim.claim_id,\n decision: 'accepted_for_synthesis',\n reason: 'No findings recorded for this claim by the current reviewer.',\n finding_ids: [],\n reviewer,\n review_method: reviewMethod,\n created_at: now,\n });\n continue;\n }\n\n let decisions: ReviewDecision[] = [];\n for (const f of claimFindings) {\n if (f.severity === 'block') {\n decisions.push(BLOCK_TO_DECISION[f.category] ?? 'rejected');\n } else if (f.severity === 'warn') {\n const d = WARN_TO_DECISION[f.category];\n if (d) decisions.push(d);\n }\n }\n if (decisions.length === 0) decisions.push('accepted_for_synthesis');\n\n // Conservative merge: a claim flagged ONLY by the narrow critic (and\n // no general / heuristic reviewer corroborated it) gets soft pressure,\n // not auto-rejection. The narrow critic's role is to surface risk; the\n // final reject must be backed by the general pass or a heuristic\n // structural check. This prevents a false-positive-prone critic from\n // killing claims unilaterally.\n const isCritic = (f: ReviewFinding): boolean =>\n typeof f.review_method === 'string' && f.review_method.endsWith('_narrow_critic');\n const onlyCritic =\n claimFindings.length > 0 && claimFindings.every(isCritic);\n if (onlyCritic) {\n decisions = decisions.map((d) =>\n d === 'rejected' ? 'needs_human_review' : d,\n );\n }\n\n const decision = pickHighestPriority(decisions);\n const reasonParts = claimFindings\n .filter((f) => f.severity !== 'info')\n .map((f) => `${f.category} (${f.severity})`);\n const reason =\n reasonParts.length > 0\n ? `Findings: ${reasonParts.join('; ')}.`\n : 'Only info-level findings; accepted.';\n\n reviews.push({\n claim_id: claim.claim_id,\n decision,\n reason,\n finding_ids: claimFindings.map((f) => f.finding_id),\n reviewer,\n review_method: reviewMethod,\n created_at: now,\n });\n }\n\n return reviews;\n}\n","import type { ReviewSnapshot } from './schema.js';\n\nconst SEVERITY_GLYPH: Record<string, string> = {\n info: '[INFO]',\n warn: '[WARN]',\n block: '[BLOCK]',\n};\n\nconst DECISION_GLYPH: Record<string, string> = {\n accepted_for_synthesis: '[ACCEPTED]',\n rejected: '[REJECTED]',\n needs_scope_repair: '[NEEDS-SCOPE-REPAIR]',\n needs_source_repair: '[NEEDS-SOURCE-REPAIR]',\n needs_contradiction_mapping: '[NEEDS-CONTRADICTION-MAPPING]',\n needs_human_review: '[NEEDS-HUMAN-REVIEW]',\n};\n\nexport function renderReviewMarkdown(snapshot: ReviewSnapshot): string {\n const lines: string[] = [];\n lines.push(`# Adversarial Review: ${snapshot.section_id}`);\n lines.push('');\n lines.push(`**Reviewer:** ${snapshot.reviewer} (${snapshot.review_method})`);\n lines.push(`**Reviewed at:** ${snapshot.reviewed_at}`);\n lines.push(`**Candidate claims:** ${snapshot.candidate_claims}`);\n lines.push(`**Findings:** ${snapshot.findings.length} (block: ${snapshot.severity_counts.block ?? 0}, warn: ${snapshot.severity_counts.warn ?? 0}, info: ${snapshot.severity_counts.info ?? 0})`);\n lines.push(`**LLM findings rejected (ungrounded):** ${snapshot.llm_findings_rejected_ungrounded}`);\n lines.push('');\n\n lines.push('> Adversarial review judges research integrity. It does not synthesize, rewrite source truth, or erase extraction history. Decisions below are review truth — claims.jsonl is unchanged.');\n lines.push('');\n\n lines.push('## Effective decisions');\n lines.push('');\n const decisions = snapshot.decision_counts;\n for (const d of [\n 'rejected',\n 'needs_contradiction_mapping',\n 'needs_source_repair',\n 'needs_scope_repair',\n 'needs_human_review',\n 'accepted_for_synthesis',\n ]) {\n const n = decisions[d as keyof typeof decisions] ?? 0;\n if (n > 0) lines.push(`- ${DECISION_GLYPH[d] ?? d}: ${n}`);\n }\n if (snapshot.findings.length === 0) {\n lines.push('');\n lines.push('No findings produced. A clean review is not proof of completeness — it means the configured reviewer found nothing of integrity concern.');\n }\n lines.push('');\n\n if (snapshot.findings.length > 0) {\n lines.push('## Findings');\n lines.push('');\n for (const f of snapshot.findings) {\n const glyph = SEVERITY_GLYPH[f.severity] ?? `[${f.severity.toUpperCase()}]`;\n lines.push(`### ${glyph} ${f.category} (${f.finding_id})`);\n lines.push('');\n lines.push(f.summary);\n lines.push('');\n lines.push(`- **Claim IDs:** ${f.claim_ids.map((c) => `\\`${c}\\``).join(', ') || '(none)'}`);\n lines.push(`- **Source IDs:** ${f.source_ids.map((s) => `\\`${s}\\``).join(', ') || '(none)'}`);\n lines.push(`- **Required action:** ${f.required_action || '(unspecified)'}`);\n lines.push(`- **Reviewer:** ${f.reviewer} (${f.review_method})`);\n lines.push(`- **Confidence:** ${f.confidence}`);\n if (f.evidence) lines.push(`- **Evidence:** ${f.evidence}`);\n lines.push('');\n }\n }\n\n if (snapshot.claim_reviews.length > 0) {\n lines.push('## Claim review decisions');\n lines.push('');\n for (const r of snapshot.claim_reviews) {\n const glyph = DECISION_GLYPH[r.decision] ?? `[${r.decision.toUpperCase()}]`;\n lines.push(`### ${glyph} \\`${r.claim_id}\\``);\n lines.push('');\n lines.push(`${r.reason}`);\n if (r.finding_ids.length > 0) {\n lines.push('');\n lines.push(`Cites findings: ${r.finding_ids.map((id) => `\\`${id}\\``).join(', ')}.`);\n }\n lines.push('');\n }\n }\n\n return lines.join('\\n');\n}\n","import { createHash } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { appendFile, mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { join, resolve } from 'node:path';\nimport { parse as yamlParse, stringify as yamlStringify } from 'yaml';\n\nimport { PackNotFoundError, SectionNotFoundError } from '../errors.js';\nimport { ResearchYamlSchema, type ResearchYaml, type Section } from '../intake/schema.js';\nimport { ClaimSchema, type Claim } from '../claims/schema.js';\nimport { ContradictionSchema, type Contradiction } from '../contradictions/schema.js';\nimport { ContradictionResolutionSchema, type ContradictionResolution } from '../contradictions/resolution-schema.js';\nimport {\n FetchReceiptSchema,\n SourceCardSchema,\n type FetchReceipt,\n type SourceCard,\n} from '../sources/schema.js';\nimport { ExcerptSchema, type Excerpt } from '../sources/excerpts/schema.js';\nimport { ledgerPathFor } from '../sources/excerpts/ledger.js';\nimport { SectionGateResultSchema, type SectionGateResult } from '../gates/schema.js';\n\nimport {\n DEFAULT_PROFILE,\n profileDir,\n readActiveProfile,\n} from './profiles.js';\n\nimport {\n defaultReviewers,\n pickReviewer,\n} from './reviewers/index.js';\nimport { deriveClaimReviews } from './decision.js';\nimport { renderReviewMarkdown } from './markdown.js';\nimport {\n ClaimReviewSchema,\n ReviewFindingSchema,\n ReviewSnapshotSchema,\n type ClaimReview,\n type ReviewFinding,\n type ReviewSnapshot,\n} from './schema.js';\nimport type {\n DraftFinding,\n FindingSeverity,\n ReviewDecision,\n ReviewerName,\n RunReviewOptions,\n RunReviewSummary,\n} from './types.js';\n\nasync function readJsonl<T>(\n packPath: string,\n rel: string,\n parse: (raw: unknown) => T,\n): Promise<T[]> {\n const path = join(packPath, rel);\n if (!existsSync(path)) return [];\n const text = await readFile(path, 'utf8');\n const out: T[] = [];\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n out.push(parse(JSON.parse(line)));\n }\n return out;\n}\n\nasync function readSourceCards(packPath: string): Promise<SourceCard[]> {\n const dir = join(packPath, 'evidence', 'source-cards');\n if (!existsSync(dir)) return [];\n const { readdir } = await import('node:fs/promises');\n const entries = await readdir(dir);\n const cards: SourceCard[] = [];\n for (const entry of entries) {\n if (!entry.endsWith('.json')) continue;\n const text = await readFile(join(dir, entry), 'utf8');\n cards.push(SourceCardSchema.parse(JSON.parse(text)));\n }\n return cards;\n}\n\nasync function readGateResult(\n packPath: string,\n sectionId: string,\n): Promise<SectionGateResult | null> {\n const path = join(packPath, 'audits', `${sectionId}-gate.json`);\n if (!existsSync(path)) return null;\n const text = await readFile(path, 'utf8');\n return SectionGateResultSchema.parse(JSON.parse(text));\n}\n\nasync function readBriefText(\n packPath: string,\n sectionId: string,\n): Promise<string | null> {\n const path = join(packPath, 'sections', sectionId, 'brief.md');\n if (!existsSync(path)) return null;\n return readFile(path, 'utf8');\n}\n\nasync function readRawTextBySource(\n packPath: string,\n receipts: FetchReceipt[],\n): Promise<Map<string, string>> {\n const map = new Map<string, string>();\n for (const r of receipts) {\n if (r.fetch_outcome !== 'ok' || !r.raw_text_path) continue;\n const path = join(packPath, r.raw_text_path);\n if (!existsSync(path)) continue;\n if (map.has(r.source_id)) continue;\n map.set(r.source_id, await readFile(path, 'utf8'));\n }\n return map;\n}\n\n// Load span-first excerpt ledgers for every source cited by the section's\n// claims. Reviewers use this for structural grounding checks instead of\n// re-normalising raw text.\nasync function readExcerptsBySource(\n packPath: string,\n claims: Claim[],\n): Promise<Map<string, Map<string, Excerpt>>> {\n const out = new Map<string, Map<string, Excerpt>>();\n const sourceIds = new Set<string>();\n for (const c of claims) for (const sid of c.source_ids) sourceIds.add(sid);\n for (const sid of sourceIds) {\n const path = ledgerPathFor(packPath, sid);\n if (!existsSync(path)) continue;\n const text = await readFile(path, 'utf8');\n const index = new Map<string, Excerpt>();\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n const e = ExcerptSchema.parse(JSON.parse(line));\n index.set(e.excerpt_id, e);\n } catch {\n /* skip malformed line */\n }\n }\n if (index.size > 0) out.set(sid, index);\n }\n return out;\n}\n\nfunction makeFindingId(args: {\n sectionId: string;\n category: string;\n claimIds: string[];\n reviewer: ReviewerName;\n}): string {\n const sortedClaimIds = [...args.claimIds].sort().join(',');\n const hash = createHash('sha256')\n .update(`${args.sectionId}|${args.category}|${sortedClaimIds}|${args.reviewer}`)\n .digest('hex')\n .slice(0, 12);\n return `fnd_${hash}`;\n}\n\nfunction isValidReference(\n draft: DraftFinding,\n knownClaimIds: Set<string>,\n knownSourceIds: Set<string>,\n): boolean {\n if (draft.claim_ids.length === 0) return false;\n for (const cid of draft.claim_ids) {\n if (!knownClaimIds.has(cid)) return false;\n }\n for (const sid of draft.source_ids) {\n if (!knownSourceIds.has(sid)) return false;\n }\n return true;\n}\n\nfunction buildFinding(args: {\n draft: DraftFinding;\n sectionId: string;\n reviewer: ReviewerName;\n reviewMethod: string;\n}): ReviewFinding {\n const { draft, sectionId, reviewer, reviewMethod } = args;\n return ReviewFindingSchema.parse({\n finding_id: makeFindingId({\n sectionId,\n category: draft.category,\n claimIds: draft.claim_ids,\n reviewer,\n }),\n section_id: sectionId,\n claim_ids: draft.claim_ids,\n source_ids: draft.source_ids,\n category: draft.category,\n severity: draft.severity,\n summary: draft.summary,\n evidence: draft.evidence,\n required_action: draft.required_action,\n reviewer,\n review_method: reviewMethod,\n confidence: draft.confidence,\n created_at: new Date().toISOString(),\n });\n}\n\nasync function loadResearchYaml(packPath: string): Promise<ResearchYaml> {\n const yamlPath = join(packPath, 'research.yaml');\n if (!existsSync(yamlPath)) throw new PackNotFoundError(packPath);\n const text = await readFile(yamlPath, 'utf8');\n return ResearchYamlSchema.parse(yamlParse(text));\n}\n\nasync function maybePromoteToReviewed(\n packPath: string,\n sectionId: string,\n allAccepted: boolean,\n): Promise<boolean> {\n if (!allAccepted) return false;\n const yamlPath = join(packPath, 'research.yaml');\n const text = await readFile(yamlPath, 'utf8');\n const research = ResearchYamlSchema.parse(yamlParse(text));\n const idx = research.sections.findIndex((s) => s.id === sectionId);\n if (idx < 0) return false;\n const current = research.sections[idx]!;\n if (current.status !== 'gated') return false;\n research.sections[idx] = { ...current, status: 'reviewed' };\n await writeFile(yamlPath, yamlStringify(research, { lineWidth: 0 }), 'utf8');\n return true;\n}\n\nexport async function review(options: RunReviewOptions): Promise<RunReviewSummary> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n if (!existsSync(join(packPath, 'research.yaml'))) throw new PackNotFoundError(packPath);\n const sectionDir = join(packPath, 'sections', options.sectionId);\n if (!existsSync(sectionDir)) throw new SectionNotFoundError(options.sectionId);\n\n const research = await loadResearchYaml(packPath);\n const section: Section | undefined = research.sections.find((s) => s.id === options.sectionId);\n if (!section) throw new SectionNotFoundError(options.sectionId);\n\n const claims = await readJsonl<Claim>(packPath, `sections/${options.sectionId}/claims.jsonl`, (r) => ClaimSchema.parse(r));\n let candidateClaims = claims.filter((c) => c.review_state === 'candidate');\n if (options.triagedOnly) {\n const { readTriagedClaimIds } = await import('../triage/run.js');\n const allowed = await readTriagedClaimIds(packPath, options.sectionId);\n candidateClaims = candidateClaims.filter((c) => allowed.has(c.claim_id));\n }\n const sources = await readSourceCards(packPath);\n const receipts = await readJsonl<FetchReceipt>(packPath, 'evidence/fetch-log.jsonl', (r) => FetchReceiptSchema.parse(r));\n const contradictions = await readJsonl<Contradiction>(packPath, `sections/${options.sectionId}/contradictions.jsonl`, (r) => ContradictionSchema.parse(r));\n const resolutions = await readJsonl<ContradictionResolution>(packPath, `sections/${options.sectionId}/contradiction-resolutions.jsonl`, (r) => ContradictionResolutionSchema.parse(r));\n const gateResult = await readGateResult(packPath, options.sectionId);\n const rawTextBySourceId = await readRawTextBySource(packPath, receipts);\n const excerptsBySourceId = await readExcerptsBySource(packPath, claims);\n const briefText = await readBriefText(packPath, options.sectionId);\n\n const reviewers = options.reviewers ?? defaultReviewers();\n\n // Multi-pass: run every available reviewer and merge findings. The classic\n // shape is general LLM + narrow-critic LLM + heuristic — each catches a\n // different failure mode, and the merger is append-only with dedup.\n if (options.multiPass) {\n return runMultiPassReview({\n packPath,\n options,\n reviewers,\n research,\n section,\n claims,\n candidateClaims,\n sources,\n receipts,\n contradictions,\n resolutions,\n gateResult,\n rawTextBySourceId,\n excerptsBySourceId,\n briefText,\n });\n }\n\n const reviewer = await pickReviewer(reviewers);\n\n const result = await reviewer.review({\n research,\n section,\n candidateClaims,\n sources,\n receipts,\n contradictions,\n resolutions,\n excerptsBySourceId,\n gateResult,\n rawTextBySourceId,\n briefText,\n });\n\n if (!result.ok) {\n // Reviewer-level failure (e.g. Ollama HTTP error). Fall back to heuristic if available.\n const heuristic = reviewers.find((r) => r.name === 'heuristic');\n if (!heuristic || heuristic === reviewer) {\n throw new Error(`Reviewer \"${reviewer.name}\" failed and no fallback available: ${result.error}`);\n }\n return reviewWithSpecificReviewer({\n packPath,\n options,\n reviewer: heuristic,\n research,\n section,\n claims,\n candidateClaims,\n sources,\n receipts,\n contradictions,\n resolutions,\n gateResult,\n rawTextBySourceId,\n excerptsBySourceId,\n briefText,\n });\n }\n\n const knownClaimIds = new Set(claims.map((c) => c.claim_id));\n const knownSourceIds = new Set(sources.map((s) => s.source_id));\n let llmFindingsRejected = 0;\n const acceptedDrafts: DraftFinding[] = [];\n for (const d of result.drafts) {\n if (reviewer.name === 'ollama-intern' && !isValidReference(d, knownClaimIds, knownSourceIds)) {\n llmFindingsRejected += 1;\n continue;\n }\n acceptedDrafts.push(d);\n }\n\n return finalizeReview({\n packPath,\n sectionId: options.sectionId,\n reviewer: reviewer.name,\n reviewMethod: result.method,\n candidateClaims,\n drafts: acceptedDrafts,\n llmFindingsRejected,\n profile: options.profile ?? DEFAULT_PROFILE,\n });\n}\n\ninterface ReviewWithSpecificReviewerArgs {\n packPath: string;\n options: RunReviewOptions;\n reviewer: ReturnType<typeof pickReviewer> extends Promise<infer T> ? T : never;\n research: ResearchYaml;\n section: Section;\n claims: Claim[];\n candidateClaims: Claim[];\n sources: SourceCard[];\n receipts: FetchReceipt[];\n contradictions: Contradiction[];\n resolutions?: ContradictionResolution[];\n gateResult: SectionGateResult | null;\n rawTextBySourceId: Map<string, string>;\n excerptsBySourceId: Map<string, Map<string, Excerpt>>;\n briefText: string | null;\n}\n\ninterface MultiPassArgs extends Omit<ReviewWithSpecificReviewerArgs, 'reviewer'> {\n reviewers: ReadonlyArray<\n ReturnType<typeof pickReviewer> extends Promise<infer T> ? T : never\n >;\n}\n\n// Run every available reviewer in sequence, merging findings into one\n// append-only ledger. Dedup by (claim_ids sorted, category, summary prefix).\n// The merged \"method\" tag concatenates each reviewer's reported method so\n// downstream consumers can see exactly which passes contributed.\nasync function runMultiPassReview(args: MultiPassArgs): Promise<RunReviewSummary> {\n const knownClaimIds = new Set(args.claims.map((c) => c.claim_id));\n const knownSourceIds = new Set(args.sources.map((s) => s.source_id));\n\n const allDrafts: DraftFinding[] = [];\n const methods: string[] = [];\n const failedReviewers: string[] = [];\n let llmFindingsRejected = 0;\n let pickedReviewerName: ReviewerName = 'heuristic';\n\n for (const reviewer of args.reviewers) {\n if (!(await reviewer.available())) continue;\n const result = await reviewer.review({\n research: args.research,\n section: args.section,\n candidateClaims: args.candidateClaims,\n sources: args.sources,\n receipts: args.receipts,\n contradictions: args.contradictions,\n resolutions: args.resolutions,\n excerptsBySourceId: args.excerptsBySourceId,\n gateResult: args.gateResult,\n rawTextBySourceId: args.rawTextBySourceId,\n briefText: args.briefText,\n });\n if (!result.ok) {\n failedReviewers.push(`${reviewer.name}:${result.error}`);\n continue;\n }\n methods.push(result.method);\n if (result.rejected_ungrounded) llmFindingsRejected += result.rejected_ungrounded;\n // The reviewer \"name\" recorded on the section is the one that contributed\n // the most findings — used for the snapshot's reviewer field. Default to\n // heuristic; let any LLM pass override.\n if (reviewer.name === 'ollama-intern') pickedReviewerName = 'ollama-intern';\n for (const d of result.drafts) {\n if (\n reviewer.name === 'ollama-intern' &&\n !isValidReference(d, knownClaimIds, knownSourceIds)\n ) {\n llmFindingsRejected += 1;\n continue;\n }\n allDrafts.push(d);\n }\n }\n\n if (allDrafts.length === 0 && failedReviewers.length === args.reviewers.length) {\n throw new Error(\n `Multi-pass review: every reviewer failed. ${failedReviewers.join(' | ')}`,\n );\n }\n\n // Dedup findings by (sorted claim_ids, category, summary prefix). Two\n // reviewers can flag the same problem; the section ledger should record it\n // once, not twice.\n const seen = new Set<string>();\n const merged: DraftFinding[] = [];\n for (const d of allDrafts) {\n const key = `${d.category}|${[...d.claim_ids].sort().join(',')}|${d.summary.toLowerCase().slice(0, 80)}`;\n if (seen.has(key)) continue;\n seen.add(key);\n merged.push(d);\n }\n\n return finalizeReview({\n packPath: args.packPath,\n sectionId: args.options.sectionId,\n reviewer: pickedReviewerName,\n reviewMethod: methods.length > 0 ? `multi_pass(${methods.join(' + ')})` : 'multi_pass(empty)',\n candidateClaims: args.candidateClaims,\n drafts: merged,\n llmFindingsRejected,\n profile: args.options.profile ?? DEFAULT_PROFILE,\n });\n}\n\nasync function reviewWithSpecificReviewer(args: ReviewWithSpecificReviewerArgs): Promise<RunReviewSummary> {\n const result = await args.reviewer.review({\n research: args.research,\n section: args.section,\n candidateClaims: args.candidateClaims,\n sources: args.sources,\n receipts: args.receipts,\n contradictions: args.contradictions,\n resolutions: args.resolutions,\n gateResult: args.gateResult,\n rawTextBySourceId: args.rawTextBySourceId,\n excerptsBySourceId: args.excerptsBySourceId,\n briefText: args.briefText,\n });\n if (!result.ok) {\n throw new Error(`Fallback reviewer \"${args.reviewer.name}\" also failed: ${result.error}`);\n }\n return finalizeReview({\n packPath: args.packPath,\n sectionId: args.options.sectionId,\n reviewer: args.reviewer.name,\n reviewMethod: result.method,\n candidateClaims: args.candidateClaims,\n drafts: result.drafts,\n llmFindingsRejected: 0,\n profile: args.options.profile ?? DEFAULT_PROFILE,\n });\n}\n\ninterface FinalizeArgs {\n packPath: string;\n sectionId: string;\n reviewer: ReviewerName;\n reviewMethod: string;\n candidateClaims: Claim[];\n drafts: DraftFinding[];\n llmFindingsRejected: number;\n profile: string;\n}\n\nasync function finalizeReview(args: FinalizeArgs): Promise<RunReviewSummary> {\n const findings: ReviewFinding[] = args.drafts.map((d) =>\n buildFinding({\n draft: d,\n sectionId: args.sectionId,\n reviewer: args.reviewer,\n reviewMethod: args.reviewMethod,\n }),\n );\n // Dedup by finding_id within this run\n const seen = new Set<string>();\n const dedupedFindings: ReviewFinding[] = [];\n let dedupedCount = 0;\n for (const f of findings) {\n if (seen.has(f.finding_id)) {\n dedupedCount += 1;\n continue;\n }\n seen.add(f.finding_id);\n dedupedFindings.push(f);\n }\n\n const claimReviews: ClaimReview[] = deriveClaimReviews({\n claims: args.candidateClaims,\n findings: dedupedFindings,\n reviewer: args.reviewer,\n reviewMethod: args.reviewMethod,\n });\n\n const decisionCounts: Record<ReviewDecision, number> = {\n accepted_for_synthesis: 0,\n rejected: 0,\n needs_scope_repair: 0,\n needs_source_repair: 0,\n needs_contradiction_mapping: 0,\n needs_human_review: 0,\n };\n for (const r of claimReviews) decisionCounts[r.decision] += 1;\n\n const severityCounts: Record<FindingSeverity, number> = { info: 0, warn: 0, block: 0 };\n for (const f of dedupedFindings) severityCounts[f.severity] += 1;\n\n const allAccepted =\n args.candidateClaims.length > 0 &&\n claimReviews.every((r) => r.decision === 'accepted_for_synthesis');\n // Only promote section status when this run is on the active profile —\n // calibration / A/B runs must never touch section state.\n const activeProfileForPromote = await readActiveProfile(args.packPath, args.sectionId);\n const promoteEligible =\n args.profile === activeProfileForPromote ||\n (activeProfileForPromote === DEFAULT_PROFILE && args.profile === DEFAULT_PROFILE);\n const promoted = promoteEligible\n ? await maybePromoteToReviewed(args.packPath, args.sectionId, allAccepted)\n : false;\n\n const snapshot: ReviewSnapshot = ReviewSnapshotSchema.parse({\n section_id: args.sectionId,\n reviewer: args.reviewer,\n review_method: args.reviewMethod,\n reviewed_at: new Date().toISOString(),\n candidate_claims: args.candidateClaims.length,\n findings: dedupedFindings,\n claim_reviews: claimReviews,\n decision_counts: decisionCounts,\n severity_counts: severityCounts,\n llm_findings_rejected_ungrounded: args.llmFindingsRejected,\n promoted_to_reviewed: promoted,\n });\n\n // ALWAYS write the profile-scoped artifacts: even non-active runs leave a\n // full record under sections/<id>/reviews/<profile>/ for calibration.\n const profDir = profileDir(args.packPath, args.sectionId, args.profile);\n await mkdir(profDir, { recursive: true });\n await writeFile(join(profDir, 'review.json'), JSON.stringify(snapshot, null, 2), 'utf8');\n await writeFile(join(profDir, 'review.md'), renderReviewMarkdown(snapshot), 'utf8');\n const profileFindingsPath = join(profDir, 'findings.jsonl');\n for (const f of dedupedFindings) {\n await appendFile(profileFindingsPath, JSON.stringify(f) + '\\n', 'utf8');\n }\n const profileReviewsPath = join(profDir, 'claim-reviews.jsonl');\n for (const r of claimReviews) {\n await appendFile(profileReviewsPath, JSON.stringify(ClaimReviewSchema.parse(r)) + '\\n', 'utf8');\n }\n\n // Mirror to canonical paths ONLY when this profile is the active one (or\n // there is no active profile and we are running the implicit default).\n // This is what stops A/B experiments from corrupting the section's\n // effective review state.\n const activeProfile = await readActiveProfile(args.packPath, args.sectionId);\n const isActive = args.profile === activeProfile || (activeProfile === DEFAULT_PROFILE && args.profile === DEFAULT_PROFILE);\n if (isActive) {\n const auditsDir = join(args.packPath, 'audits');\n await mkdir(auditsDir, { recursive: true });\n await writeFile(\n join(auditsDir, `${args.sectionId}-review.json`),\n JSON.stringify(snapshot, null, 2),\n 'utf8',\n );\n await writeFile(\n join(auditsDir, `${args.sectionId}-review.md`),\n renderReviewMarkdown(snapshot),\n 'utf8',\n );\n const findingsPath = join(auditsDir, `${args.sectionId}-findings.jsonl`);\n for (const f of dedupedFindings) {\n await appendFile(findingsPath, JSON.stringify(f) + '\\n', 'utf8');\n }\n const reviewsPath = join(args.packPath, 'sections', args.sectionId, 'claim-reviews.jsonl');\n for (const r of claimReviews) {\n await appendFile(reviewsPath, JSON.stringify(ClaimReviewSchema.parse(r)) + '\\n', 'utf8');\n }\n }\n\n return {\n sectionId: args.sectionId,\n reviewer: args.reviewer,\n reviewMethod: args.reviewMethod,\n candidateClaims: args.candidateClaims.length,\n findingsAdded: dedupedFindings.length,\n findingsDeduped: dedupedCount,\n llmFindingsRejected: args.llmFindingsRejected,\n decisions: decisionCounts,\n blockingFindings: dedupedFindings.filter((f) => f.severity === 'block').length,\n promotedToReviewed: promoted,\n };\n}\n","import { existsSync } from 'node:fs';\nimport { copyFile, mkdir, readFile, writeFile, appendFile } from 'node:fs/promises';\nimport { join, resolve } from 'node:path';\nimport { parse as yamlParse, stringify as yamlStringify } from 'yaml';\n\nimport { PackNotFoundError, SectionNotFoundError } from '../errors.js';\nimport { ResearchYamlSchema } from '../intake/schema.js';\nimport {\n DEFAULT_PROFILE,\n isValidProfileName,\n profileDir,\n reviewActivePath,\n writeActiveProfile,\n type PromotionCalibrationSummary,\n} from './profiles.js';\nimport { ReviewSnapshotSchema } from './schema.js';\nimport { renderReviewMarkdown } from './markdown.js';\n\nexport interface PromoteOptions {\n sectionId: string;\n packPath?: string;\n profile: string;\n // Free-text rationale recorded on review-active.json. Strongly encouraged\n // — explains WHY this profile became section truth, not just which one.\n promotionReason?: string;\n // Optional calibration evidence captured at promotion time. The profile/\n // promote layer is provenance-first: future gate/audit/freeze can show\n // not just \"this is active\" but \"this was trusted because <numbers>\".\n calibrationSummary?: PromotionCalibrationSummary | null;\n // When true, also bump section status from gated → reviewed if every claim\n // in the promoted profile is accepted_for_synthesis.\n promoteSectionStatus?: boolean;\n now?: () => Date;\n}\n\nexport interface PromoteResult {\n packPath: string;\n sectionId: string;\n profile: string;\n promoted_at: string;\n promoted_method: string;\n promoted_reviewer: string;\n canonical_files_updated: string[];\n section_status_bumped: boolean;\n}\n\n// Promote a review profile: copy its artifacts to the canonical paths\n// (audits/<id>-review.{json,md}, audits/<id>-findings.jsonl,\n// sections/<id>/claim-reviews.jsonl) and write\n// sections/<id>/review-active.json. Until promoted, a profile is\n// calibration evidence; after, it is section truth.\nexport async function promote(options: PromoteOptions): Promise<PromoteResult> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n if (!existsSync(join(packPath, 'research.yaml'))) throw new PackNotFoundError(packPath);\n if (!existsSync(join(packPath, 'sections', options.sectionId)))\n throw new SectionNotFoundError(options.sectionId);\n if (!isValidProfileName(options.profile)) {\n throw new Error(\n `Invalid profile name \"${options.profile}\". Use a kebab/snake-case slug.`,\n );\n }\n const dir = profileDir(packPath, options.sectionId, options.profile);\n const reviewJsonPath = join(dir, 'review.json');\n if (!existsSync(reviewJsonPath)) {\n throw new Error(\n `Profile \"${options.profile}\" not found at ${dir}. Run \\`research-os review --profile ${options.profile}\\` first.`,\n );\n }\n\n // Load the profile's snapshot to discover reviewer/method for the receipt.\n const snapshot = ReviewSnapshotSchema.parse(\n JSON.parse(await readFile(reviewJsonPath, 'utf8')),\n );\n\n // Copy review.json + review.md to canonical audits/.\n const auditsDir = join(packPath, 'audits');\n await mkdir(auditsDir, { recursive: true });\n const canonicalReviewJson = join(auditsDir, `${options.sectionId}-review.json`);\n const canonicalReviewMd = join(auditsDir, `${options.sectionId}-review.md`);\n await copyFile(reviewJsonPath, canonicalReviewJson);\n await writeFile(canonicalReviewMd, renderReviewMarkdown(snapshot), 'utf8');\n\n // The findings.jsonl and claim-reviews.jsonl ledgers are append-only on\n // canonical. To make this profile's decisions effective, we re-append\n // every record from the profile so they are the LATEST writes.\n const canonicalFindings = join(auditsDir, `${options.sectionId}-findings.jsonl`);\n const profileFindings = join(dir, 'findings.jsonl');\n const writtenFindings: string[] = [];\n if (existsSync(profileFindings)) {\n const text = await readFile(profileFindings, 'utf8');\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n await appendFile(canonicalFindings, line + '\\n', 'utf8');\n writtenFindings.push(line);\n }\n }\n const canonicalReviews = join(packPath, 'sections', options.sectionId, 'claim-reviews.jsonl');\n const profileReviews = join(dir, 'claim-reviews.jsonl');\n if (existsSync(profileReviews)) {\n const text = await readFile(profileReviews, 'utf8');\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n await appendFile(canonicalReviews, line + '\\n', 'utf8');\n }\n }\n\n // Mark this profile as active. Carry promotion provenance so downstream\n // consumers can explain why the reviewer is trusted, not just point at\n // which one ran.\n const stamp = (options.now ?? (() => new Date()))();\n await writeActiveProfile(packPath, options.sectionId, {\n active_profile: options.profile,\n promoted_at: stamp.toISOString(),\n promoted_method: snapshot.review_method,\n promoted_reviewer: snapshot.reviewer,\n promotion_reason:\n options.promotionReason && options.promotionReason.trim().length >= 8\n ? options.promotionReason.trim()\n : `promoted from sections/${options.sectionId}/reviews/${options.profile}/`,\n calibration_summary: options.calibrationSummary ?? null,\n });\n\n let sectionStatusBumped = false;\n if (options.promoteSectionStatus) {\n const yamlPath = join(packPath, 'research.yaml');\n const research = ResearchYamlSchema.parse(yamlParse(await readFile(yamlPath, 'utf8')));\n const idx = research.sections.findIndex((s) => s.id === options.sectionId);\n if (idx >= 0 && research.sections[idx]!.status === 'gated') {\n const allAccepted =\n snapshot.candidate_claims > 0 &&\n snapshot.claim_reviews.every((r) => r.decision === 'accepted_for_synthesis');\n if (allAccepted) {\n research.sections[idx] = { ...research.sections[idx]!, status: 'reviewed' };\n await writeFile(yamlPath, yamlStringify(research, { lineWidth: 0 }), 'utf8');\n sectionStatusBumped = true;\n }\n }\n }\n\n return {\n packPath,\n sectionId: options.sectionId,\n profile: options.profile,\n promoted_at: stamp.toISOString(),\n promoted_method: snapshot.review_method,\n promoted_reviewer: snapshot.reviewer,\n canonical_files_updated: [\n canonicalReviewJson,\n canonicalReviewMd,\n canonicalReviews,\n canonicalFindings,\n reviewActivePath(packPath, options.sectionId),\n ],\n section_status_bumped: sectionStatusBumped,\n };\n}\n\n// Convenience for callers: `default` is implicitly the active profile when\n// review-active.json doesn't exist. Callers can use this to special-case\n// pre-profile packs.\nexport const PROMOTE_DEFAULT_PROFILE = DEFAULT_PROFILE;\n","export { review } from './run.js';\nexport {\n HeuristicReviewer,\n OllamaInternReviewer,\n defaultReviewers,\n pickReviewer,\n} from './reviewers/index.js';\nexport { promote, type PromoteOptions, type PromoteResult } from './promote.js';\nexport {\n DEFAULT_PROFILE,\n ReviewActiveSchema,\n type ReviewActive,\n readActiveProfile,\n writeActiveProfile,\n profileDir,\n reviewActivePath,\n isValidProfileName,\n} from './profiles.js';\nexport { deriveClaimReviews } from './decision.js';\nexport { renderReviewMarkdown } from './markdown.js';\nexport {\n FindingCategorySchema,\n FindingSeveritySchema,\n ReviewerNameSchema,\n ReviewDecisionSchema,\n ReviewConfidenceSchema,\n ReviewFindingSchema,\n ClaimReviewSchema,\n ReviewSnapshotSchema,\n type ReviewFinding,\n type ClaimReview,\n type ReviewSnapshot,\n} from './schema.js';\nexport type {\n FindingCategory,\n FindingSeverity,\n ReviewerName,\n ReviewDecision,\n DraftFinding,\n ReviewerResult,\n ReviewerInput,\n Reviewer,\n RunReviewOptions,\n RunReviewSummary,\n} from './types.js';\n","export const SCHEMA_VERSION = 1;\n\nexport const DDL_STATEMENTS: string[] = [\n `CREATE TABLE IF NOT EXISTS meta (\n key TEXT PRIMARY KEY,\n value TEXT NOT NULL\n )`,\n\n `CREATE TABLE IF NOT EXISTS artifacts (\n artifact_id TEXT PRIMARY KEY,\n artifact_type TEXT NOT NULL,\n section_id TEXT,\n path TEXT NOT NULL,\n sha256 TEXT,\n bytes INTEGER,\n indexed_at TEXT NOT NULL\n )`,\n\n `CREATE TABLE IF NOT EXISTS sections (\n section_id TEXT PRIMARY KEY,\n purpose TEXT,\n status TEXT,\n max_time_minutes INTEGER,\n min_sources INTEGER,\n primary_sources_required INTEGER,\n contradictions_required INTEGER,\n indexed_at TEXT NOT NULL\n )`,\n\n `CREATE TABLE IF NOT EXISTS sources (\n source_id TEXT PRIMARY KEY,\n section_id TEXT,\n url TEXT,\n publisher TEXT,\n source_type TEXT,\n relevance TEXT,\n asserts TEXT,\n scope TEXT,\n not_field TEXT,\n fetched_at TEXT,\n published_at TEXT,\n artifact_path TEXT NOT NULL,\n indexed_at TEXT NOT NULL\n )`,\n\n `CREATE TABLE IF NOT EXISTS claims (\n claim_id TEXT PRIMARY KEY,\n section_id TEXT NOT NULL,\n source_ids_json TEXT NOT NULL,\n asserts TEXT NOT NULL,\n scope TEXT,\n not_field TEXT,\n evidence_excerpt TEXT NOT NULL,\n confidence TEXT,\n extractor TEXT,\n extraction_method TEXT,\n review_state TEXT,\n artifact_path TEXT NOT NULL,\n indexed_at TEXT NOT NULL\n )`,\n\n `CREATE TABLE IF NOT EXISTS contradictions (\n contradiction_id TEXT PRIMARY KEY,\n section_id TEXT NOT NULL,\n type TEXT,\n severity TEXT,\n status TEXT,\n overlap_assessment TEXT,\n claim_ids_json TEXT NOT NULL,\n source_ids_json TEXT NOT NULL,\n summary TEXT,\n detector TEXT,\n artifact_path TEXT NOT NULL,\n indexed_at TEXT NOT NULL\n )`,\n\n `CREATE TABLE IF NOT EXISTS review_findings (\n finding_id TEXT PRIMARY KEY,\n section_id TEXT NOT NULL,\n category TEXT,\n severity TEXT,\n claim_ids_json TEXT NOT NULL,\n source_ids_json TEXT NOT NULL,\n summary TEXT,\n required_action TEXT,\n reviewer TEXT,\n artifact_path TEXT NOT NULL,\n indexed_at TEXT NOT NULL\n )`,\n\n `CREATE TABLE IF NOT EXISTS claim_reviews (\n rowid_pk INTEGER PRIMARY KEY AUTOINCREMENT,\n claim_id TEXT NOT NULL,\n section_id TEXT NOT NULL,\n decision TEXT,\n reason TEXT,\n reviewer TEXT,\n created_at TEXT,\n artifact_path TEXT NOT NULL,\n indexed_at TEXT NOT NULL\n )`,\n\n `CREATE TABLE IF NOT EXISTS gate_results (\n section_id TEXT PRIMARY KEY,\n verdict TEXT,\n synthesis_eligible INTEGER,\n failures_json TEXT,\n warnings_json TEXT,\n blocking_reasons_json TEXT,\n waivers_json TEXT,\n next_actions_json TEXT,\n artifact_path TEXT NOT NULL,\n checked_at TEXT,\n indexed_at TEXT NOT NULL\n )`,\n\n `CREATE TABLE IF NOT EXISTS fetch_receipts (\n receipt_id TEXT PRIMARY KEY,\n source_id TEXT,\n section_id TEXT,\n status INTEGER,\n fetch_outcome TEXT,\n content_type TEXT,\n sha256 TEXT,\n fetched_at TEXT,\n raw_text_path TEXT,\n artifact_path TEXT NOT NULL,\n indexed_at TEXT NOT NULL\n )`,\n\n `CREATE VIRTUAL TABLE IF NOT EXISTS facts_fts USING fts5(\n record_type UNINDEXED,\n record_id UNINDEXED,\n section_id UNINDEXED,\n artifact_path UNINDEXED,\n text,\n prefix='2 3 4'\n )`,\n\n `CREATE INDEX IF NOT EXISTS idx_sources_section ON sources(section_id)`,\n `CREATE INDEX IF NOT EXISTS idx_claims_section ON claims(section_id)`,\n `CREATE INDEX IF NOT EXISTS idx_contradictions_section ON contradictions(section_id)`,\n `CREATE INDEX IF NOT EXISTS idx_findings_section ON review_findings(section_id)`,\n `CREATE INDEX IF NOT EXISTS idx_reviews_claim ON claim_reviews(claim_id)`,\n `CREATE INDEX IF NOT EXISTS idx_receipts_source ON fetch_receipts(source_id)`,\n];\n\nexport function applySchema(db: import('better-sqlite3').Database): void {\n db.exec('PRAGMA journal_mode = WAL;');\n db.exec('PRAGMA foreign_keys = ON;');\n for (const ddl of DDL_STATEMENTS) {\n db.exec(ddl);\n }\n const setMeta = db.prepare('INSERT OR REPLACE INTO meta(key, value) VALUES (?, ?)');\n setMeta.run('schema_version', String(SCHEMA_VERSION));\n}\n","import { mkdirSync, writeFileSync, existsSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport Database from 'better-sqlite3';\n\nimport { applySchema } from './schema.js';\n\nexport interface OpenDbOptions {\n packPath: string;\n readonly?: boolean;\n}\n\nexport function indexDbPath(packPath: string): string {\n return join(packPath, '.research-os', 'index.sqlite');\n}\n\nfunction ensureGitIgnore(packPath: string): void {\n const dir = join(packPath, '.research-os');\n const gi = join(dir, '.gitignore');\n if (!existsSync(gi)) {\n mkdirSync(dir, { recursive: true });\n writeFileSync(gi, '*\\n', 'utf8');\n }\n}\n\nexport function openIndexDb(opts: OpenDbOptions): Database.Database {\n const dbPath = indexDbPath(opts.packPath);\n if (!opts.readonly) {\n mkdirSync(dirname(dbPath), { recursive: true });\n ensureGitIgnore(opts.packPath);\n }\n const db = new Database(dbPath, { readonly: opts.readonly ?? false, fileMustExist: opts.readonly ?? false });\n if (!opts.readonly) applySchema(db);\n return db;\n}\n","import { existsSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { join, resolve, relative } from 'node:path';\nimport { createHash } from 'node:crypto';\nimport { parse as yamlParse } from 'yaml';\nimport type Database from 'better-sqlite3';\n\nimport { PackNotFoundError, SectionNotFoundError } from '../errors.js';\nimport { ResearchYamlSchema, type ResearchYaml } from '../intake/schema.js';\nimport { ClaimSchema, type Claim } from '../claims/schema.js';\nimport { ContradictionSchema, type Contradiction } from '../contradictions/schema.js';\nimport {\n FetchReceiptSchema,\n SourceCardSchema,\n type FetchReceipt,\n type SourceCard,\n} from '../sources/schema.js';\nimport {\n SectionGateResultSchema,\n type SectionGateResult,\n} from '../gates/schema.js';\nimport {\n ClaimReviewSchema,\n ReviewFindingSchema,\n type ClaimReview,\n type ReviewFinding,\n} from '../review/schema.js';\n\nimport { openIndexDb, indexDbPath } from './db.js';\nimport type { IndexBuildOptions, IndexBuildSummary } from './types.js';\n\nfunction relPath(packPath: string, abs: string): string {\n return relative(packPath, abs).split('\\\\').join('/');\n}\n\nasync function tryReadJsonl<T>(\n packPath: string,\n rel: string,\n parse: (raw: unknown) => T,\n): Promise<T[]> {\n const path = join(packPath, rel);\n if (!existsSync(path)) return [];\n const text = await readFile(path, 'utf8');\n const out: T[] = [];\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n out.push(parse(JSON.parse(line)));\n }\n return out;\n}\n\nasync function readSourceCards(packPath: string): Promise<SourceCard[]> {\n const dir = join(packPath, 'evidence', 'source-cards');\n if (!existsSync(dir)) return [];\n const { readdir } = await import('node:fs/promises');\n const entries = await readdir(dir);\n const cards: SourceCard[] = [];\n for (const entry of entries) {\n if (!entry.endsWith('.json')) continue;\n const text = await readFile(join(dir, entry), 'utf8');\n cards.push(SourceCardSchema.parse(JSON.parse(text)));\n }\n return cards;\n}\n\nasync function readGateResult(packPath: string, sectionId: string): Promise<SectionGateResult | null> {\n const path = join(packPath, 'audits', `${sectionId}-gate.json`);\n if (!existsSync(path)) return null;\n const text = await readFile(path, 'utf8');\n return SectionGateResultSchema.parse(JSON.parse(text));\n}\n\n\nfunction fileSha256(text: string): string {\n return createHash('sha256').update(text).digest('hex');\n}\n\nasync function indexSection(args: {\n db: Database.Database;\n packPath: string;\n research: ResearchYaml;\n sectionId: string;\n now: string;\n counts: IndexBuildSummary;\n}): Promise<void> {\n const { db, packPath, research, sectionId, now, counts } = args;\n\n const section = research.sections.find((s) => s.id === sectionId);\n if (!section) throw new SectionNotFoundError(sectionId);\n const sectionDir = join(packPath, 'sections', sectionId);\n if (!existsSync(sectionDir)) throw new SectionNotFoundError(sectionId);\n\n // Clear all existing rows for this section so re-index is clean\n db.prepare('DELETE FROM sources WHERE section_id = ?').run(sectionId);\n db.prepare('DELETE FROM claims WHERE section_id = ?').run(sectionId);\n db.prepare('DELETE FROM contradictions WHERE section_id = ?').run(sectionId);\n db.prepare('DELETE FROM review_findings WHERE section_id = ?').run(sectionId);\n db.prepare('DELETE FROM claim_reviews WHERE section_id = ?').run(sectionId);\n db.prepare('DELETE FROM gate_results WHERE section_id = ?').run(sectionId);\n db.prepare('DELETE FROM fetch_receipts WHERE section_id = ?').run(sectionId);\n db.prepare('DELETE FROM artifacts WHERE section_id = ?').run(sectionId);\n db.prepare('DELETE FROM facts_fts WHERE section_id = ?').run(sectionId);\n\n // Section row\n db.prepare(\n `INSERT OR REPLACE INTO sections(section_id, purpose, status, max_time_minutes,\n min_sources, primary_sources_required, contradictions_required, indexed_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,\n ).run(\n section.id,\n section.purpose,\n section.status,\n section.max_time_minutes,\n section.min_sources,\n section.primary_sources_required,\n section.contradictions_required ? 1 : 0,\n now,\n );\n\n const insertArtifact = db.prepare(\n `INSERT OR REPLACE INTO artifacts(artifact_id, artifact_type, section_id, path, sha256, bytes, indexed_at)\n VALUES (?, ?, ?, ?, ?, ?, ?)`,\n );\n const insertFts = db.prepare(\n `INSERT INTO facts_fts(record_type, record_id, section_id, artifact_path, text)\n VALUES (?, ?, ?, ?, ?)`,\n );\n const recordArtifact = (artifactType: string, rel: string, content: string | null): void => {\n const sha = content === null ? null : fileSha256(content);\n insertArtifact.run(`${sectionId}:${artifactType}`, artifactType, sectionId, rel, sha, content === null ? null : Buffer.byteLength(content, 'utf8'), now);\n counts.artifacts += 1;\n };\n\n // Sources (cards) — only those tagged for this section\n const allCards = await readSourceCards(packPath);\n const sectionSourceIds = new Set<string>();\n const sourcesJsonlPath = join(sectionDir, 'sources.jsonl');\n if (existsSync(sourcesJsonlPath)) {\n const text = await readFile(sourcesJsonlPath, 'utf8');\n recordArtifact('sources_jsonl', relPath(packPath, sourcesJsonlPath), text);\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n const entry = JSON.parse(line) as { source_id?: string };\n if (typeof entry.source_id === 'string') sectionSourceIds.add(entry.source_id);\n }\n }\n for (const card of allCards) {\n if (!sectionSourceIds.has(card.source_id) && card.section_id !== sectionId) continue;\n const cardPath = relPath(packPath, join(packPath, 'evidence', 'source-cards', `${card.source_id}.json`));\n db.prepare(\n `INSERT OR REPLACE INTO sources(\n source_id, section_id, url, publisher, source_type, relevance,\n asserts, scope, not_field, fetched_at, published_at, artifact_path, indexed_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n ).run(\n card.source_id,\n sectionId,\n card.url,\n card.publisher,\n card.source_type,\n card.relevance,\n card.asserts,\n card.scope,\n card.not,\n card.fetched_at,\n card.published_at,\n cardPath,\n now,\n );\n counts.sources += 1;\n const text = `${card.title}\\n${card.asserts}\\n${card.scope ?? ''}\\n${card.not ?? ''}\\n${card.key_points.join('\\n')}`;\n insertFts.run('source', card.source_id, sectionId, cardPath, text);\n }\n\n // Claims\n const claims = await tryReadJsonl<Claim>(\n packPath,\n `sections/${sectionId}/claims.jsonl`,\n (r) => ClaimSchema.parse(r),\n );\n const claimsArtifact = relPath(packPath, join(sectionDir, 'claims.jsonl'));\n if (existsSync(join(sectionDir, 'claims.jsonl'))) {\n const text = await readFile(join(sectionDir, 'claims.jsonl'), 'utf8');\n recordArtifact('claims_jsonl', claimsArtifact, text);\n }\n for (const claim of claims) {\n db.prepare(\n `INSERT OR REPLACE INTO claims(\n claim_id, section_id, source_ids_json, asserts, scope, not_field,\n evidence_excerpt, confidence, extractor, extraction_method, review_state,\n artifact_path, indexed_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n ).run(\n claim.claim_id,\n sectionId,\n JSON.stringify(claim.source_ids),\n claim.asserts,\n claim.scope,\n claim.not,\n claim.evidence_excerpt,\n claim.confidence,\n claim.extractor,\n claim.extraction_method,\n claim.review_state,\n claimsArtifact,\n now,\n );\n counts.claims += 1;\n const ftsText = `${claim.asserts}\\n${claim.scope ?? ''}\\n${claim.not ?? ''}\\n${claim.evidence_excerpt}`;\n insertFts.run('claim', claim.claim_id, sectionId, claimsArtifact, ftsText);\n }\n\n // Contradictions\n const contradictions = await tryReadJsonl<Contradiction>(\n packPath,\n `sections/${sectionId}/contradictions.jsonl`,\n (r) => ContradictionSchema.parse(r),\n );\n const contradictionsArtifact = relPath(packPath, join(sectionDir, 'contradictions.jsonl'));\n if (existsSync(join(sectionDir, 'contradictions.jsonl'))) {\n const text = await readFile(join(sectionDir, 'contradictions.jsonl'), 'utf8');\n recordArtifact('contradictions_jsonl', contradictionsArtifact, text);\n }\n for (const c of contradictions) {\n db.prepare(\n `INSERT OR REPLACE INTO contradictions(\n contradiction_id, section_id, type, severity, status, overlap_assessment,\n claim_ids_json, source_ids_json, summary, detector, artifact_path, indexed_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n ).run(\n c.contradiction_id,\n sectionId,\n c.type,\n c.severity,\n c.status,\n c.overlap_assessment,\n JSON.stringify(c.claim_ids),\n JSON.stringify(c.source_ids),\n c.summary,\n c.detector,\n contradictionsArtifact,\n now,\n );\n counts.contradictions += 1;\n const ftsText = `${c.summary}\\n${c.scope_analysis}\\n${c.evidence}\\n${c.type}\\n${c.severity}`;\n insertFts.run('contradiction', c.contradiction_id, sectionId, contradictionsArtifact, ftsText);\n }\n\n // Review findings\n const findings = await tryReadJsonl<ReviewFinding>(\n packPath,\n `audits/${sectionId}-findings.jsonl`,\n (r) => ReviewFindingSchema.parse(r),\n );\n const findingsArtifact = relPath(packPath, join(packPath, 'audits', `${sectionId}-findings.jsonl`));\n const findingsAbs = join(packPath, 'audits', `${sectionId}-findings.jsonl`);\n if (existsSync(findingsAbs)) {\n const text = await readFile(findingsAbs, 'utf8');\n recordArtifact('findings_jsonl', findingsArtifact, text);\n }\n // Dedup findings by ID since the ledger is append-only — keep the latest occurrence\n const findingById = new Map<string, ReviewFinding>();\n for (const f of findings) findingById.set(f.finding_id, f);\n for (const f of findingById.values()) {\n db.prepare(\n `INSERT OR REPLACE INTO review_findings(\n finding_id, section_id, category, severity, claim_ids_json, source_ids_json,\n summary, required_action, reviewer, artifact_path, indexed_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n ).run(\n f.finding_id,\n sectionId,\n f.category,\n f.severity,\n JSON.stringify(f.claim_ids),\n JSON.stringify(f.source_ids),\n f.summary,\n f.required_action,\n f.reviewer,\n findingsArtifact,\n now,\n );\n counts.reviewFindings += 1;\n const ftsText = `${f.category}\\n${f.severity}\\n${f.summary}\\n${f.required_action}\\n${f.evidence}`;\n insertFts.run('review_finding', f.finding_id, sectionId, findingsArtifact, ftsText);\n }\n\n // Claim reviews (append-only ledger — every entry is preserved)\n const reviews = await tryReadJsonl<ClaimReview>(\n packPath,\n `sections/${sectionId}/claim-reviews.jsonl`,\n (r) => ClaimReviewSchema.parse(r),\n );\n const reviewsArtifact = relPath(packPath, join(sectionDir, 'claim-reviews.jsonl'));\n const reviewsAbs = join(sectionDir, 'claim-reviews.jsonl');\n if (existsSync(reviewsAbs)) {\n const text = await readFile(reviewsAbs, 'utf8');\n recordArtifact('claim_reviews_jsonl', reviewsArtifact, text);\n }\n for (const r of reviews) {\n db.prepare(\n `INSERT INTO claim_reviews(\n claim_id, section_id, decision, reason, reviewer, created_at, artifact_path, indexed_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,\n ).run(\n r.claim_id,\n sectionId,\n r.decision,\n r.reason,\n r.reviewer,\n r.created_at,\n reviewsArtifact,\n now,\n );\n counts.claimReviews += 1;\n const ftsText = `${r.decision}\\n${r.reason}`;\n insertFts.run('claim_review', `${r.claim_id}@${r.created_at}`, sectionId, reviewsArtifact, ftsText);\n }\n\n // Gate result\n const gate = await readGateResult(packPath, sectionId);\n if (gate) {\n const gateArtifact = relPath(packPath, join(packPath, 'audits', `${sectionId}-gate.json`));\n const gateText = await readFile(join(packPath, 'audits', `${sectionId}-gate.json`), 'utf8');\n recordArtifact('gate_json', gateArtifact, gateText);\n db.prepare(\n `INSERT OR REPLACE INTO gate_results(\n section_id, verdict, synthesis_eligible,\n failures_json, warnings_json, blocking_reasons_json, waivers_json, next_actions_json,\n artifact_path, checked_at, indexed_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n ).run(\n gate.section_id,\n gate.verdict,\n gate.synthesis_eligible ? 1 : 0,\n JSON.stringify(gate.failures),\n JSON.stringify(gate.warnings),\n JSON.stringify(gate.blocking_reasons),\n JSON.stringify(gate.waivers_applied),\n JSON.stringify(gate.next_actions),\n gateArtifact,\n gate.checked_at,\n now,\n );\n counts.gateResults += 1;\n const ftsText = `${gate.verdict}\\n${gate.summary}\\n${gate.blocking_reasons.join('\\n')}\\n${gate.next_actions.join('\\n')}`;\n insertFts.run('gate_result', sectionId, sectionId, gateArtifact, ftsText);\n }\n\n // Fetch receipts (filtered to this section by section_id field)\n const allReceipts = await tryReadJsonl<FetchReceipt>(\n packPath,\n 'evidence/fetch-log.jsonl',\n (r) => FetchReceiptSchema.parse(r),\n );\n const fetchLogAbs = join(packPath, 'evidence', 'fetch-log.jsonl');\n if (existsSync(fetchLogAbs)) {\n const text = await readFile(fetchLogAbs, 'utf8');\n recordArtifact('fetch_log_jsonl', relPath(packPath, fetchLogAbs), text);\n }\n for (const receipt of allReceipts.filter((r) => r.section_id === sectionId)) {\n db.prepare(\n `INSERT OR REPLACE INTO fetch_receipts(\n receipt_id, source_id, section_id, status, fetch_outcome, content_type,\n sha256, fetched_at, raw_text_path, artifact_path, indexed_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n ).run(\n receipt.receipt_id,\n receipt.source_id,\n receipt.section_id,\n receipt.status,\n receipt.fetch_outcome,\n receipt.content_type,\n receipt.sha256,\n receipt.fetched_at,\n receipt.raw_text_path,\n relPath(packPath, fetchLogAbs),\n now,\n );\n counts.fetchReceipts += 1;\n const ftsText = `${receipt.fetch_outcome} ${receipt.requested_url} ${receipt.title ?? ''} ${receipt.fetch_error ?? ''}`;\n insertFts.run('fetch_receipt', receipt.receipt_id, sectionId, relPath(packPath, fetchLogAbs), ftsText);\n }\n}\n\nconst ROLLUP_FILES: Array<{ filename: string; recordType: 'pack_audit' | 'audit_rollup'; recordId: string }> = [\n { filename: 'pack-audit.json', recordType: 'pack_audit', recordId: 'pack_audit' },\n { filename: 'orphan-claims.json', recordType: 'audit_rollup', recordId: 'orphan-claims' },\n { filename: 'stale-sources.json', recordType: 'audit_rollup', recordId: 'stale-sources' },\n { filename: 'weak-sources.json', recordType: 'audit_rollup', recordId: 'weak-sources' },\n { filename: 'unresolved-contradictions.json', recordType: 'audit_rollup', recordId: 'unresolved-contradictions' },\n { filename: 'scope-widening-risks.json', recordType: 'audit_rollup', recordId: 'scope-widening-risks' },\n { filename: 'source-diversity-gaps.json', recordType: 'audit_rollup', recordId: 'source-diversity-gaps' },\n { filename: 'synthesis-readiness.json', recordType: 'audit_rollup', recordId: 'synthesis-readiness' },\n];\n\nasync function indexPackAuditRollups(\n db: Database.Database,\n packPath: string,\n _now: string,\n): Promise<void> {\n const insertFts = db.prepare(\n `INSERT INTO facts_fts(record_type, record_id, section_id, artifact_path, text)\n VALUES (?, ?, ?, ?, ?)`,\n );\n // Clear any prior rollup entries first (each record_id is unique per type)\n for (const f of ROLLUP_FILES) {\n db.prepare(`DELETE FROM facts_fts WHERE record_type = ? AND record_id = ?`).run(f.recordType, f.recordId);\n }\n for (const f of ROLLUP_FILES) {\n const abs = join(packPath, 'audits', f.filename);\n if (!existsSync(abs)) continue;\n const text = await readFile(abs, 'utf8');\n insertFts.run(\n f.recordType,\n f.recordId,\n null,\n `audits/${f.filename}`,\n text.slice(0, 24_000),\n );\n }\n}\n\nexport async function build(options: IndexBuildOptions): Promise<IndexBuildSummary> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n if (!existsSync(join(packPath, 'research.yaml'))) throw new PackNotFoundError(packPath);\n const research = ResearchYamlSchema.parse(yamlParse(await readFile(join(packPath, 'research.yaml'), 'utf8')));\n\n const targets: string[] = options.sectionId\n ? [options.sectionId]\n : options.all\n ? research.sections.map((s) => s.id)\n : research.sections.map((s) => s.id);\n\n if (targets.length === 0) {\n throw new Error('No sections to index. Add at least one section to the pack.');\n }\n\n const db = openIndexDb({ packPath });\n const now = new Date().toISOString();\n const counts: IndexBuildSummary = {\n packPath,\n dbPath: indexDbPath(packPath),\n sectionsIndexed: 0,\n sources: 0,\n claims: 0,\n contradictions: 0,\n reviewFindings: 0,\n claimReviews: 0,\n gateResults: 0,\n fetchReceipts: 0,\n artifacts: 0,\n };\n\n try {\n for (const sid of targets) {\n await indexSection({ db, packPath, research, sectionId: sid, now, counts });\n counts.sectionsIndexed += 1;\n }\n await indexPackAuditRollups(db, packPath, now);\n } finally {\n db.close();\n }\n\n return counts;\n}\n","import { existsSync } from 'node:fs';\nimport { resolve } from 'node:path';\n\nimport { PackNotFoundError } from '../errors.js';\nimport { openIndexDb, indexDbPath } from './db.js';\nimport type { IndexQueryOptions, IndexQuerySummary, QueryHit, RecordType } from './types.js';\n\nexport class IndexNotBuiltError extends Error {\n constructor(public readonly dbPath: string) {\n super(\n `No index found at ${dbPath}. Run 'research-os index --all' to build it before querying.`,\n );\n this.name = 'IndexNotBuiltError';\n }\n}\n\nfunction escapeFtsTerm(term: string): string {\n // Quote each word and OR them together so common phrasing works.\n // For simplicity: wrap the entire term in quotes if it contains spaces,\n // otherwise pass through. FTS5 prefix queries supported via *.\n const trimmed = term.trim();\n if (!trimmed) return '\"\"';\n // If user already provided FTS syntax characters, pass through. Otherwise quote.\n if (/[\" *^()-]/.test(trimmed)) return trimmed;\n return `\"${trimmed.replace(/\"/g, '\"\"')}\"`;\n}\n\nexport function query(options: IndexQueryOptions): IndexQuerySummary {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n const dbPath = indexDbPath(packPath);\n if (!existsSync(packPath)) throw new PackNotFoundError(packPath);\n if (!existsSync(dbPath)) throw new IndexNotBuiltError(dbPath);\n\n const db = openIndexDb({ packPath, readonly: true });\n const limit = options.limit ?? 25;\n const ftsTerm = escapeFtsTerm(options.term);\n\n let stmt;\n let rows: Array<{\n record_type: string;\n record_id: string;\n section_id: string | null;\n artifact_path: string;\n snippet: string;\n rank: number;\n }>;\n try {\n if (options.recordType) {\n stmt = db.prepare(\n `SELECT record_type, record_id, section_id, artifact_path,\n snippet(facts_fts, 4, '<mark>', '</mark>', '...', 30) AS snippet,\n rank\n FROM facts_fts\n WHERE facts_fts MATCH ?\n AND record_type = ?\n ORDER BY rank\n LIMIT ?`,\n );\n rows = stmt.all(ftsTerm, options.recordType, limit) as typeof rows;\n } else {\n stmt = db.prepare(\n `SELECT record_type, record_id, section_id, artifact_path,\n snippet(facts_fts, 4, '<mark>', '</mark>', '...', 30) AS snippet,\n rank\n FROM facts_fts\n WHERE facts_fts MATCH ?\n ORDER BY rank\n LIMIT ?`,\n );\n rows = stmt.all(ftsTerm, limit) as typeof rows;\n }\n } finally {\n db.close();\n }\n\n const hits: QueryHit[] = rows.map((r) => ({\n record_type: r.record_type as RecordType,\n record_id: r.record_id,\n section_id: r.section_id,\n artifact_path: r.artifact_path,\n snippet: r.snippet,\n rank: r.rank,\n }));\n\n const grouped: Record<string, QueryHit[]> = {};\n for (const h of hits) {\n if (!grouped[h.record_type]) grouped[h.record_type] = [];\n grouped[h.record_type]!.push(h);\n }\n\n return {\n term: options.term,\n totalHits: hits.length,\n hits,\n groupedByType: grouped,\n };\n}\n","import { existsSync } from 'node:fs';\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join, resolve } from 'node:path';\n\nimport { PackNotFoundError } from '../errors.js';\nimport { openIndexDb, indexDbPath } from './db.js';\nimport { IndexNotBuiltError } from './query.js';\nimport type { ExportOptions, ExportSummary } from './types.js';\n\ninterface FactRow {\n fact_type: string;\n id: string;\n section_id: string | null;\n text: string;\n artifact_path: string;\n metadata: Record<string, unknown>;\n pack_origin: string;\n exported_at: string;\n}\n\nexport async function exportRepoKnowledge(options: ExportOptions): Promise<ExportSummary> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n if (!existsSync(packPath)) throw new PackNotFoundError(packPath);\n const dbPath = indexDbPath(packPath);\n if (!existsSync(dbPath)) throw new IndexNotBuiltError(dbPath);\n\n const outPath = options.outPath\n ? resolve(options.outPath)\n : join(packPath, 'evidence', 'repo-knowledge', 'research-os-facts.jsonl');\n await mkdir(dirname(outPath), { recursive: true });\n\n const db = openIndexDb({ packPath, readonly: true });\n const now = new Date().toISOString();\n const facts: FactRow[] = [];\n const byType: Record<string, number> = {};\n const incr = (t: string): void => {\n byType[t] = (byType[t] ?? 0) + 1;\n };\n\n try {\n const sources = db\n .prepare(`SELECT * FROM sources`)\n .all() as Array<Record<string, unknown>>;\n for (const r of sources) {\n facts.push({\n fact_type: 'research_os.source',\n id: String(r.source_id),\n section_id: r.section_id as string | null,\n text: [r.asserts, r.scope, r.not_field].filter(Boolean).join(' '),\n artifact_path: String(r.artifact_path),\n metadata: {\n url: r.url,\n publisher: r.publisher,\n source_type: r.source_type,\n relevance: r.relevance,\n fetched_at: r.fetched_at,\n published_at: r.published_at,\n },\n pack_origin: packPath,\n exported_at: now,\n });\n incr('research_os.source');\n }\n\n const claims = db\n .prepare(`SELECT * FROM claims`)\n .all() as Array<Record<string, unknown>>;\n for (const r of claims) {\n facts.push({\n fact_type: 'research_os.claim',\n id: String(r.claim_id),\n section_id: r.section_id as string,\n text: [r.asserts, r.scope, r.not_field, r.evidence_excerpt].filter(Boolean).join(' '),\n artifact_path: String(r.artifact_path),\n metadata: {\n source_ids: JSON.parse(String(r.source_ids_json)),\n confidence: r.confidence,\n extractor: r.extractor,\n extraction_method: r.extraction_method,\n review_state: r.review_state,\n },\n pack_origin: packPath,\n exported_at: now,\n });\n incr('research_os.claim');\n }\n\n const contradictions = db\n .prepare(`SELECT * FROM contradictions`)\n .all() as Array<Record<string, unknown>>;\n for (const r of contradictions) {\n facts.push({\n fact_type: 'research_os.contradiction',\n id: String(r.contradiction_id),\n section_id: r.section_id as string,\n text: String(r.summary ?? ''),\n artifact_path: String(r.artifact_path),\n metadata: {\n type: r.type,\n severity: r.severity,\n status: r.status,\n overlap_assessment: r.overlap_assessment,\n claim_ids: JSON.parse(String(r.claim_ids_json)),\n source_ids: JSON.parse(String(r.source_ids_json)),\n detector: r.detector,\n },\n pack_origin: packPath,\n exported_at: now,\n });\n incr('research_os.contradiction');\n }\n\n const findings = db\n .prepare(`SELECT * FROM review_findings`)\n .all() as Array<Record<string, unknown>>;\n for (const r of findings) {\n facts.push({\n fact_type: 'research_os.review_finding',\n id: String(r.finding_id),\n section_id: r.section_id as string,\n text: [r.summary, r.required_action].filter(Boolean).join(' '),\n artifact_path: String(r.artifact_path),\n metadata: {\n category: r.category,\n severity: r.severity,\n claim_ids: JSON.parse(String(r.claim_ids_json)),\n source_ids: JSON.parse(String(r.source_ids_json)),\n reviewer: r.reviewer,\n },\n pack_origin: packPath,\n exported_at: now,\n });\n incr('research_os.review_finding');\n }\n\n const gates = db\n .prepare(`SELECT * FROM gate_results`)\n .all() as Array<Record<string, unknown>>;\n for (const r of gates) {\n facts.push({\n fact_type: 'research_os.gate_result',\n id: String(r.section_id),\n section_id: r.section_id as string,\n text: `${r.verdict} ${(JSON.parse(String(r.blocking_reasons_json)) as string[]).join(' ')}`,\n artifact_path: String(r.artifact_path),\n metadata: {\n verdict: r.verdict,\n synthesis_eligible: r.synthesis_eligible === 1,\n checked_at: r.checked_at,\n blocking_reasons: JSON.parse(String(r.blocking_reasons_json)),\n waivers: JSON.parse(String(r.waivers_json)),\n next_actions: JSON.parse(String(r.next_actions_json)),\n },\n pack_origin: packPath,\n exported_at: now,\n });\n incr('research_os.gate_result');\n }\n } finally {\n db.close();\n }\n\n const text = facts.map((f) => JSON.stringify(f)).join('\\n') + (facts.length > 0 ? '\\n' : '');\n await writeFile(outPath, text, 'utf8');\n\n return {\n outPath,\n factCount: facts.length,\n byType,\n };\n}\n","import { resolve } from 'node:path';\n\nimport { exportRepoKnowledge } from './export.js';\nimport type { SyncOptions, SyncSummary } from './types.js';\n\ninterface RepoKnowledgeShape {\n ingestFacts?: (args: {\n facts: unknown[];\n namespace?: string;\n }) => Promise<{ count: number }> | { count: number };\n}\n\nasync function loadRepoKnowledge(): Promise<RepoKnowledgeShape | null> {\n // Optional peer dependency; resolved dynamically at runtime so the package\n // does not need to be installed for the rest of research-os to work.\n const pkgName = '@mcptoolshop/repo-knowledge';\n try {\n const mod = (await import(/* @vite-ignore */ pkgName).catch(() => null)) as\n | RepoKnowledgeShape\n | null;\n return mod;\n } catch {\n return null;\n }\n}\n\nexport async function syncRepoKnowledge(options: SyncOptions): Promise<SyncSummary> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n const rk = await loadRepoKnowledge();\n if (!rk || typeof rk.ingestFacts !== 'function') {\n return {\n attempted: false,\n ok: false,\n reason:\n '@mcptoolshop/repo-knowledge not available locally. Sync skipped — pack remains self-contained. Use `research-os index export-repo-knowledge` for a portable export instead.',\n factsSynced: 0,\n };\n }\n\n const exportResult = await exportRepoKnowledge({ packPath });\n // Re-read the JSONL we just wrote so repo-knowledge ingests the same canonical fact stream\n const { readFile } = await import('node:fs/promises');\n const text = await readFile(exportResult.outPath, 'utf8');\n const facts = text\n .split(/\\r?\\n/)\n .filter((l) => l.trim().length > 0)\n .map((l) => JSON.parse(l));\n\n try {\n const r = await rk.ingestFacts({ facts, namespace: 'research-os' });\n return {\n attempted: true,\n ok: true,\n reason: 'ingested via @mcptoolshop/repo-knowledge.ingestFacts',\n factsSynced: r.count ?? facts.length,\n };\n } catch (err) {\n return {\n attempted: true,\n ok: false,\n reason: err instanceof Error ? err.message : 'unknown ingest error',\n factsSynced: 0,\n };\n }\n}\n","export { build } from './build.js';\nexport { query, IndexNotBuiltError } from './query.js';\nexport { exportRepoKnowledge } from './export.js';\nexport { syncRepoKnowledge } from './sync.js';\nexport { openIndexDb, indexDbPath } from './db.js';\nexport { applySchema, SCHEMA_VERSION } from './schema.js';\nexport type {\n IndexBuildOptions,\n IndexBuildSummary,\n IndexQueryOptions,\n IndexQuerySummary,\n QueryHit,\n RecordType,\n ExportOptions,\n ExportSummary,\n SyncOptions,\n SyncSummary,\n} from './types.js';\n","import { z } from 'zod';\n\nexport const ClaimSynthesisDispositionStatusSchema = z.enum([\n 'parked_not_for_synthesis',\n 'preserved_for_human_note',\n 'needs_human_review_excluded',\n 'out_of_bounds_regression_fixture',\n]);\n\nexport const ClaimSynthesisDispositionSchema = z.object({\n claim_id: z.string().min(1),\n section_id: z.string().min(1),\n status: ClaimSynthesisDispositionStatusSchema,\n reason: z.string().min(4),\n decided_by: z.string().min(1),\n authorized_by: z.string().min(1),\n source: z.string().min(1),\n created_at: z.string().min(1),\n});\n\nexport type ClaimSynthesisDisposition = z.infer<typeof ClaimSynthesisDispositionSchema>;\nexport type ClaimSynthesisDispositionStatus = z.infer<typeof ClaimSynthesisDispositionStatusSchema>;\n","import { createHash } from 'node:crypto';\n\nimport type { ResearchYaml } from '../intake/schema.js';\nimport type { Claim } from '../claims/schema.js';\nimport type { ClaimReview } from '../review/schema.js';\nimport type { Contradiction } from '../contradictions/schema.js';\nimport type { ContradictionResolution } from '../contradictions/resolution-schema.js';\nimport type { ClaimSynthesisDisposition } from '../dispositions/schema.js';\nimport type { SectionGateResult } from '../gates/schema.js';\n\nimport type {\n CoworkHandoffPayload,\n HandoffMode,\n IndexStatus,\n ProvenanceSummary,\n ReviewDecisionCount,\n SectionState,\n WaiverEntry,\n} from './types.js';\n\nexport interface DeriveInput {\n research: ResearchYaml;\n perSection: Map<\n string,\n {\n gate: SectionGateResult | null;\n candidateClaims: Claim[];\n claimReviews: ClaimReview[];\n contradictions: Contradiction[];\n resolutions?: ContradictionResolution[];\n dispositions?: ClaimSynthesisDisposition[];\n }\n >;\n indexStatus: IndexStatus;\n generatedAt: string;\n warnings: string[];\n}\n\nexport const FORBIDDEN_ACTIONS_ALWAYS = [\n 'Mutate sections/<id>/claims.jsonl directly — it is extraction truth (append-only via research-os tools)',\n 'Mutate evidence/source-cards/*.json or evidence/fetch-log.jsonl — these are fetched-truth artifacts',\n 'Mutate audits/*-gate.json or audits/*-review.json — these are immutable audit snapshots',\n 'Cite a source_id that is not present in evidence/source-cards/',\n 'Cite a claim_id that is not present in sections/<id>/claims.jsonl',\n 'Treat a claim with scope=null as broadly applicable — null-scope means scope-undetermined, not scope-universal',\n 'Widen the scope of a claim beyond what the source explicitly supports',\n 'Flatten an unresolved contradiction; preserve it deliberately or route it through claim-reviews',\n 'Write final synthesis prose unless mode == synthesis_ready',\n 'Reconcile contradictions silently — use research-os contradict map / research-os review with explicit decisions',\n];\n\nconst ALLOWED_WRITE_BASE = [\n 'handoffs/cowork-options.md',\n 'handoffs/cowork-notes.md',\n];\n\nconst ALLOWED_WRITE_REPAIR = [\n ...ALLOWED_WRITE_BASE,\n 'sections/<id>/open_questions.md',\n 'sections/<id>/brief.md (working notes only — final brief lands at synthesis time)',\n 'audits/<id>-cowork-repair-notes.md',\n];\n\nconst ALLOWED_WRITE_SYNTHESIS = [\n ...ALLOWED_WRITE_BASE,\n 'synthesis/cross-section-map.md',\n 'synthesis/decision-brief.md',\n 'synthesis/final-report.md',\n 'synthesis/working-report.md',\n 'sections/<id>/brief.md (final form, drawing from accepted claims only)',\n];\n\nfunction packId(research: ResearchYaml): string {\n const fingerprint = `${research.topic}|${research.created_at}`;\n return createHash('sha256').update(fingerprint).digest('hex').slice(0, 12);\n}\n\nfunction latestDecisionByClaim(reviews: ClaimReview[]): Map<string, ClaimReview> {\n const map = new Map<string, ClaimReview>();\n for (const r of reviews) {\n const existing = map.get(r.claim_id);\n if (!existing || r.created_at > existing.created_at) {\n map.set(r.claim_id, r);\n }\n }\n return map;\n}\n\nfunction buildEffectiveStatuses(resolutions: ContradictionResolution[]): Map<string, string> {\n const sorted = [...resolutions].sort((a, b) => a.resolved_at.localeCompare(b.resolved_at));\n const map = new Map<string, string>();\n for (const r of sorted) map.set(r.contradiction_id, r.status);\n return map;\n}\n\nfunction buildEffectiveDispositions(\n dispositions: ClaimSynthesisDisposition[],\n decisionByClaim: Map<string, ClaimReview>,\n warnings: string[],\n): Map<string, string> {\n const map = new Map<string, string>();\n if (dispositions.length === 0) return map;\n const sorted = [...dispositions].sort((a, b) => a.created_at.localeCompare(b.created_at));\n for (const d of sorted) {\n const review = decisionByClaim.get(d.claim_id);\n if (review?.decision === 'accepted_for_synthesis') {\n warnings.push(\n `invalid disposition: claim ${d.claim_id} has accepted_for_synthesis review but a disposition entry was found — layer separation violated`,\n );\n continue;\n }\n map.set(d.claim_id, d.status);\n }\n return map;\n}\n\nfunction buildSectionState(args: {\n sectionId: string;\n research: ResearchYaml;\n gate: SectionGateResult | null;\n candidateClaims: Claim[];\n claimReviews: ClaimReview[];\n contradictions: Contradiction[];\n resolutions?: ContradictionResolution[];\n dispositions?: ClaimSynthesisDisposition[];\n warnings: string[];\n}): SectionState {\n const { sectionId, research, gate, candidateClaims, claimReviews, contradictions, resolutions = [], dispositions = [], warnings } = args;\n const sectionMeta = research.sections.find((s) => s.id === sectionId);\n const purpose = sectionMeta?.purpose ?? '';\n const status = sectionMeta?.status ?? 'unknown';\n\n const decisionByClaim = latestDecisionByClaim(claimReviews);\n const effectiveDispositions = buildEffectiveDispositions(dispositions, decisionByClaim, warnings);\n\n const accepted: string[] = [];\n const repair: string[] = [];\n const rejected: string[] = [];\n const dispositioned: string[] = [];\n for (const c of candidateClaims) {\n const d = decisionByClaim.get(c.claim_id);\n if (!d) continue;\n if (d.decision === 'accepted_for_synthesis') {\n accepted.push(c.claim_id);\n } else if (d.decision === 'rejected') {\n rejected.push(c.claim_id);\n } else if (effectiveDispositions.has(c.claim_id)) {\n dispositioned.push(c.claim_id);\n } else {\n repair.push(c.claim_id);\n }\n }\n\n const effectiveStatuses = buildEffectiveStatuses(resolutions);\n const unresolved = contradictions.filter((c) => {\n const effective = effectiveStatuses.get(c.contradiction_id);\n return effective !== undefined ? effective === 'unresolved' : c.status === 'unresolved';\n });\n const blocking = unresolved.filter(\n (c) => c.severity === 'high' || c.severity === 'blocking',\n );\n\n const reviewedClaimIds = new Set(decisionByClaim.keys());\n const triageParkedCount = candidateClaims.filter((c) => !reviewedClaimIds.has(c.claim_id)).length;\n\n const dispositionedBreakdown = {\n parked_not_for_synthesis: 0,\n preserved_for_human_note: 0,\n needs_human_review_excluded: 0,\n out_of_bounds_regression_fixture: 0,\n };\n for (const cid of dispositioned) {\n const s = effectiveDispositions.get(cid);\n if (s === 'parked_not_for_synthesis') dispositionedBreakdown.parked_not_for_synthesis++;\n else if (s === 'preserved_for_human_note') dispositionedBreakdown.preserved_for_human_note++;\n else if (s === 'needs_human_review_excluded') dispositionedBreakdown.needs_human_review_excluded++;\n else if (s === 'out_of_bounds_regression_fixture') dispositionedBreakdown.out_of_bounds_regression_fixture++;\n }\n\n const overrideAcceptedCount = Array.from(decisionByClaim.values()).filter(\n (r) => r.decision === 'accepted_for_synthesis' && r.review_method.includes('operator_override'),\n ).length;\n\n const waiversActive = gate?.waivers_applied.map((w) => `${w.family}:${w.check}`) ?? [];\n\n const provenanceSummary: ProvenanceSummary = {\n accepted_count: accepted.length,\n rejected_count: rejected.length,\n triage_parked_count: triageParkedCount,\n needs_review_undispositioned_count: repair.length,\n dispositioned_count: dispositioned.length,\n dispositioned_breakdown: dispositionedBreakdown,\n active_repair_blockers: repair.length,\n active_unresolved_contradictions: unresolved.length,\n waivers_active: waiversActive,\n overrides_applied_count: overrideAcceptedCount,\n };\n\n return {\n section_id: sectionId,\n purpose,\n status,\n has_gate_run: !!gate,\n has_review_run: claimReviews.length > 0,\n gate_verdict: gate?.verdict ?? null,\n synthesis_eligible: gate?.synthesis_eligible ?? false,\n accepted_claim_ids: accepted,\n repair_claim_ids: repair,\n rejected_claim_ids: rejected,\n dispositioned_claim_ids: dispositioned,\n candidate_claims_total: candidateClaims.length,\n unresolved_contradiction_ids: unresolved.map((c) => c.contradiction_id),\n blocking_reasons: gate?.blocking_reasons ?? [],\n active_blockers: gate?.blocking_reasons ?? [],\n blocking_contradictions_unresolved: blocking.length,\n provenance_summary: provenanceSummary,\n };\n}\n\nfunction collectWaivers(\n research: ResearchYaml,\n perSection: DeriveInput['perSection'],\n): WaiverEntry[] {\n const waivers: WaiverEntry[] = [];\n const w = research.primary_source_waiver;\n if (w.status === 'granted') {\n waivers.push({\n scope: 'pack',\n family: 'source_floor',\n reason: w.reason ?? '',\n compensating_controls: w.compensating_controls ?? [],\n applied_to: 'primary_sources_required',\n });\n }\n for (const [sid, data] of perSection) {\n const gate = data.gate;\n if (!gate) continue;\n for (const wa of gate.waivers_applied) {\n waivers.push({\n scope: 'gate',\n family: wa.family,\n reason: wa.reason,\n compensating_controls: wa.compensating_controls,\n applied_to: `${sid}.${wa.check}`,\n });\n }\n }\n return waivers;\n}\n\nfunction determineMode(\n sections: SectionState[],\n waivers: WaiverEntry[],\n warnings: string[],\n): HandoffMode {\n const hasMalformed = warnings.some((w) => /malformed|invalid|parse/i.test(w));\n const invalidWaivers = waivers.some(\n (w) => w.reason.trim().length === 0 || w.compensating_controls.length === 0,\n );\n const blockingContradictions = sections.some(\n (s) => s.blocking_contradictions_unresolved > 0,\n );\n\n if (hasMalformed || invalidWaivers || blockingContradictions) {\n return 'human_review_required';\n }\n\n const allReady = sections.every(\n (s) =>\n s.has_gate_run &&\n s.synthesis_eligible &&\n s.has_review_run &&\n s.candidate_claims_total > 0 &&\n s.active_blockers.length === 0 &&\n s.unresolved_contradiction_ids.length === 0,\n );\n\n if (allReady && sections.length > 0) return 'synthesis_ready';\n return 'repair_required';\n}\n\nfunction buildRecommendedNextActions(\n sections: SectionState[],\n mode: HandoffMode,\n): string[] {\n const actions: string[] = [];\n if (mode === 'synthesis_ready') {\n actions.push('Run `research-os query \"<term>\"` to navigate the indexed evidence base before drafting synthesis.');\n actions.push('Draft `synthesis/cross-section-map.md` listing how accepted claims relate across sections (no new facts).');\n actions.push('Draft `synthesis/decision-brief.md` for the pack\\'s `decision` field, citing only accepted_claim_ids.');\n actions.push('When done, suggest the user run `research-os index build --all` and `research-os cowork handoff` to refresh the runtime contract.');\n return actions;\n }\n if (mode === 'human_review_required') {\n actions.push('Stop and surface the human-review-required reasons to the operator.');\n actions.push('Prepare options in `handoffs/cowork-options.md` — do not decide.');\n return actions;\n }\n // repair_required\n for (const s of sections) {\n if (!s.has_gate_run) {\n actions.push(`Run \\`research-os gate ${s.section_id}\\` (no gate result on file yet).`);\n continue;\n }\n if (!s.synthesis_eligible) {\n for (const r of s.blocking_reasons) {\n actions.push(`[${s.section_id}] address blocking gate failure: ${r}`);\n }\n if (s.blocking_reasons.length === 0) {\n actions.push(`[${s.section_id}] gate verdict ${s.gate_verdict ?? 'unknown'} but synthesis is not eligible — re-run \\`research-os gate ${s.section_id}\\` and review the audits.`);\n }\n }\n if (!s.has_review_run && s.candidate_claims_total > 0) {\n actions.push(`Run \\`research-os review ${s.section_id}\\` (no review on file yet).`);\n }\n if (s.repair_claim_ids.length > 0) {\n actions.push(`[${s.section_id}] ${s.repair_claim_ids.length} claim(s) need repair per latest review — re-run gather/extract for affected sources, then re-run review.`);\n }\n if (s.unresolved_contradiction_ids.length > 0) {\n actions.push(`[${s.section_id}] resolve, preserve, or reject ${s.unresolved_contradiction_ids.length} unresolved contradiction(s).`);\n }\n }\n if (actions.length === 0) {\n actions.push('No specific repair actions identified, but mode=repair_required — re-run `research-os gate --all` and `research-os review --all` to refresh state.');\n }\n return actions;\n}\n\nexport function derive(input: DeriveInput): CoworkHandoffPayload {\n const sections: SectionState[] = [];\n const acceptedAll: string[] = [];\n const repairAll: string[] = [];\n const blockedAll: string[] = [];\n const dispositionedAll: string[] = [];\n const unresolvedContradictionsAll: string[] = [];\n const gateVerdicts: CoworkHandoffPayload['gate_verdicts'] = [];\n const reviewDecisionCounts: ReviewDecisionCount[] = [];\n\n for (const sectionMeta of input.research.sections) {\n const data = input.perSection.get(sectionMeta.id) ?? {\n gate: null,\n candidateClaims: [],\n claimReviews: [],\n contradictions: [],\n };\n const state = buildSectionState({\n sectionId: sectionMeta.id,\n research: input.research,\n gate: data.gate,\n candidateClaims: data.candidateClaims,\n claimReviews: data.claimReviews,\n contradictions: data.contradictions,\n resolutions: data.resolutions,\n dispositions: data.dispositions,\n warnings: input.warnings,\n });\n sections.push(state);\n acceptedAll.push(...state.accepted_claim_ids);\n repairAll.push(...state.repair_claim_ids);\n blockedAll.push(...state.rejected_claim_ids);\n dispositionedAll.push(...state.dispositioned_claim_ids);\n unresolvedContradictionsAll.push(...state.unresolved_contradiction_ids);\n\n if (data.gate) {\n gateVerdicts.push({\n section_id: sectionMeta.id,\n verdict: data.gate.verdict,\n synthesis_eligible: data.gate.synthesis_eligible,\n });\n }\n\n const decisionTally: Record<string, number> = {};\n const latest = latestDecisionByClaim(data.claimReviews);\n for (const r of latest.values()) {\n decisionTally[r.decision] = (decisionTally[r.decision] ?? 0) + 1;\n }\n for (const [decision, count] of Object.entries(decisionTally)) {\n reviewDecisionCounts.push({ section_id: sectionMeta.id, decision, count });\n }\n }\n\n const waivers = collectWaivers(input.research, input.perSection);\n const mode = determineMode(sections, waivers, input.warnings);\n const synthesisAllowed = mode === 'synthesis_ready';\n\n const allowedWritePaths = mode === 'synthesis_ready'\n ? ALLOWED_WRITE_SYNTHESIS\n : mode === 'human_review_required'\n ? ALLOWED_WRITE_BASE\n : ALLOWED_WRITE_REPAIR;\n\n const summary = (() => {\n const ready = sections.filter((s) => s.synthesis_eligible).length;\n const blocked = sections.length - ready;\n return `Pack mode=${mode}; ${sections.length} section(s) total, ${ready} synthesis-eligible, ${blocked} blocked or unrun. ${acceptedAll.length} accepted claim(s); ${repairAll.length} need repair; ${dispositionedAll.length} dispositioned; ${blockedAll.length} rejected; ${unresolvedContradictionsAll.length} unresolved contradiction(s); ${waivers.length} waiver(s).`;\n })();\n\n return {\n pack_id: packId(input.research),\n pack_topic: input.research.topic,\n generated_at: input.generatedAt,\n mode,\n synthesis_allowed: synthesisAllowed,\n summary,\n sections,\n accepted_claim_ids: acceptedAll,\n repair_claim_ids: repairAll,\n blocked_claim_ids: blockedAll,\n dispositioned_claim_ids: dispositionedAll,\n unresolved_contradiction_ids: unresolvedContradictionsAll,\n waivers,\n gate_verdicts: gateVerdicts,\n review_decisions: reviewDecisionCounts,\n recommended_next_actions: buildRecommendedNextActions(sections, mode),\n allowed_write_paths: allowedWritePaths,\n forbidden_actions: FORBIDDEN_ACTIONS_ALWAYS,\n index_status: input.indexStatus,\n warnings: input.warnings,\n };\n}\n","import { z } from 'zod';\n\nexport const HandoffModeSchema = z.enum([\n 'repair_required',\n 'synthesis_ready',\n 'human_review_required',\n]);\n\nexport const IndexStatusSchema = z.enum(['present', 'missing']);\n\nexport const ProvenanceSummarySchema = z.object({\n accepted_count: z.number().int().nonnegative(),\n rejected_count: z.number().int().nonnegative(),\n triage_parked_count: z.number().int().nonnegative(),\n needs_review_undispositioned_count: z.number().int().nonnegative(),\n dispositioned_count: z.number().int().nonnegative(),\n dispositioned_breakdown: z.object({\n parked_not_for_synthesis: z.number().int().nonnegative(),\n preserved_for_human_note: z.number().int().nonnegative(),\n needs_human_review_excluded: z.number().int().nonnegative(),\n out_of_bounds_regression_fixture: z.number().int().nonnegative(),\n }),\n active_repair_blockers: z.number().int().nonnegative(),\n active_unresolved_contradictions: z.number().int().nonnegative(),\n waivers_active: z.array(z.string()),\n overrides_applied_count: z.number().int().nonnegative(),\n});\n\nexport const SectionStateSchema = z.object({\n section_id: z.string().regex(/^[0-9]{2}-[a-z0-9-]+$/),\n purpose: z.string(),\n status: z.string(),\n has_gate_run: z.boolean(),\n has_review_run: z.boolean(),\n gate_verdict: z.string().nullable(),\n synthesis_eligible: z.boolean(),\n accepted_claim_ids: z.array(z.string()),\n repair_claim_ids: z.array(z.string()),\n rejected_claim_ids: z.array(z.string()),\n dispositioned_claim_ids: z.array(z.string()).default([]),\n candidate_claims_total: z.number().int().nonnegative(),\n unresolved_contradiction_ids: z.array(z.string()),\n blocking_reasons: z.array(z.string()),\n active_blockers: z.array(z.string()).default([]),\n blocking_contradictions_unresolved: z.number().int().nonnegative(),\n provenance_summary: ProvenanceSummarySchema.optional(),\n});\n\nexport const WaiverEntrySchema = z.object({\n scope: z.enum(['pack', 'gate']),\n family: z.string(),\n reason: z.string(),\n compensating_controls: z.array(z.string()),\n applied_to: z.string(),\n});\n\nexport const GateVerdictEntrySchema = z.object({\n section_id: z.string(),\n verdict: z.string(),\n synthesis_eligible: z.boolean(),\n});\n\nexport const ReviewDecisionCountSchema = z.object({\n section_id: z.string(),\n decision: z.string(),\n count: z.number().int().nonnegative(),\n});\n\nexport const CoworkHandoffPayloadSchema = z.object({\n pack_id: z.string(),\n pack_topic: z.string(),\n generated_at: z.string(),\n mode: HandoffModeSchema,\n synthesis_allowed: z.boolean(),\n summary: z.string(),\n sections: z.array(SectionStateSchema),\n accepted_claim_ids: z.array(z.string()),\n repair_claim_ids: z.array(z.string()),\n blocked_claim_ids: z.array(z.string()),\n dispositioned_claim_ids: z.array(z.string()).default([]),\n unresolved_contradiction_ids: z.array(z.string()),\n waivers: z.array(WaiverEntrySchema),\n gate_verdicts: z.array(GateVerdictEntrySchema),\n review_decisions: z.array(ReviewDecisionCountSchema),\n recommended_next_actions: z.array(z.string()),\n allowed_write_paths: z.array(z.string()),\n forbidden_actions: z.array(z.string()),\n index_status: IndexStatusSchema,\n warnings: z.array(z.string()),\n});\n\nexport type CoworkHandoffPayload = z.infer<typeof CoworkHandoffPayloadSchema>;\n","import type { CoworkHandoffPayload, HandoffMode } from './types.js';\n\nconst MODE_GLYPH: Record<HandoffMode, string> = {\n repair_required: '[REPAIR REQUIRED]',\n synthesis_ready: '[SYNTHESIS READY]',\n human_review_required: '[HUMAN REVIEW REQUIRED]',\n};\n\nconst MODE_NARRATIVE: Record<HandoffMode, string> = {\n repair_required:\n 'The pack is not ready for synthesis. At least one section is blocked, has unrun gates/review, or has claims that need repair. Your job is to gather more sources, repair scope/source issues, re-run gates and review, and document open questions. **You may not write final synthesis prose in this mode.**',\n synthesis_ready:\n 'Required sections are synthesis-eligible, accepted claims exist, no unwaived blocking contradictions remain. You may perform cross-section synthesis using accepted claim_ids only. You may not introduce new facts or cite outside the source ledger.',\n human_review_required:\n 'The pack contains unresolved waivers, blocking contradictions, malformed artifacts, or ambiguous review states. Stop. Prepare options for the operator in `handoffs/cowork-options.md`. **You may not decide on these issues yourself.**',\n};\n\nconst MODE_ALLOWED: Record<HandoffMode, string[]> = {\n repair_required: [\n 'Run `research-os gather <section> --url ...` to add sources where the source-floor gate is failing.',\n 'Run `research-os claim extract <section>` after adding sources.',\n 'Run `research-os contradict map <section>` and `research-os review <section>` to refresh tension and review state.',\n 'Re-run `research-os gate <section>` to determine if synthesis-eligibility has been earned.',\n 'Re-run `research-os index build --all` and `research-os cowork handoff` to refresh the runtime contract.',\n 'Write working notes to `handoffs/cowork-notes.md` and per-section `open_questions.md`.',\n ],\n synthesis_ready: [\n 'Reason across sections to draft `synthesis/cross-section-map.md`.',\n 'Produce `synthesis/decision-brief.md` answering the pack\\'s `decision` field, citing only accepted_claim_ids.',\n 'Draft `synthesis/final-report.md` if (and only if) the decision brief is honest about unresolved tensions.',\n 'Use `research-os query \"<term>\"` to retrieve grounded artifacts; never paraphrase past the indexed evidence.',\n ],\n human_review_required: [\n 'Read the pack state below.',\n 'Surface the unresolved issues to the operator in `handoffs/cowork-options.md` with proposed options, no decisions.',\n 'Stop after the options document is written.',\n ],\n};\n\nexport function renderCoworkMaster(payload: CoworkHandoffPayload): string {\n const lines: string[] = [];\n lines.push(`# Cowork Handoff: ${payload.pack_topic}`);\n lines.push('');\n lines.push(`**Pack ID:** \\`${payload.pack_id}\\``);\n lines.push(`**Mode:** ${MODE_GLYPH[payload.mode]} ${payload.mode}`);\n lines.push(`**Synthesis allowed:** ${payload.synthesis_allowed ? 'yes' : 'no'}`);\n lines.push(`**Generated:** ${payload.generated_at}`);\n lines.push(`**Index:** ${payload.index_status}`);\n lines.push('');\n lines.push(`> ${payload.summary}`);\n lines.push('');\n\n lines.push('## Operating mode');\n lines.push('');\n lines.push(MODE_NARRATIVE[payload.mode]);\n lines.push('');\n\n lines.push('## What you may do');\n lines.push('');\n for (const a of MODE_ALLOWED[payload.mode]) lines.push(`- ${a}`);\n lines.push('');\n\n lines.push('## What you may not do (always — these are pack invariants)');\n lines.push('');\n for (const a of payload.forbidden_actions) lines.push(`- ${a}`);\n lines.push('');\n\n lines.push('## Pack state');\n lines.push('');\n if (payload.sections.length === 0) {\n lines.push('No sections in this pack.');\n } else {\n lines.push('| Section | Status | Gate verdict | Synthesis-eligible | Candidate claims | Accepted | Need repair | Rejected | Unresolved contradictions |');\n lines.push('|---|---|---|---|---|---|---|---|---|');\n for (const s of payload.sections) {\n lines.push(\n `| \\`${s.section_id}\\` | ${s.status} | ${s.gate_verdict ?? '—'} | ${s.synthesis_eligible ? 'yes' : 'no'} | ${s.candidate_claims_total} | ${s.accepted_claim_ids.length} | ${s.repair_claim_ids.length} | ${s.rejected_claim_ids.length} | ${s.unresolved_contradiction_ids.length} |`,\n );\n }\n }\n lines.push('');\n\n lines.push('### Accepted claims (synthesis-ready)');\n lines.push('');\n if (payload.accepted_claim_ids.length === 0) {\n lines.push('_No claims have been accepted for synthesis. Synthesis is not allowed in this handoff._');\n } else {\n for (const cid of payload.accepted_claim_ids) lines.push(`- \\`${cid}\\``);\n }\n lines.push('');\n\n lines.push('### Claims needing repair');\n lines.push('');\n if (payload.repair_claim_ids.length === 0) {\n lines.push('_None._');\n } else {\n for (const cid of payload.repair_claim_ids) lines.push(`- \\`${cid}\\``);\n }\n lines.push('');\n\n lines.push('### Rejected claims');\n lines.push('');\n if (payload.blocked_claim_ids.length === 0) {\n lines.push('_None._');\n } else {\n for (const cid of payload.blocked_claim_ids) lines.push(`- \\`${cid}\\``);\n }\n lines.push('');\n\n lines.push('### Unresolved contradictions');\n lines.push('');\n if (payload.unresolved_contradiction_ids.length === 0) {\n lines.push('_None._');\n } else {\n for (const id of payload.unresolved_contradiction_ids) lines.push(`- \\`${id}\\``);\n }\n lines.push('');\n\n lines.push('### Active waivers');\n lines.push('');\n if (payload.waivers.length === 0) {\n lines.push('_None._');\n } else {\n for (const w of payload.waivers) {\n lines.push(`- **${w.scope}.${w.family}** applied to \\`${w.applied_to}\\``);\n lines.push(` - Reason: ${w.reason || '_(empty — INVALID)_'}`);\n if (w.compensating_controls.length === 0) {\n lines.push(` - Compensating controls: _(none — INVALID)_`);\n } else {\n for (const c of w.compensating_controls) lines.push(` - Compensating: ${c}`);\n }\n }\n }\n lines.push('');\n\n lines.push('## Recommended next actions');\n lines.push('');\n if (payload.recommended_next_actions.length === 0) {\n lines.push('_(none recommended)_');\n } else {\n let i = 1;\n for (const a of payload.recommended_next_actions) {\n lines.push(`${i}. ${a}`);\n i += 1;\n }\n }\n lines.push('');\n\n lines.push('## Allowed write paths');\n lines.push('');\n for (const p of payload.allowed_write_paths) lines.push(`- \\`${p}\\``);\n lines.push('');\n\n lines.push('## Useful index queries');\n lines.push('');\n lines.push('- `research-os query \"source_floor\"` — surface gate failures grounded in audit JSON.');\n lines.push('- `research-os query \"source_cluster_monopoly\"` — find publisher-monopoly findings and the claims they touch.');\n lines.push('- `research-os query \"candidate\" --type claim` — list candidate claims that haven\\'t been accepted yet.');\n lines.push('- `research-os query \"blocked\" --type gate_result` — every gate that blocks synthesis.');\n lines.push('- `research-os query \"<term>\"` — full-text search; every hit points to a canonical artifact path.');\n lines.push('');\n\n lines.push('## Stop conditions');\n lines.push('');\n if (payload.mode === 'synthesis_ready') {\n lines.push('- Final synthesis artifacts written to `synthesis/`.');\n } else if (payload.mode === 'human_review_required') {\n lines.push('- `handoffs/cowork-options.md` written with proposed options for operator review.');\n } else {\n lines.push('- All blocked sections become synthesis-eligible OR mode flips to `human_review_required`.');\n lines.push('- Repair budget for the pack is exhausted (re-run handoff to confirm).');\n }\n lines.push('- Pack-level `max_runtime_minutes` (in `research.yaml`) is exhausted — surface partial state honestly.');\n lines.push('');\n\n lines.push('## Final instruction');\n lines.push('');\n lines.push('Do not introduce unsupported claims. Preserve unresolved contradictions. Do not widen scope beyond the source-tagged scope. Cite only `claim_id` and `source_id` values that already exist in this pack. The pack is the source of authority — this handoff is a layout step, not new truth.');\n lines.push('');\n\n if (payload.warnings.length > 0) {\n lines.push('## Warnings (from handoff generation)');\n lines.push('');\n for (const w of payload.warnings) lines.push(`- ${w}`);\n lines.push('');\n }\n\n return lines.join('\\n');\n}\n","import { existsSync } from 'node:fs';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { join, resolve } from 'node:path';\nimport { parse as yamlParse } from 'yaml';\n\nimport { PackNotFoundError } from '../errors.js';\nimport { ResearchYamlSchema, type ResearchYaml } from '../intake/schema.js';\nimport { ClaimSchema, type Claim } from '../claims/schema.js';\nimport { ContradictionSchema, type Contradiction } from '../contradictions/schema.js';\nimport { ContradictionResolutionSchema, type ContradictionResolution } from '../contradictions/resolution-schema.js';\nimport { ClaimSynthesisDispositionSchema, type ClaimSynthesisDisposition } from '../dispositions/schema.js';\nimport { SectionGateResultSchema, type SectionGateResult } from '../gates/schema.js';\nimport { ClaimReviewSchema, type ClaimReview } from '../review/schema.js';\nimport { indexDbPath } from '../indexer/db.js';\n\nimport { derive, type DeriveInput } from './derive.js';\nimport { CoworkHandoffPayloadSchema } from './schema.js';\nimport { renderCoworkMaster } from './markdown.js';\nimport type { HandoffOptions, HandoffSummary } from './types.js';\n\nasync function loadResearchYaml(packPath: string): Promise<ResearchYaml> {\n const yamlPath = join(packPath, 'research.yaml');\n if (!existsSync(yamlPath)) throw new PackNotFoundError(packPath);\n const text = await readFile(yamlPath, 'utf8');\n return ResearchYamlSchema.parse(yamlParse(text));\n}\n\nasync function readJsonl<T>(\n path: string,\n parse: (raw: unknown) => T,\n warnings: string[],\n): Promise<T[]> {\n if (!existsSync(path)) return [];\n const text = await readFile(path, 'utf8');\n const out: T[] = [];\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n out.push(parse(JSON.parse(line)));\n } catch (err) {\n const msg = err instanceof Error ? err.message : 'parse error';\n warnings.push(`malformed line in ${path}: ${msg}`);\n }\n }\n return out;\n}\n\nasync function readGate(\n packPath: string,\n sectionId: string,\n warnings: string[],\n): Promise<SectionGateResult | null> {\n const path = join(packPath, 'audits', `${sectionId}-gate.json`);\n if (!existsSync(path)) return null;\n try {\n const text = await readFile(path, 'utf8');\n return SectionGateResultSchema.parse(JSON.parse(text));\n } catch (err) {\n warnings.push(`malformed gate result at audits/${sectionId}-gate.json: ${err instanceof Error ? err.message : err}`);\n return null;\n }\n}\n\nexport async function handoff(options: HandoffOptions): Promise<HandoffSummary> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n const research = await loadResearchYaml(packPath);\n const warnings: string[] = [];\n\n const perSection: DeriveInput['perSection'] = new Map();\n for (const section of research.sections) {\n const sid = section.id;\n const claims = await readJsonl<Claim>(\n join(packPath, 'sections', sid, 'claims.jsonl'),\n (r) => ClaimSchema.parse(r),\n warnings,\n );\n const candidateClaims = claims.filter((c) => c.review_state === 'candidate');\n const claimReviews = await readJsonl<ClaimReview>(\n join(packPath, 'sections', sid, 'claim-reviews.jsonl'),\n (r) => ClaimReviewSchema.parse(r),\n warnings,\n );\n const contradictions = await readJsonl<Contradiction>(\n join(packPath, 'sections', sid, 'contradictions.jsonl'),\n (r) => ContradictionSchema.parse(r),\n warnings,\n );\n const resolutions = await readJsonl<ContradictionResolution>(\n join(packPath, 'sections', sid, 'contradiction-resolutions.jsonl'),\n (r) => ContradictionResolutionSchema.parse(r),\n warnings,\n );\n const dispositions = await readJsonl<ClaimSynthesisDisposition>(\n join(packPath, 'sections', sid, 'claim-synthesis-dispositions.jsonl'),\n (r) => ClaimSynthesisDispositionSchema.parse(r),\n warnings,\n );\n const gate = await readGate(packPath, sid, warnings);\n perSection.set(sid, { gate, candidateClaims, claimReviews, contradictions, resolutions, dispositions });\n }\n\n const indexExists = existsSync(indexDbPath(packPath));\n if (!indexExists) {\n warnings.push(\n 'Pack-local index missing at .research-os/index.sqlite — Cowork can still operate from canonical artifacts, but `research-os query` will refuse until you run `research-os index build --all`.',\n );\n }\n\n const generatedAt = new Date().toISOString();\n const payload = CoworkHandoffPayloadSchema.parse(\n derive({\n research,\n perSection,\n indexStatus: indexExists ? 'present' : 'missing',\n generatedAt,\n warnings,\n }),\n );\n\n const handoffsDir = join(packPath, 'handoffs');\n await mkdir(handoffsDir, { recursive: true });\n const jsonPath = join(handoffsDir, 'cowork-handoff.json');\n const mdPath = join(handoffsDir, 'cowork-master.md');\n await writeFile(jsonPath, JSON.stringify(payload, null, 2), 'utf8');\n await writeFile(mdPath, renderCoworkMaster(payload), 'utf8');\n\n return {\n packId: payload.pack_id,\n packTopic: payload.pack_topic,\n mode: payload.mode,\n synthesisAllowed: payload.synthesis_allowed,\n jsonPath,\n markdownPath: mdPath,\n warnings,\n acceptedCount: payload.accepted_claim_ids.length,\n repairCount: payload.repair_claim_ids.length,\n blockedCount: payload.blocked_claim_ids.length,\n };\n}\n","export { handoff } from './run.js';\nexport { derive, FORBIDDEN_ACTIONS_ALWAYS } from './derive.js';\nexport { renderCoworkMaster } from './markdown.js';\nexport {\n HandoffModeSchema,\n IndexStatusSchema,\n SectionStateSchema,\n WaiverEntrySchema,\n GateVerdictEntrySchema,\n ReviewDecisionCountSchema,\n CoworkHandoffPayloadSchema,\n} from './schema.js';\nexport type {\n HandoffMode,\n IndexStatus,\n SectionState,\n WaiverEntry,\n GateVerdictEntry,\n ReviewDecisionCount,\n CoworkHandoffPayload,\n HandoffOptions,\n HandoffSummary,\n} from './types.js';\n","import { createHash } from 'node:crypto';\n\nimport type { Claim } from '../claims/schema.js';\nimport type { ClaimReview } from '../review/schema.js';\nimport type { Contradiction } from '../contradictions/schema.js';\nimport type { SourceCard } from '../sources/schema.js';\nimport type { ResearchYaml } from '../intake/schema.js';\nimport type { CoworkHandoffPayload } from '../cowork/schema.js';\nimport { jaccardSimilarity } from '../contradictions/scope.js';\n\nimport type {\n AllowedSynthesisInput,\n ClaimCluster,\n CrossSectionContradictionRef,\n CrossSectionMap,\n ForbiddenInput,\n ScopeOverlap,\n SectionAcceptedSummary,\n SharedSource,\n WaiverDependency,\n} from './types.js';\n\nconst SCOPE_OVERLAP_THRESHOLD = 0.3;\n\nexport interface DeriveMapInput {\n research: ResearchYaml;\n handoff: CoworkHandoffPayload;\n claimsBySection: Map<string, Claim[]>;\n reviewsBySection: Map<string, ClaimReview[]>;\n contradictionsBySection: Map<string, Contradiction[]>;\n sources: SourceCard[];\n generatedAt: string;\n}\n\nfunction latestDecisionByClaim(reviews: ClaimReview[]): Map<string, ClaimReview> {\n const map = new Map<string, ClaimReview>();\n for (const r of reviews) {\n const existing = map.get(r.claim_id);\n if (!existing || r.created_at > existing.created_at) {\n map.set(r.claim_id, r);\n }\n }\n return map;\n}\n\nfunction clusterClaimsBySharedSources(claims: Claim[]): ClaimCluster[] {\n const parent = new Map<string, string>();\n const find = (a: string): string => {\n let root = a;\n while (parent.get(root) && parent.get(root) !== root) {\n root = parent.get(root)!;\n }\n if (!parent.has(root)) parent.set(root, root);\n return root;\n };\n const union = (a: string, b: string): void => {\n const ra = find(a);\n const rb = find(b);\n if (ra !== rb) parent.set(ra, rb);\n };\n\n for (const c of claims) parent.set(c.claim_id, c.claim_id);\n\n for (let i = 0; i < claims.length; i += 1) {\n for (let j = i + 1; j < claims.length; j += 1) {\n const shared = claims[i]!.source_ids.filter((s) => claims[j]!.source_ids.includes(s));\n if (shared.length > 0) union(claims[i]!.claim_id, claims[j]!.claim_id);\n }\n }\n\n const groups = new Map<string, Claim[]>();\n for (const c of claims) {\n const root = find(c.claim_id);\n if (!groups.has(root)) groups.set(root, []);\n groups.get(root)!.push(c);\n }\n\n const clusters: ClaimCluster[] = [];\n for (const [, members] of groups) {\n if (members.length === 0) continue;\n const sharedSet = new Set<string>();\n for (let i = 0; i < members.length; i += 1) {\n for (let j = i + 1; j < members.length; j += 1) {\n for (const sid of members[i]!.source_ids) {\n if (members[j]!.source_ids.includes(sid)) sharedSet.add(sid);\n }\n }\n }\n const memberIds = members.map((m) => m.claim_id).sort();\n const sections = Array.from(new Set(members.map((m) => m.section_id))).sort();\n const clusterId = `cls_${createHash('sha256').update(memberIds.join('|')).digest('hex').slice(0, 12)}`;\n clusters.push({\n cluster_id: clusterId,\n shared_source_ids: Array.from(sharedSet).sort(),\n member_claim_ids: memberIds,\n spans_sections: sections,\n });\n }\n return clusters;\n}\n\nfunction buildSharedSources(\n acceptedClaims: Claim[],\n sources: SourceCard[],\n): SharedSource[] {\n const usage = new Map<string, { claims: Set<string>; sections: Set<string> }>();\n for (const c of acceptedClaims) {\n for (const sid of c.source_ids) {\n if (!usage.has(sid)) {\n usage.set(sid, { claims: new Set(), sections: new Set() });\n }\n usage.get(sid)!.claims.add(c.claim_id);\n usage.get(sid)!.sections.add(c.section_id);\n }\n }\n const out: SharedSource[] = [];\n for (const [sid, { claims: cs, sections: secs }] of usage) {\n if (cs.size < 2 && secs.size < 2) continue;\n const card = sources.find((s) => s.source_id === sid);\n out.push({\n source_id: sid,\n publisher: card?.publisher ?? null,\n source_type: card?.source_type ?? 'unknown',\n used_by_claim_ids: Array.from(cs).sort(),\n spans_sections: Array.from(secs).sort(),\n });\n }\n return out;\n}\n\nfunction buildScopeOverlaps(acceptedClaims: Claim[]): ScopeOverlap[] {\n const out: ScopeOverlap[] = [];\n for (let i = 0; i < acceptedClaims.length; i += 1) {\n for (let j = i + 1; j < acceptedClaims.length; j += 1) {\n const a = acceptedClaims[i]!;\n const b = acceptedClaims[j]!;\n if (a.scope === null || b.scope === null) continue;\n const sim = jaccardSimilarity(a.scope, b.scope);\n if (sim < SCOPE_OVERLAP_THRESHOLD) continue;\n const crossSection = a.section_id !== b.section_id;\n const warning = crossSection\n ? `Cross-section scope overlap (jaccard=${sim.toFixed(2)}). Synthesis must not silently merge these claims; cite each separately and note their scope.`\n : `In-section scope overlap (jaccard=${sim.toFixed(2)}). Synthesis must keep each claim's scope tag intact.`;\n out.push({\n claim_a: a.claim_id,\n claim_b: b.claim_id,\n scope_a: a.scope,\n scope_b: b.scope,\n jaccard: Number(sim.toFixed(4)),\n cross_section: crossSection,\n warning,\n });\n }\n }\n return out;\n}\n\nfunction buildCrossSectionContradictions(\n byClaim: Map<string, string>,\n contradictionsBySection: Map<string, Contradiction[]>,\n): CrossSectionContradictionRef[] {\n const out: CrossSectionContradictionRef[] = [];\n for (const list of contradictionsBySection.values()) {\n for (const c of list) {\n const sections = new Set<string>();\n for (const cid of c.claim_ids) {\n const sec = byClaim.get(cid);\n if (sec) sections.add(sec);\n }\n if (sections.size <= 1) continue;\n out.push({\n contradiction_id: c.contradiction_id,\n claim_ids: c.claim_ids,\n sections: Array.from(sections).sort(),\n type: c.type,\n severity: c.severity,\n status: c.status,\n });\n }\n }\n return out;\n}\n\nfunction buildWaiverDependencies(handoff: CoworkHandoffPayload): WaiverDependency[] {\n return handoff.waivers.map((w) => ({\n scope: w.scope,\n family: w.family,\n reason: w.reason,\n compensating_controls: w.compensating_controls,\n applied_to: w.applied_to,\n must_disclose_in: 'both' as const,\n }));\n}\n\nfunction buildSectionsSummary(\n research: ResearchYaml,\n handoff: CoworkHandoffPayload,\n): SectionAcceptedSummary[] {\n return research.sections.map((s) => {\n const handoffSection = handoff.sections.find((hs) => hs.section_id === s.id);\n const accepted = handoffSection?.accepted_claim_ids ?? [];\n let excludedReason: string | null = null;\n if (handoffSection) {\n if (!handoffSection.synthesis_eligible) {\n excludedReason = `Section gate verdict ${handoffSection.gate_verdict ?? 'unknown'}; synthesis-eligible=false.`;\n } else if (accepted.length === 0) {\n excludedReason = 'No claims accepted for synthesis in this section.';\n }\n } else {\n excludedReason = 'No handoff entry for this section.';\n }\n return {\n section_id: s.id,\n purpose: s.purpose,\n status: s.status,\n accepted_claim_ids: accepted,\n excluded_reason: excludedReason,\n };\n });\n}\n\nexport function deriveCrossSectionMap(input: DeriveMapInput): CrossSectionMap {\n const acceptedSet = new Set(input.handoff.accepted_claim_ids);\n const acceptedClaims: Claim[] = [];\n const claimToSection = new Map<string, string>();\n for (const [sectionId, claims] of input.claimsBySection) {\n for (const c of claims) {\n claimToSection.set(c.claim_id, sectionId);\n if (acceptedSet.has(c.claim_id)) acceptedClaims.push(c);\n }\n }\n\n const claimClusters = clusterClaimsBySharedSources(acceptedClaims);\n const sharedSources = buildSharedSources(acceptedClaims, input.sources);\n const scopeOverlaps = buildScopeOverlaps(acceptedClaims);\n const crossSectionContradictions = buildCrossSectionContradictions(\n claimToSection,\n input.contradictionsBySection,\n );\n\n const allowedInputs: AllowedSynthesisInput[] = acceptedClaims.map((c) => ({\n claim_id: c.claim_id,\n section_id: c.section_id,\n artifact_path: `sections/${c.section_id}/claims.jsonl`,\n asserts: c.asserts,\n scope: c.scope,\n not: c.not,\n source_ids: c.source_ids,\n }));\n\n const forbidden: ForbiddenInput[] = [];\n for (const [sectionId, claims] of input.claimsBySection) {\n const reviews = input.reviewsBySection.get(sectionId) ?? [];\n const latest = latestDecisionByClaim(reviews);\n for (const c of claims) {\n if (acceptedSet.has(c.claim_id)) continue;\n const decision = latest.get(c.claim_id)?.decision ?? 'no_review';\n forbidden.push({\n claim_id: c.claim_id,\n section_id: sectionId,\n decision,\n reason:\n decision === 'rejected'\n ? 'Claim rejected by adversarial review.'\n : decision === 'no_review'\n ? 'Claim has no review decision; cannot be cited in synthesis.'\n : `Claim status is \"${decision}\"; only accepted_for_synthesis claims may enter synthesis.`,\n });\n }\n }\n\n return {\n pack_id: input.handoff.pack_id,\n pack_topic: input.research.topic,\n pack_decision: input.research.decision,\n generated_at: input.generatedAt,\n accepted_claim_ids: input.handoff.accepted_claim_ids,\n sections: buildSectionsSummary(input.research, input.handoff),\n claim_clusters: claimClusters,\n shared_sources: sharedSources,\n scope_overlaps: scopeOverlaps,\n cross_section_contradictions: crossSectionContradictions,\n waiver_dependencies: buildWaiverDependencies(input.handoff),\n open_questions: [],\n allowed_synthesis_inputs: allowedInputs,\n forbidden_inputs: forbidden,\n };\n}\n","import { z } from 'zod';\n\nexport const SectionAcceptedSummarySchema = z.object({\n section_id: z.string().regex(/^[0-9]{2}-[a-z0-9-]+$/),\n purpose: z.string(),\n status: z.string(),\n accepted_claim_ids: z.array(z.string()),\n excluded_reason: z.string().nullable(),\n});\n\nexport const ClaimClusterSchema = z.object({\n cluster_id: z.string(),\n shared_source_ids: z.array(z.string()),\n member_claim_ids: z.array(z.string()).min(1),\n spans_sections: z.array(z.string()),\n});\n\nexport const SharedSourceSchema = z.object({\n source_id: z.string(),\n publisher: z.string().nullable(),\n source_type: z.string(),\n used_by_claim_ids: z.array(z.string()),\n spans_sections: z.array(z.string()),\n});\n\nexport const ScopeOverlapSchema = z.object({\n claim_a: z.string(),\n claim_b: z.string(),\n scope_a: z.string().nullable(),\n scope_b: z.string().nullable(),\n jaccard: z.number().min(0).max(1),\n cross_section: z.boolean(),\n warning: z.string(),\n});\n\nexport const CrossSectionContradictionRefSchema = z.object({\n contradiction_id: z.string(),\n claim_ids: z.array(z.string()),\n sections: z.array(z.string()),\n type: z.string(),\n severity: z.string(),\n status: z.string(),\n});\n\nexport const WaiverDependencySchema = z.object({\n scope: z.enum(['pack', 'gate']),\n family: z.string(),\n reason: z.string(),\n compensating_controls: z.array(z.string()),\n applied_to: z.string(),\n must_disclose_in: z.enum(['decision-brief.md', 'final-report.md', 'both']),\n});\n\nexport const AllowedSynthesisInputSchema = z.object({\n claim_id: z.string(),\n section_id: z.string(),\n artifact_path: z.string(),\n asserts: z.string(),\n scope: z.string().nullable(),\n not: z.string().nullable(),\n source_ids: z.array(z.string()),\n});\n\nexport const ForbiddenInputSchema = z.object({\n claim_id: z.string(),\n section_id: z.string(),\n decision: z.string(),\n reason: z.string(),\n});\n\nexport const CrossSectionMapSchema = z.object({\n pack_id: z.string(),\n pack_topic: z.string(),\n pack_decision: z.string(),\n generated_at: z.string(),\n accepted_claim_ids: z.array(z.string()),\n sections: z.array(SectionAcceptedSummarySchema),\n claim_clusters: z.array(ClaimClusterSchema),\n shared_sources: z.array(SharedSourceSchema),\n scope_overlaps: z.array(ScopeOverlapSchema),\n cross_section_contradictions: z.array(CrossSectionContradictionRefSchema),\n waiver_dependencies: z.array(WaiverDependencySchema),\n open_questions: z.array(z.string()),\n allowed_synthesis_inputs: z.array(AllowedSynthesisInputSchema),\n forbidden_inputs: z.array(ForbiddenInputSchema),\n});\n\nexport type CrossSectionMap = z.infer<typeof CrossSectionMapSchema>;\n","import type { CrossSectionMap } from './types.js';\n\nexport function renderCrossSectionMapMarkdown(map: CrossSectionMap): string {\n const lines: string[] = [];\n lines.push(`# Cross-Section Map: ${map.pack_topic}`);\n lines.push('');\n lines.push(`**Pack ID:** \\`${map.pack_id}\\``);\n lines.push(`**Pack decision:** ${map.pack_decision || '_(no decision recorded in research.yaml)_'}`);\n lines.push(`**Generated:** ${map.generated_at}`);\n lines.push(`**Accepted claims:** ${map.accepted_claim_ids.length}`);\n lines.push('');\n lines.push(\n '> This map points at canonical artifacts. It does not synthesize. It does not infer across claims. Use it as a routing layer when drafting `decision-brief.md` and `working-report.md`. The pack is the source of authority.',\n );\n lines.push('');\n\n lines.push('## Accepted claims by section');\n lines.push('');\n for (const s of map.sections) {\n if (s.accepted_claim_ids.length === 0) {\n lines.push(`### \\`${s.section_id}\\` — excluded`);\n lines.push('');\n lines.push(`- **Purpose:** ${s.purpose}`);\n lines.push(`- **Status:** ${s.status}`);\n lines.push(`- **Excluded reason:** ${s.excluded_reason ?? '_(no reason recorded)_'}`);\n lines.push('');\n } else {\n lines.push(`### \\`${s.section_id}\\` — ${s.accepted_claim_ids.length} accepted claim(s)`);\n lines.push('');\n lines.push(`- **Purpose:** ${s.purpose}`);\n lines.push(`- **Status:** ${s.status}`);\n lines.push('- **Accepted claims:**');\n for (const cid of s.accepted_claim_ids) {\n lines.push(` - \\`${cid}\\``);\n }\n lines.push('');\n }\n }\n\n lines.push('## Shared source relationships');\n lines.push('');\n if (map.shared_sources.length === 0) {\n lines.push('_No sources are shared across multiple accepted claims or sections._');\n } else {\n for (const s of map.shared_sources) {\n lines.push(`- \\`${s.source_id}\\` (publisher: ${s.publisher ?? 'unknown'}, type: ${s.source_type})`);\n lines.push(` - Used by: ${s.used_by_claim_ids.map((c) => `\\`${c}\\``).join(', ')}`);\n lines.push(` - Spans sections: ${s.spans_sections.map((s) => `\\`${s}\\``).join(', ')}`);\n }\n }\n lines.push('');\n\n lines.push('## Claim clusters (shared sources within an accepted set)');\n lines.push('');\n if (map.claim_clusters.length === 0) {\n lines.push('_No clusters detected._');\n } else {\n for (const c of map.claim_clusters) {\n lines.push(`### Cluster \\`${c.cluster_id}\\``);\n lines.push('');\n lines.push(`- **Members:** ${c.member_claim_ids.map((m) => `\\`${m}\\``).join(', ')}`);\n lines.push(`- **Spans sections:** ${c.spans_sections.map((s) => `\\`${s}\\``).join(', ')}`);\n lines.push(`- **Shared source IDs:** ${c.shared_source_ids.length === 0 ? '(singleton)' : c.shared_source_ids.map((s) => `\\`${s}\\``).join(', ')}`);\n lines.push('');\n }\n }\n\n lines.push('## Scope overlap warnings');\n lines.push('');\n if (map.scope_overlaps.length === 0) {\n lines.push('_No scope overlaps above the configured threshold._');\n } else {\n for (const o of map.scope_overlaps) {\n lines.push(`- \\`${o.claim_a}\\` ↔ \\`${o.claim_b}\\` (jaccard ${o.jaccard}, ${o.cross_section ? 'cross-section' : 'in-section'})`);\n lines.push(` - Scope A: ${o.scope_a}`);\n lines.push(` - Scope B: ${o.scope_b}`);\n lines.push(` - Warning: ${o.warning}`);\n }\n }\n lines.push('');\n\n lines.push('## Cross-section contradictions (must be preserved)');\n lines.push('');\n if (map.cross_section_contradictions.length === 0) {\n lines.push('_None recorded._');\n } else {\n for (const c of map.cross_section_contradictions) {\n lines.push(`- \\`${c.contradiction_id}\\` — type: ${c.type}, severity: ${c.severity}, status: ${c.status}`);\n lines.push(` - Claims: ${c.claim_ids.map((id) => `\\`${id}\\``).join(', ')}`);\n lines.push(` - Sections: ${c.sections.map((s) => `\\`${s}\\``).join(', ')}`);\n }\n }\n lines.push('');\n\n lines.push('## Waivers (must be disclosed in any synthesis output)');\n lines.push('');\n if (map.waiver_dependencies.length === 0) {\n lines.push('_None active._');\n } else {\n for (const w of map.waiver_dependencies) {\n lines.push(`- **${w.scope}.${w.family}** applied to \\`${w.applied_to}\\` — disclose in: ${w.must_disclose_in}`);\n lines.push(` - Reason: ${w.reason || '_(empty — INVALID)_'}`);\n if (w.compensating_controls.length === 0) {\n lines.push(' - Compensating controls: _(none — INVALID)_');\n } else {\n for (const cc of w.compensating_controls) lines.push(` - Compensating: ${cc}`);\n }\n }\n }\n lines.push('');\n\n lines.push('## Sections excluded from synthesis');\n lines.push('');\n const excluded = map.sections.filter((s) => s.excluded_reason !== null);\n if (excluded.length === 0) {\n lines.push('_All sections contributed accepted claims._');\n } else {\n for (const s of excluded) {\n lines.push(`- \\`${s.section_id}\\`: ${s.excluded_reason}`);\n }\n }\n lines.push('');\n\n lines.push('## Useful index queries');\n lines.push('');\n lines.push('- `research-os query \"<scope-term>\"` — pull claims by scope tag');\n lines.push('- `research-os query \"<source-id>\" --type claim` — claims that cite a specific source');\n lines.push('- `research-os query \"blocking\" --type gate_result` — re-confirm no blocking gate failures before drafting');\n lines.push('- `research-os query \"unresolved\" --type contradiction` — re-confirm cross-section contradictions are still tracked');\n lines.push('');\n\n lines.push('## Forbidden inputs');\n lines.push('');\n if (map.forbidden_inputs.length === 0) {\n lines.push('_All claims in the pack are accepted for synthesis._');\n } else {\n lines.push('Synthesis must not cite any of the following claims:');\n lines.push('');\n for (const f of map.forbidden_inputs) {\n lines.push(`- \\`${f.claim_id}\\` (\\`${f.section_id}\\`, decision=${f.decision}): ${f.reason}`);\n }\n }\n lines.push('');\n\n return lines.join('\\n');\n}\n\nconst COMMON_GUARDRAILS = [\n '- **Cite only `claim_id` values listed in `synthesis/cross-section-map.json` under `allowed_synthesis_inputs[]`.**',\n '- **Do not introduce facts not present in the cited claims.**',\n '- **Do not flatten unresolved contradictions; preserve them by name.**',\n '- **Do not widen any claim\\'s `scope`; restate it verbatim where the claim is invoked.**',\n '- **Disclose every active waiver from `waiver_dependencies[]`.**',\n '- **Do not cite any claim listed under `forbidden_inputs[]`.**',\n];\n\nexport function renderDecisionBrief(map: CrossSectionMap): string {\n const lines: string[] = [];\n lines.push('# Decision Brief');\n lines.push('');\n lines.push(`**Pack:** ${map.pack_topic}`);\n lines.push(`**Pack ID:** \\`${map.pack_id}\\``);\n lines.push(`**Decision question:** ${map.pack_decision || '_(no decision recorded in research.yaml)_'}`);\n lines.push('');\n lines.push('> **Guardrails (enforced at freeze time):**');\n for (const g of COMMON_GUARDRAILS) lines.push(`> ${g}`);\n lines.push('> - **Recommendation must cite at least one accepted claim_id.**');\n lines.push('');\n lines.push('## Recommendation');\n lines.push('');\n lines.push('_(empty — Cowork or operator writes here. Cite accepted_claim_ids inline as `[claim:clm_...]`.)_');\n lines.push('');\n lines.push('## Evidence cited');\n lines.push('');\n lines.push('_(empty — list the accepted_claim_ids you actually cited above.)_');\n lines.push('');\n lines.push('## Unresolved contradictions preserved');\n lines.push('');\n if (map.cross_section_contradictions.length === 0) {\n lines.push('_None._');\n } else {\n for (const c of map.cross_section_contradictions) {\n lines.push(`- \\`${c.contradiction_id}\\` — ${c.type}, severity ${c.severity}`);\n }\n }\n lines.push('');\n lines.push('## Waivers disclosed');\n lines.push('');\n if (map.waiver_dependencies.length === 0) {\n lines.push('_None active._');\n } else {\n for (const w of map.waiver_dependencies) {\n lines.push(`- **${w.scope}.${w.family}** — ${w.reason}`);\n }\n }\n lines.push('');\n return lines.join('\\n');\n}\n\nexport function renderWorkingReport(map: CrossSectionMap): string {\n const lines: string[] = [];\n lines.push('# Working Report');\n lines.push('');\n lines.push(`**Pack:** ${map.pack_topic}`);\n lines.push(`**Pack ID:** \\`${map.pack_id}\\``);\n lines.push('');\n lines.push('> **Guardrails:**');\n lines.push('> - This is the working synthesis area. Drafts here are not final.');\n for (const g of COMMON_GUARDRAILS) lines.push(`> ${g}`);\n lines.push('> - **Every paragraph must cite at least one accepted_claim_id (inline `[claim:clm_...]`).**');\n lines.push('> - **Unresolved contradictions must remain visible in the prose, not summarized away.**');\n lines.push('');\n lines.push('## Working synthesis');\n lines.push('');\n lines.push('_(empty — Cowork drafts here.)_');\n lines.push('');\n return lines.join('\\n');\n}\n\nexport function renderFinalReport(map: CrossSectionMap): string {\n const lines: string[] = [];\n lines.push('# Final Report');\n lines.push('');\n lines.push(`**Pack:** ${map.pack_topic}`);\n lines.push(`**Pack ID:** \\`${map.pack_id}\\``);\n lines.push(`**Decision question:** ${map.pack_decision || '_(no decision recorded in research.yaml)_'}`);\n lines.push('');\n lines.push('> **Guardrails (locked area):**');\n lines.push('> - This file cannot be considered complete until the freeze step (Link 12) verifies citation coverage and claim-id existence.');\n lines.push('> - Until then, treat this as a draft. Do not promote it externally.');\n for (const g of COMMON_GUARDRAILS) lines.push(`> ${g}`);\n lines.push('');\n lines.push('## Summary');\n lines.push('');\n lines.push('_(empty — Cowork or operator writes here.)_');\n lines.push('');\n lines.push('## Body');\n lines.push('');\n lines.push('_(empty — Cowork or operator writes here.)_');\n lines.push('');\n lines.push('## Limitations and unresolved tensions');\n lines.push('');\n if (map.cross_section_contradictions.length === 0) {\n lines.push('_(empty — Cowork must list anything that the evidence base could not resolve.)_');\n } else {\n for (const c of map.cross_section_contradictions) {\n lines.push(`- \\`${c.contradiction_id}\\` — ${c.type}, severity ${c.severity}, status ${c.status}`);\n }\n }\n lines.push('');\n lines.push('## Waivers disclosed');\n lines.push('');\n if (map.waiver_dependencies.length === 0) {\n lines.push('_None active._');\n } else {\n for (const w of map.waiver_dependencies) {\n lines.push(`- **${w.scope}.${w.family}** applied to \\`${w.applied_to}\\` — ${w.reason}`);\n }\n }\n lines.push('');\n return lines.join('\\n');\n}\n","import { existsSync } from 'node:fs';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { join, resolve } from 'node:path';\nimport { parse as yamlParse } from 'yaml';\n\nimport { HandoffNotFoundError, PackNotFoundError } from '../errors.js';\nimport { ResearchYamlSchema, type ResearchYaml } from '../intake/schema.js';\nimport { ClaimSchema, type Claim } from '../claims/schema.js';\nimport { ClaimReviewSchema, type ClaimReview } from '../review/schema.js';\nimport { ContradictionSchema, type Contradiction } from '../contradictions/schema.js';\nimport { SourceCardSchema, type SourceCard } from '../sources/schema.js';\nimport { CoworkHandoffPayloadSchema, type CoworkHandoffPayload } from '../cowork/schema.js';\n\nimport { deriveCrossSectionMap } from './derive.js';\nimport { CrossSectionMapSchema } from './schema.js';\nimport {\n renderCrossSectionMapMarkdown,\n renderDecisionBrief,\n renderFinalReport,\n renderWorkingReport,\n} from './markdown.js';\nimport type { WorkspaceOptions, WorkspaceSummary } from './types.js';\n\nasync function readJsonl<T>(path: string, parse: (raw: unknown) => T): Promise<T[]> {\n if (!existsSync(path)) return [];\n const text = await readFile(path, 'utf8');\n const out: T[] = [];\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n out.push(parse(JSON.parse(line)));\n }\n return out;\n}\n\nasync function readSourceCards(packPath: string): Promise<SourceCard[]> {\n const dir = join(packPath, 'evidence', 'source-cards');\n if (!existsSync(dir)) return [];\n const { readdir } = await import('node:fs/promises');\n const entries = await readdir(dir);\n const cards: SourceCard[] = [];\n for (const entry of entries) {\n if (!entry.endsWith('.json')) continue;\n const text = await readFile(join(dir, entry), 'utf8');\n cards.push(SourceCardSchema.parse(JSON.parse(text)));\n }\n return cards;\n}\n\nexport async function workspace(options: WorkspaceOptions): Promise<WorkspaceSummary> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n const yamlPath = join(packPath, 'research.yaml');\n if (!existsSync(yamlPath)) throw new PackNotFoundError(packPath);\n const research: ResearchYaml = ResearchYamlSchema.parse(yamlParse(await readFile(yamlPath, 'utf8')));\n\n const handoffPath = join(packPath, 'handoffs', 'cowork-handoff.json');\n if (!existsSync(handoffPath)) throw new HandoffNotFoundError();\n const handoff: CoworkHandoffPayload = CoworkHandoffPayloadSchema.parse(\n JSON.parse(await readFile(handoffPath, 'utf8')),\n );\n\n if (handoff.mode !== 'synthesis_ready') {\n return {\n packPath,\n mode: handoff.mode,\n refused: true,\n refusalReason: `Synthesis workspace refused: pack is in ${handoff.mode} mode. Run 'research-os cowork handoff' for repair instructions.`,\n filesWritten: [],\n acceptedClaims: handoff.accepted_claim_ids.length,\n claimClusters: 0,\n scopeOverlaps: 0,\n crossSectionContradictions: 0,\n };\n }\n\n const claimsBySection = new Map<string, Claim[]>();\n const reviewsBySection = new Map<string, ClaimReview[]>();\n const contradictionsBySection = new Map<string, Contradiction[]>();\n for (const section of research.sections) {\n claimsBySection.set(\n section.id,\n await readJsonl<Claim>(join(packPath, 'sections', section.id, 'claims.jsonl'), (r) =>\n ClaimSchema.parse(r),\n ),\n );\n reviewsBySection.set(\n section.id,\n await readJsonl<ClaimReview>(\n join(packPath, 'sections', section.id, 'claim-reviews.jsonl'),\n (r) => ClaimReviewSchema.parse(r),\n ),\n );\n contradictionsBySection.set(\n section.id,\n await readJsonl<Contradiction>(\n join(packPath, 'sections', section.id, 'contradictions.jsonl'),\n (r) => ContradictionSchema.parse(r),\n ),\n );\n }\n const sources = await readSourceCards(packPath);\n\n const map = CrossSectionMapSchema.parse(\n deriveCrossSectionMap({\n research,\n handoff,\n claimsBySection,\n reviewsBySection,\n contradictionsBySection,\n sources,\n generatedAt: new Date().toISOString(),\n }),\n );\n\n const synthDir = join(packPath, 'synthesis');\n await mkdir(synthDir, { recursive: true });\n\n const filesWritten: string[] = [];\n const writeIfAbsent = async (relPath: string, content: string): Promise<void> => {\n const abs = join(synthDir, relPath);\n if (existsSync(abs)) return;\n await writeFile(abs, content, 'utf8');\n filesWritten.push(abs);\n };\n const writeAlways = async (relPath: string, content: string): Promise<void> => {\n const abs = join(synthDir, relPath);\n await writeFile(abs, content, 'utf8');\n filesWritten.push(abs);\n };\n\n // cross-section-map.* always regenerated (it's derived state)\n await writeAlways('cross-section-map.json', JSON.stringify(map, null, 2));\n await writeAlways('cross-section-map.md', renderCrossSectionMapMarkdown(map));\n\n // Writable workspaces only created if absent — Cowork's drafts are preserved across re-runs\n await writeIfAbsent('decision-brief.md', renderDecisionBrief(map));\n await writeIfAbsent('working-report.md', renderWorkingReport(map));\n await writeIfAbsent('final-report.md', renderFinalReport(map));\n\n return {\n packPath,\n mode: handoff.mode,\n refused: false,\n refusalReason: null,\n filesWritten,\n acceptedClaims: map.accepted_claim_ids.length,\n claimClusters: map.claim_clusters.length,\n scopeOverlaps: map.scope_overlaps.length,\n crossSectionContradictions: map.cross_section_contradictions.length,\n };\n}\n","export { workspace } from './run.js';\nexport { deriveCrossSectionMap } from './derive.js';\nexport {\n renderCrossSectionMapMarkdown,\n renderDecisionBrief,\n renderWorkingReport,\n renderFinalReport,\n} from './markdown.js';\nexport {\n CrossSectionMapSchema,\n SectionAcceptedSummarySchema,\n ClaimClusterSchema,\n SharedSourceSchema,\n ScopeOverlapSchema,\n CrossSectionContradictionRefSchema,\n WaiverDependencySchema,\n AllowedSynthesisInputSchema,\n ForbiddenInputSchema,\n} from './schema.js';\nexport type {\n CrossSectionMap,\n SectionAcceptedSummary,\n ClaimCluster,\n SharedSource,\n ScopeOverlap,\n CrossSectionContradictionRef,\n WaiverDependency,\n AllowedSynthesisInput,\n ForbiddenInput,\n WorkspaceOptions,\n WorkspaceSummary,\n} from './types.js';\n","import type { ResearchYaml } from '../intake/schema.js';\nimport type { Claim } from '../claims/schema.js';\nimport type { ClaimReview, ReviewFinding } from '../review/schema.js';\nimport type { Contradiction } from '../contradictions/schema.js';\nimport type { ContradictionResolution } from '../contradictions/resolution-schema.js';\nimport type { ClaimSynthesisDisposition } from '../dispositions/schema.js';\nimport type { SectionGateResult } from '../gates/schema.js';\nimport type { FetchReceipt, SourceCard } from '../sources/schema.js';\nimport type { CoworkHandoffPayload } from '../cowork/schema.js';\n\nimport type {\n ClaimSummary,\n ContradictionSummary,\n HandoffMode,\n OrphanClaimRow,\n PackAuditPayload,\n PackVerdict,\n ReadinessSummary,\n ReviewSummary,\n ScopeWideningRiskRow,\n SourceDiversityGapRow,\n SourceSummary,\n StaleSourceRow,\n SynthesisReadinessRow,\n UnresolvedContradictionRow,\n WaiverSummary,\n WeakSourceRow,\n} from './types.js';\n\nexport interface AggregateInput {\n research: ResearchYaml;\n perSection: Map<\n string,\n {\n claims: Claim[];\n candidateClaims: Claim[];\n claimReviews: ClaimReview[];\n contradictions: Contradiction[];\n resolutions?: ContradictionResolution[];\n dispositions?: ClaimSynthesisDisposition[];\n gate: SectionGateResult | null;\n findings: ReviewFinding[];\n sourceIdsForSection: string[];\n }\n >;\n sources: SourceCard[];\n receipts: FetchReceipt[];\n handoff: CoworkHandoffPayload | null;\n generatedAt: string;\n warnings: string[];\n}\n\nexport interface AggregateOutput {\n payload: PackAuditPayload;\n orphanClaims: OrphanClaimRow[];\n staleSources: StaleSourceRow[];\n weakSources: WeakSourceRow[];\n unresolvedContradictions: UnresolvedContradictionRow[];\n scopeWideningRisks: ScopeWideningRiskRow[];\n sourceDiversityGaps: SourceDiversityGapRow[];\n}\n\nfunction packId(research: ResearchYaml): string {\n // Stable ID derived from topic + created_at; same logic as cowork derive\n // (kept inline so audit module does not depend on cowork internals).\n const fingerprint = `${research.topic}|${research.created_at}`;\n let hash = 0;\n for (let i = 0; i < fingerprint.length; i += 1) {\n hash = Math.imul(31, hash) + fingerprint.charCodeAt(i);\n hash |= 0;\n }\n return Math.abs(hash).toString(16).padStart(12, '0').slice(-12);\n}\n\nfunction latestDecisionByClaim(reviews: ClaimReview[]): Map<string, ClaimReview> {\n const m = new Map<string, ClaimReview>();\n for (const r of reviews) {\n const existing = m.get(r.claim_id);\n if (!existing || r.created_at > existing.created_at) m.set(r.claim_id, r);\n }\n return m;\n}\n\nfunction buildEffectiveStatuses(resolutions: ContradictionResolution[]): Map<string, string> {\n const map = new Map<string, string>();\n if (resolutions.length === 0) return map;\n const sorted = [...resolutions].sort((a, b) => a.resolved_at.localeCompare(b.resolved_at));\n for (const r of sorted) map.set(r.contradiction_id, r.status);\n return map;\n}\n\nfunction buildEffectiveDispositions(\n dispositions: ClaimSynthesisDisposition[],\n decisionByClaim: Map<string, ClaimReview>,\n warnings: string[],\n): Map<string, string> {\n const map = new Map<string, string>();\n if (dispositions.length === 0) return map;\n const sorted = [...dispositions].sort((a, b) => a.created_at.localeCompare(b.created_at));\n for (const d of sorted) {\n const review = decisionByClaim.get(d.claim_id);\n if (review?.decision === 'accepted_for_synthesis') {\n warnings.push(\n `invalid disposition: claim ${d.claim_id} has accepted_for_synthesis review but a disposition entry was found — layer separation violated`,\n );\n continue;\n }\n map.set(d.claim_id, d.status);\n }\n return map;\n}\n\nfunction buildOrphanClaims(input: AggregateInput): OrphanClaimRow[] {\n const out: OrphanClaimRow[] = [];\n const cardIds = new Set(input.sources.map((c) => c.source_id));\n const okReceiptSourceIds = new Set(\n input.receipts.filter((r) => r.fetch_outcome === 'ok').map((r) => r.source_id),\n );\n\n for (const [sid, data] of input.perSection) {\n const path = `sections/${sid}/claims.jsonl`;\n for (const claim of data.candidateClaims) {\n for (const refSid of claim.source_ids) {\n if (!cardIds.has(refSid)) {\n out.push({\n claim_id: claim.claim_id,\n section_id: sid,\n reason: 'missing_source_card',\n details: `Claim cites source_id ${refSid} but no source card exists at evidence/source-cards/${refSid}.json`,\n artifact_path: path,\n });\n }\n if (!okReceiptSourceIds.has(refSid)) {\n out.push({\n claim_id: claim.claim_id,\n section_id: sid,\n reason: 'unresolvable_source_id',\n details: `Claim cites source_id ${refSid} which has no successful fetch receipt in evidence/fetch-log.jsonl`,\n artifact_path: path,\n });\n }\n }\n if (claim.source_hashes.length === 0) {\n out.push({\n claim_id: claim.claim_id,\n section_id: sid,\n reason: 'missing_source_hash',\n details: 'Claim has empty source_hashes — tamper detection is not anchored to a fetch receipt.',\n artifact_path: path,\n });\n }\n if (claim.evidence_excerpt.trim().length === 0) {\n out.push({\n claim_id: claim.claim_id,\n section_id: sid,\n reason: 'missing_evidence_excerpt',\n details: 'Claim has empty evidence_excerpt.',\n artifact_path: path,\n });\n }\n }\n }\n return out;\n}\n\nfunction buildStaleSources(input: AggregateInput): StaleSourceRow[] {\n const out: StaleSourceRow[] = [];\n const policy = {\n required: input.research.freshness.required,\n max_source_age_months: input.research.freshness.max_source_age_months,\n stale_source_policy: input.research.gates.freshness.stale_source_policy,\n };\n if (!policy.required) return out;\n for (const card of input.sources) {\n const path = `evidence/source-cards/${card.source_id}.json`;\n if (!card.published_at) {\n out.push({\n source_id: card.source_id,\n section_id: card.section_id,\n publisher: card.publisher,\n reason: 'missing_date',\n details: 'Source card has no published_at; freshness cannot be evaluated.',\n artifact_path: path,\n policy,\n });\n continue;\n }\n const d = Date.parse(card.published_at);\n if (Number.isNaN(d)) {\n out.push({\n source_id: card.source_id,\n section_id: card.section_id,\n publisher: card.publisher,\n reason: 'unparseable_date',\n details: `published_at \"${card.published_at}\" is not a valid date.`,\n artifact_path: path,\n policy,\n });\n continue;\n }\n if (policy.max_source_age_months !== null) {\n const ageMonths = (Date.now() - d) / (1000 * 60 * 60 * 24 * 30.44);\n if (ageMonths > policy.max_source_age_months) {\n out.push({\n source_id: card.source_id,\n section_id: card.section_id,\n publisher: card.publisher,\n reason: 'too_old',\n details: `Source is ~${ageMonths.toFixed(1)} months old; pack policy max=${policy.max_source_age_months}. stale_source_policy=${policy.stale_source_policy}.`,\n artifact_path: path,\n policy,\n });\n }\n }\n }\n return out;\n}\n\nfunction buildWeakSources(input: AggregateInput): WeakSourceRow[] {\n const out: WeakSourceRow[] = [];\n const cfg = input.research.gates.source_floor;\n for (const [sid, data] of input.perSection) {\n const sectionSources = input.sources.filter((c) => data.sourceIdsForSection.includes(c.source_id));\n if (sectionSources.length === 0) continue;\n const publishers = new Set(\n sectionSources.map((c) => c.publisher).filter((p): p is string => typeof p === 'string'),\n );\n if (publishers.size === 1 && sectionSources.length >= 2) {\n out.push({\n reason: 'source_cluster_monopoly',\n section_id: sid,\n details: `Every source in this section traces to a single publisher (${[...publishers][0]}).`,\n evidence_ids: sectionSources.map((s) => s.source_id),\n artifact_path: `sections/${sid}/sources.jsonl`,\n });\n }\n if (publishers.size < cfg.min_independent_publishers) {\n out.push({\n reason: 'low_independent_publishers',\n section_id: sid,\n details: `${publishers.size} independent publisher(s) — pack policy requires at least ${cfg.min_independent_publishers}.`,\n evidence_ids: [...publishers],\n artifact_path: `sections/${sid}/sources.jsonl`,\n });\n }\n const primary = sectionSources.filter((c) => c.source_type === 'primary').length;\n if (primary < cfg.primary_sources_required) {\n out.push({\n reason: 'missing_primary_source',\n section_id: sid,\n details: `${primary} primary source(s) — pack policy requires at least ${cfg.primary_sources_required}.`,\n evidence_ids: sectionSources.filter((c) => c.source_type === 'primary').map((c) => c.source_id),\n artifact_path: `sections/${sid}/sources.jsonl`,\n });\n }\n const types = new Map<string, number>();\n for (const c of sectionSources) types.set(c.source_type, (types.get(c.source_type) ?? 0) + 1);\n let dominantType: string | null = null;\n let dominantCount = 0;\n for (const [t, n] of types) if (n > dominantCount) { dominantType = t; dominantCount = n; }\n if (dominantType && sectionSources.length >= 4 && dominantCount / sectionSources.length > 0.8) {\n out.push({\n reason: 'excessive_type_imbalance',\n section_id: sid,\n details: `${dominantCount}/${sectionSources.length} (${Math.round((100 * dominantCount) / sectionSources.length)}%) of sources are type=${dominantType}.`,\n evidence_ids: sectionSources.filter((s) => s.source_type === dominantType).map((s) => s.source_id),\n artifact_path: `sections/${sid}/sources.jsonl`,\n });\n }\n const failedReceipts = input.receipts.filter(\n (r) => r.section_id === sid && r.fetch_outcome !== 'ok',\n );\n if (failedReceipts.length > 0 && sectionSources.length < cfg.min_sources) {\n out.push({\n reason: 'failed_fetches_reducing_floor',\n section_id: sid,\n details: `${failedReceipts.length} failed fetch(es) recorded; section currently has ${sectionSources.length} source(s) vs minimum ${cfg.min_sources}.`,\n evidence_ids: failedReceipts.map((r) => r.receipt_id),\n artifact_path: `evidence/fetch-log.jsonl`,\n });\n }\n }\n return out;\n}\n\nfunction buildUnresolvedContradictions(input: AggregateInput): UnresolvedContradictionRow[] {\n const out: UnresolvedContradictionRow[] = [];\n for (const [sid, data] of input.perSection) {\n const effectiveStatuses = buildEffectiveStatuses(data.resolutions ?? []);\n for (const c of data.contradictions) {\n const eff = effectiveStatuses.get(c.contradiction_id);\n const isUnresolved = eff !== undefined ? eff === 'unresolved' : c.status === 'unresolved';\n if (!isUnresolved) continue;\n out.push({\n contradiction_id: c.contradiction_id,\n section_id: sid,\n type: c.type,\n severity: c.severity,\n status: c.status,\n claim_ids: c.claim_ids,\n artifact_path: `sections/${sid}/contradictions.jsonl`,\n });\n }\n }\n return out;\n}\n\nfunction buildScopeWideningRisks(input: AggregateInput): ScopeWideningRiskRow[] {\n const out: ScopeWideningRiskRow[] = [];\n for (const [sid, data] of input.perSection) {\n for (const f of data.findings) {\n if (f.category === 'overgeneralized_claim' || f.category === 'scope_widening') {\n for (const cid of f.claim_ids) {\n out.push({\n reason: 'overgeneralization_finding',\n claim_id: cid,\n section_id: sid,\n details: `${f.category} (${f.severity}): ${f.summary}`,\n artifact_path: `audits/${sid}-findings.jsonl`,\n });\n }\n }\n if (f.category === 'missing_not_constraint') {\n for (const cid of f.claim_ids) {\n out.push({\n reason: 'missing_not_flagged',\n claim_id: cid,\n section_id: sid,\n details: f.summary,\n artifact_path: `audits/${sid}-findings.jsonl`,\n });\n }\n }\n }\n for (const claim of data.candidateClaims) {\n if (claim.scope === null && claim.asserts.length > 40) {\n out.push({\n reason: 'scope_null_in_use',\n claim_id: claim.claim_id,\n section_id: sid,\n details: 'Candidate claim has scope=null with substantive assertion — synthesis must not treat it as broad.',\n artifact_path: `sections/${sid}/claims.jsonl`,\n });\n }\n }\n }\n return out;\n}\n\nfunction buildSourceDiversityGaps(input: AggregateInput): SourceDiversityGapRow[] {\n const out: SourceDiversityGapRow[] = [];\n const cfg = input.research.gates.source_floor;\n const allPublishersBySection = new Map<string, Set<string>>();\n for (const [sid, data] of input.perSection) {\n const sectionSources = input.sources.filter((c) => data.sourceIdsForSection.includes(c.source_id));\n const publishers = new Set(\n sectionSources.map((c) => c.publisher).filter((p): p is string => typeof p === 'string'),\n );\n allPublishersBySection.set(sid, publishers);\n if (sectionSources.length === 0) {\n out.push({\n reason: 'section_has_no_sources',\n section_id: sid,\n details: 'Section has no source cards on file.',\n evidence_ids: [],\n });\n continue;\n }\n if (publishers.size === 1 && sectionSources.length >= 2) {\n out.push({\n reason: 'section_publisher_monopoly',\n section_id: sid,\n details: `Section sources monopolized by ${[...publishers][0]}.`,\n evidence_ids: sectionSources.map((s) => s.source_id),\n });\n } else if (publishers.size < cfg.min_independent_publishers) {\n out.push({\n reason: 'low_section_publisher_count',\n section_id: sid,\n details: `${publishers.size} publisher(s); pack policy requires ${cfg.min_independent_publishers}.`,\n evidence_ids: [...publishers],\n });\n }\n }\n // cross-section overlap: a publisher dominating across multiple sections\n const pubSectionCount = new Map<string, Set<string>>();\n for (const [sid, pubs] of allPublishersBySection) {\n for (const p of pubs) {\n if (!pubSectionCount.has(p)) pubSectionCount.set(p, new Set());\n pubSectionCount.get(p)!.add(sid);\n }\n }\n for (const [pub, sects] of pubSectionCount) {\n if (sects.size >= 3 && allPublishersBySection.size >= 4) {\n out.push({\n reason: 'cross_section_publisher_overlap',\n section_id: '*',\n details: `Publisher \"${pub}\" appears in ${sects.size} sections; cross-section diversity is reduced.`,\n evidence_ids: [...sects],\n });\n }\n }\n return out;\n}\n\nfunction buildSectionReadiness(input: AggregateInput, warnings: string[]): SynthesisReadinessRow[] {\n const handoffMode: HandoffMode =\n (input.handoff?.mode as HandoffMode | undefined) ?? 'unknown';\n const workspaceAllowed = input.handoff?.synthesis_allowed ?? false;\n return input.research.sections.map((s) => {\n const data = input.perSection.get(s.id);\n const decisionByClaim = data ? latestDecisionByClaim(data.claimReviews) : new Map();\n const effectiveDispositions = buildEffectiveDispositions(\n data?.dispositions ?? [],\n decisionByClaim,\n warnings,\n );\n let accepted = 0;\n let repair = 0;\n let rejected = 0;\n let dispositioned = 0;\n if (data) {\n for (const c of data.candidateClaims) {\n const d = decisionByClaim.get(c.claim_id);\n if (!d) continue;\n if (d.decision === 'accepted_for_synthesis') {\n accepted += 1;\n } else if (d.decision === 'rejected') {\n rejected += 1;\n } else if (effectiveDispositions.has(c.claim_id)) {\n dispositioned += 1;\n } else {\n repair += 1;\n }\n }\n }\n return {\n section_id: s.id,\n purpose: s.purpose,\n status: s.status,\n has_gate_run: !!data?.gate,\n has_review_run: (data?.claimReviews.length ?? 0) > 0,\n gate_verdict: data?.gate?.verdict ?? null,\n synthesis_eligible: data?.gate?.synthesis_eligible ?? false,\n candidate_claims: data?.candidateClaims.length ?? 0,\n accepted_claims: accepted,\n repair_claims: repair,\n rejected_claims: rejected,\n dispositioned_claims: dispositioned,\n blocking_reasons: data?.gate?.blocking_reasons ?? [],\n cowork_handoff_mode: handoffMode,\n workspace_allowed: workspaceAllowed,\n };\n });\n}\n\nfunction buildClaimSummary(input: AggregateInput, orphans: OrphanClaimRow[], warnings: string[]): ClaimSummary {\n let total = 0;\n let candidate = 0;\n let accepted = 0;\n let rejected = 0;\n let repair = 0;\n let dispositioned = 0;\n let noReview = 0;\n let withEvidence = 0;\n let withSourceHashes = 0;\n let scopeNull = 0;\n let notNull = 0;\n for (const data of input.perSection.values()) {\n total += data.claims.length;\n candidate += data.candidateClaims.length;\n const decisionByClaim = latestDecisionByClaim(data.claimReviews);\n const effectiveDispositions = buildEffectiveDispositions(\n data.dispositions ?? [],\n decisionByClaim,\n warnings,\n );\n for (const c of data.candidateClaims) {\n if (c.evidence_excerpt.trim().length > 0) withEvidence += 1;\n if (c.source_hashes.length > 0) withSourceHashes += 1;\n if (c.scope === null) scopeNull += 1;\n if (c.not !== null) notNull += 1;\n const d = decisionByClaim.get(c.claim_id);\n if (!d) noReview += 1;\n else if (d.decision === 'accepted_for_synthesis') accepted += 1;\n else if (d.decision === 'rejected') rejected += 1;\n else if (effectiveDispositions.has(c.claim_id)) dispositioned += 1;\n else repair += 1;\n }\n }\n const orphanIds = new Set(orphans.map((o) => o.claim_id));\n return {\n total,\n candidate,\n accepted_for_synthesis: accepted,\n rejected,\n needs_repair: repair,\n dispositioned,\n no_review: noReview,\n with_evidence_excerpt: withEvidence,\n with_source_hashes: withSourceHashes,\n scope_null: scopeNull,\n not_null: notNull,\n orphans: orphanIds.size,\n };\n}\n\nfunction buildSourceSummary(input: AggregateInput): SourceSummary {\n const cards = input.sources;\n const failed = input.receipts.filter((r) => r.fetch_outcome !== 'ok').length;\n const publishers = new Set(\n cards.map((c) => c.publisher).filter((p): p is string => typeof p === 'string'),\n );\n let withSources = 0;\n let withoutSources = 0;\n for (const data of input.perSection.values()) {\n if (data.sourceIdsForSection.length > 0) withSources += 1;\n else withoutSources += 1;\n }\n return {\n total: cards.length,\n primary: cards.filter((c) => c.source_type === 'primary').length,\n secondary: cards.filter((c) => c.source_type === 'secondary').length,\n forum: cards.filter((c) => c.source_type === 'forum').length,\n benchmark: cards.filter((c) => c.source_type === 'benchmark').length,\n docs: cards.filter((c) => c.source_type === 'docs').length,\n unknown: cards.filter((c) => c.source_type === 'unknown').length,\n independent_publishers: publishers.size,\n failed_fetches: failed,\n sections_with_sources: withSources,\n sections_without_sources: withoutSources,\n };\n}\n\nfunction buildContradictionSummary(input: AggregateInput): ContradictionSummary {\n const all: Contradiction[] = [];\n let cleanLedgers = 0;\n const effectiveUnresolved: Contradiction[] = [];\n for (const [, data] of input.perSection) {\n all.push(...data.contradictions);\n if (data.contradictions.length === 0) cleanLedgers += 1;\n const effectiveStatuses = buildEffectiveStatuses(data.resolutions ?? []);\n for (const c of data.contradictions) {\n const eff = effectiveStatuses.get(c.contradiction_id);\n if (eff !== undefined ? eff === 'unresolved' : c.status === 'unresolved') {\n effectiveUnresolved.push(c);\n }\n }\n }\n const unresolved = effectiveUnresolved;\n const blocking = unresolved.filter(\n (c) => c.severity === 'high' || c.severity === 'blocking',\n );\n const byType: Record<string, number> = {};\n for (const c of all) byType[c.type] = (byType[c.type] ?? 0) + 1;\n return {\n total: all.length,\n unresolved: unresolved.length,\n blocking: blocking.length,\n reconciled: all.filter((c) => c.status === 'reconciled').length,\n preserved_deliberately: all.filter((c) => c.status === 'preserved_deliberately').length,\n rejected: all.filter((c) => c.status === 'rejected').length,\n by_type: byType,\n sections_with_clean_ledger: cleanLedgers,\n };\n}\n\nfunction buildReviewSummary(input: AggregateInput): ReviewSummary {\n let withReview = 0;\n let withoutReview = 0;\n const decisionCounts: Record<string, number> = {};\n let blockingFindings = 0;\n for (const data of input.perSection.values()) {\n if (data.claimReviews.length > 0) withReview += 1;\n else withoutReview += 1;\n const latest = latestDecisionByClaim(data.claimReviews);\n for (const r of latest.values()) {\n decisionCounts[r.decision] = (decisionCounts[r.decision] ?? 0) + 1;\n }\n blockingFindings += data.findings.filter((f) => f.severity === 'block').length;\n }\n return {\n sections_with_review_run: withReview,\n sections_without_review_run: withoutReview,\n decision_counts: decisionCounts,\n blocking_findings: blockingFindings,\n };\n}\n\nfunction buildWaiverSummary(input: AggregateInput): WaiverSummary {\n const byFamily: Record<string, number> = {};\n let total = 0;\n let invalid = 0;\n if (input.handoff) {\n for (const w of input.handoff.waivers) {\n total += 1;\n byFamily[w.family] = (byFamily[w.family] ?? 0) + 1;\n if (!w.reason || w.compensating_controls.length === 0) invalid += 1;\n }\n } else {\n const w = input.research.primary_source_waiver;\n if (w.status === 'granted') {\n total = 1;\n byFamily['source_floor'] = 1;\n if (!w.reason || w.compensating_controls.length === 0) invalid = 1;\n }\n }\n return { total, invalid, by_family: byFamily };\n}\n\nfunction buildReadinessSummary(\n rows: SynthesisReadinessRow[],\n handoff: CoworkHandoffPayload | null,\n unresolvedContradictions: UnresolvedContradictionRow[],\n): ReadinessSummary {\n let ready = 0;\n let repair = 0;\n let blocked = 0;\n let noGate = 0;\n let noReview = 0;\n const unresolvedBySection = new Map<string, number>();\n for (const c of unresolvedContradictions) {\n unresolvedBySection.set(c.section_id, (unresolvedBySection.get(c.section_id) ?? 0) + 1);\n }\n for (const r of rows) {\n if (!r.has_gate_run) noGate += 1;\n if (!r.has_review_run) noReview += 1;\n const unresolvedCount = unresolvedBySection.get(r.section_id) ?? 0;\n if (\n r.synthesis_eligible &&\n r.has_review_run &&\n r.candidate_claims > 0 &&\n r.blocking_reasons.length === 0 &&\n unresolvedCount === 0\n ) {\n ready += 1;\n } else if (r.has_gate_run && r.gate_verdict === 'blocked' && !r.synthesis_eligible) {\n blocked += 1;\n } else {\n repair += 1;\n }\n }\n return {\n total_sections: rows.length,\n ready_sections: ready,\n repair_sections: repair,\n blocked_sections: blocked,\n no_gate_sections: noGate,\n no_review_sections: noReview,\n cowork_handoff_mode: (handoff?.mode as HandoffMode | undefined) ?? 'unknown',\n workspace_allowed: handoff?.synthesis_allowed ?? false,\n };\n}\n\nfunction determineVerdict(args: {\n rows: SynthesisReadinessRow[];\n unresolvedContradictions: UnresolvedContradictionRow[];\n waiverSummary: WaiverSummary;\n warnings: string[];\n readiness: ReadinessSummary;\n totalSections: number;\n}): { verdict: PackVerdict; blockingReasons: string[] } {\n const reasons: string[] = [];\n const malformed = args.warnings.filter((w) => /malformed|invalid|parse/i.test(w));\n const blockingContradictions = args.unresolvedContradictions.filter(\n (c) => c.severity === 'blocking' || c.severity === 'high',\n );\n\n if (malformed.length > 0) {\n reasons.push(...malformed);\n return { verdict: 'human_review_required', blockingReasons: reasons };\n }\n if (args.waiverSummary.invalid > 0) {\n reasons.push('One or more granted waivers are missing reason or compensating_controls.');\n return { verdict: 'human_review_required', blockingReasons: reasons };\n }\n if (blockingContradictions.length > 0) {\n for (const c of blockingContradictions) {\n reasons.push(`Unresolved ${c.severity} contradiction in ${c.section_id}: ${c.contradiction_id}`);\n }\n return { verdict: 'human_review_required', blockingReasons: reasons };\n }\n\n if (args.readiness.ready_sections === args.totalSections && args.totalSections > 0) {\n return { verdict: 'ready_for_synthesis', blockingReasons: [] };\n }\n\n // No gates run on any section AND no claims anywhere → blocked (foundational gap).\n if (args.readiness.no_gate_sections === args.totalSections && args.totalSections > 0) {\n reasons.push('No section has a gate result on file. Pack has not begun gating.');\n return { verdict: 'blocked', blockingReasons: reasons };\n }\n\n // Otherwise repair_required\n if (args.readiness.no_gate_sections > 0) {\n reasons.push(`${args.readiness.no_gate_sections} section(s) have no gate result.`);\n }\n for (const r of args.rows) {\n if (r.gate_verdict === 'blocked') {\n reasons.push(`Section ${r.section_id} is gate-blocked: ${r.blocking_reasons.join('; ')}`);\n }\n }\n return { verdict: 'repair_required', blockingReasons: reasons };\n}\n\nfunction buildNextActions(args: {\n rows: SynthesisReadinessRow[];\n verdict: PackVerdict;\n unresolvedContradictions: UnresolvedContradictionRow[];\n waiverSummary: WaiverSummary;\n weakSources: WeakSourceRow[];\n}): string[] {\n const actions = new Set<string>();\n if (args.verdict === 'ready_for_synthesis') {\n actions.add('Run `research-os synth workspace` to lay out the synthesis area.');\n actions.add('Run `research-os index build --all` to refresh the queryable index.');\n return Array.from(actions);\n }\n if (args.verdict === 'human_review_required') {\n actions.add('Stop. Surface blocking reasons to the operator before any further automated work.');\n if (args.waiverSummary.invalid > 0) {\n actions.add('Fix each invalid waiver in research.yaml — granted requires reason + compensating_controls.');\n }\n if (args.unresolvedContradictions.some((c) => c.severity === 'blocking' || c.severity === 'high')) {\n actions.add('Reconcile, preserve_deliberately, or reject blocking contradictions in claim-reviews.');\n }\n return Array.from(actions);\n }\n // repair_required or blocked\n for (const r of args.rows) {\n if (!r.has_gate_run) {\n actions.add(`Run \\`research-os gate ${r.section_id}\\` (no gate result on file).`);\n } else if (r.gate_verdict === 'blocked') {\n actions.add(`[${r.section_id}] address blocking gate failures, then re-run \\`research-os gate ${r.section_id}\\`.`);\n }\n if (!r.has_review_run && r.candidate_claims > 0) {\n actions.add(`Run \\`research-os review ${r.section_id}\\` (no review run on file).`);\n }\n if (r.repair_claims > 0) {\n actions.add(`[${r.section_id}] ${r.repair_claims} claim(s) need repair — re-run gather/extract/review for affected sources.`);\n }\n }\n for (const w of args.weakSources) {\n if (w.reason === 'source_cluster_monopoly') {\n actions.add(`[${w.section_id}] add a source from an independent publisher.`);\n }\n }\n if (actions.size === 0) {\n actions.add('No specific next-actions identified, but pack is not synthesis-ready — re-run audit after refreshing inputs.');\n }\n return Array.from(actions);\n}\n\nconst AUDIT_FILE_PATHS = [\n 'audits/pack-audit.json',\n 'audits/pack-audit.md',\n 'audits/orphan-claims.json',\n 'audits/orphan-claims.md',\n 'audits/stale-sources.json',\n 'audits/stale-sources.md',\n 'audits/weak-sources.json',\n 'audits/weak-sources.md',\n 'audits/unresolved-contradictions.json',\n 'audits/unresolved-contradictions.md',\n 'audits/scope-widening-risks.json',\n 'audits/scope-widening-risks.md',\n 'audits/source-diversity-gaps.json',\n 'audits/source-diversity-gaps.md',\n 'audits/synthesis-readiness.json',\n 'audits/synthesis-readiness.md',\n];\n\nexport function aggregate(input: AggregateInput): AggregateOutput {\n const orphanClaims = buildOrphanClaims(input);\n const staleSources = buildStaleSources(input);\n const weakSources = buildWeakSources(input);\n const unresolvedContradictions = buildUnresolvedContradictions(input);\n const scopeWideningRisks = buildScopeWideningRisks(input);\n const sourceDiversityGaps = buildSourceDiversityGaps(input);\n const sectionRows = buildSectionReadiness(input, input.warnings);\n\n const claimSummary = buildClaimSummary(input, orphanClaims, input.warnings);\n const sourceSummary = buildSourceSummary(input);\n const contradictionSummary = buildContradictionSummary(input);\n const reviewSummary = buildReviewSummary(input);\n const waiverSummary = buildWaiverSummary(input);\n const readinessSummary = buildReadinessSummary(sectionRows, input.handoff, unresolvedContradictions);\n\n const { verdict, blockingReasons } = determineVerdict({\n rows: sectionRows,\n unresolvedContradictions,\n waiverSummary,\n warnings: input.warnings,\n readiness: readinessSummary,\n totalSections: input.research.sections.length,\n });\n\n const synthesisAllowed = verdict === 'ready_for_synthesis';\n const nextActions = buildNextActions({\n rows: sectionRows,\n verdict,\n unresolvedContradictions,\n waiverSummary,\n weakSources,\n });\n\n const payload: PackAuditPayload = {\n pack_id: packId(input.research),\n pack_topic: input.research.topic,\n generated_at: input.generatedAt,\n verdict,\n synthesis_allowed: synthesisAllowed,\n section_summaries: sectionRows,\n claim_summary: claimSummary,\n source_summary: sourceSummary,\n contradiction_summary: contradictionSummary,\n review_summary: reviewSummary,\n waiver_summary: waiverSummary,\n readiness_summary: readinessSummary,\n audit_files: AUDIT_FILE_PATHS,\n blocking_reasons: blockingReasons,\n warnings: input.warnings,\n next_actions: nextActions,\n };\n\n return {\n payload,\n orphanClaims,\n staleSources,\n weakSources,\n unresolvedContradictions,\n scopeWideningRisks,\n sourceDiversityGaps,\n };\n}\n","import { z } from 'zod';\n\nexport const PackVerdictSchema = z.enum([\n 'ready_for_synthesis',\n 'repair_required',\n 'human_review_required',\n 'blocked',\n]);\n\nexport const HandoffModeSchema = z.enum([\n 'repair_required',\n 'synthesis_ready',\n 'human_review_required',\n 'unknown',\n]);\n\nexport const OrphanClaimRowSchema = z.object({\n claim_id: z.string(),\n section_id: z.string(),\n reason: z.enum([\n 'missing_source_card',\n 'missing_source_hash',\n 'missing_evidence_excerpt',\n 'unresolvable_source_id',\n ]),\n details: z.string(),\n artifact_path: z.string(),\n});\n\nexport const StaleSourceRowSchema = z.object({\n source_id: z.string(),\n section_id: z.string(),\n publisher: z.string().nullable(),\n reason: z.enum(['too_old', 'missing_date', 'unparseable_date']),\n details: z.string(),\n artifact_path: z.string(),\n policy: z.object({\n required: z.boolean(),\n max_source_age_months: z.number().int().nullable(),\n stale_source_policy: z.enum(['warn', 'fail']),\n }),\n});\n\nexport const WeakSourceRowSchema = z.object({\n reason: z.enum([\n 'source_cluster_monopoly',\n 'low_independent_publishers',\n 'missing_primary_source',\n 'excessive_type_imbalance',\n 'failed_fetches_reducing_floor',\n ]),\n section_id: z.string(),\n details: z.string(),\n evidence_ids: z.array(z.string()),\n artifact_path: z.string(),\n});\n\nexport const UnresolvedContradictionRowSchema = z.object({\n contradiction_id: z.string(),\n section_id: z.string(),\n type: z.string(),\n severity: z.string(),\n status: z.string(),\n claim_ids: z.array(z.string()),\n artifact_path: z.string(),\n});\n\nexport const ScopeWideningRiskRowSchema = z.object({\n reason: z.enum([\n 'overgeneralization_finding',\n 'scope_null_in_use',\n 'missing_not_flagged',\n 'contextual_to_universal_risk',\n ]),\n claim_id: z.string(),\n section_id: z.string(),\n details: z.string(),\n artifact_path: z.string(),\n});\n\nexport const SourceDiversityGapRowSchema = z.object({\n reason: z.enum([\n 'section_publisher_monopoly',\n 'low_section_publisher_count',\n 'cross_section_publisher_overlap',\n 'section_has_no_sources',\n ]),\n section_id: z.string(),\n details: z.string(),\n evidence_ids: z.array(z.string()),\n});\n\nexport const SynthesisReadinessRowSchema = z.object({\n section_id: z.string(),\n purpose: z.string(),\n status: z.string(),\n has_gate_run: z.boolean(),\n has_review_run: z.boolean(),\n gate_verdict: z.string().nullable(),\n synthesis_eligible: z.boolean(),\n candidate_claims: z.number().int().nonnegative(),\n accepted_claims: z.number().int().nonnegative(),\n repair_claims: z.number().int().nonnegative(),\n rejected_claims: z.number().int().nonnegative(),\n dispositioned_claims: z.number().int().nonnegative(),\n blocking_reasons: z.array(z.string()),\n cowork_handoff_mode: HandoffModeSchema,\n workspace_allowed: z.boolean(),\n});\n\nexport const PackAuditPayloadSchema = z.object({\n pack_id: z.string(),\n pack_topic: z.string(),\n generated_at: z.string(),\n verdict: PackVerdictSchema,\n synthesis_allowed: z.boolean(),\n section_summaries: z.array(SynthesisReadinessRowSchema),\n claim_summary: z.object({\n total: z.number().int().nonnegative(),\n candidate: z.number().int().nonnegative(),\n accepted_for_synthesis: z.number().int().nonnegative(),\n rejected: z.number().int().nonnegative(),\n needs_repair: z.number().int().nonnegative(),\n dispositioned: z.number().int().nonnegative(),\n no_review: z.number().int().nonnegative(),\n with_evidence_excerpt: z.number().int().nonnegative(),\n with_source_hashes: z.number().int().nonnegative(),\n scope_null: z.number().int().nonnegative(),\n not_null: z.number().int().nonnegative(),\n orphans: z.number().int().nonnegative(),\n }),\n source_summary: z.object({\n total: z.number().int().nonnegative(),\n primary: z.number().int().nonnegative(),\n secondary: z.number().int().nonnegative(),\n forum: z.number().int().nonnegative(),\n benchmark: z.number().int().nonnegative(),\n docs: z.number().int().nonnegative(),\n unknown: z.number().int().nonnegative(),\n independent_publishers: z.number().int().nonnegative(),\n failed_fetches: z.number().int().nonnegative(),\n sections_with_sources: z.number().int().nonnegative(),\n sections_without_sources: z.number().int().nonnegative(),\n }),\n contradiction_summary: z.object({\n total: z.number().int().nonnegative(),\n unresolved: z.number().int().nonnegative(),\n blocking: z.number().int().nonnegative(),\n reconciled: z.number().int().nonnegative(),\n preserved_deliberately: z.number().int().nonnegative(),\n rejected: z.number().int().nonnegative(),\n by_type: z.record(z.string(), z.number().int().nonnegative()),\n sections_with_clean_ledger: z.number().int().nonnegative(),\n }),\n review_summary: z.object({\n sections_with_review_run: z.number().int().nonnegative(),\n sections_without_review_run: z.number().int().nonnegative(),\n decision_counts: z.record(z.string(), z.number().int().nonnegative()),\n blocking_findings: z.number().int().nonnegative(),\n }),\n waiver_summary: z.object({\n total: z.number().int().nonnegative(),\n invalid: z.number().int().nonnegative(),\n by_family: z.record(z.string(), z.number().int().nonnegative()),\n }),\n readiness_summary: z.object({\n total_sections: z.number().int().nonnegative(),\n ready_sections: z.number().int().nonnegative(),\n repair_sections: z.number().int().nonnegative(),\n blocked_sections: z.number().int().nonnegative(),\n no_gate_sections: z.number().int().nonnegative(),\n no_review_sections: z.number().int().nonnegative(),\n cowork_handoff_mode: HandoffModeSchema,\n workspace_allowed: z.boolean(),\n }),\n audit_files: z.array(z.string()),\n blocking_reasons: z.array(z.string()),\n warnings: z.array(z.string()),\n next_actions: z.array(z.string()),\n});\n\nexport type PackAuditPayload = z.infer<typeof PackAuditPayloadSchema>;\n","import type {\n OrphanClaimRow,\n PackAuditPayload,\n PackVerdict,\n ScopeWideningRiskRow,\n SourceDiversityGapRow,\n StaleSourceRow,\n UnresolvedContradictionRow,\n WeakSourceRow,\n} from './types.js';\n\nconst VERDICT_GLYPH: Record<PackVerdict, string> = {\n ready_for_synthesis: '[READY FOR SYNTHESIS]',\n repair_required: '[REPAIR REQUIRED]',\n human_review_required: '[HUMAN REVIEW REQUIRED]',\n blocked: '[BLOCKED]',\n};\n\nconst COMMON_LAW =\n '> Pack audit aggregates existing research truth. It does not create new truth, resolve failures, or hide section-level evidence. The canonical artifacts (claims, source-cards, fetch-log, gate/review JSON) are the source of authority — these rollups are pointers.';\n\nexport function renderPackAuditMarkdown(p: PackAuditPayload): string {\n const lines: string[] = [];\n lines.push(`# Pack Audit: ${p.pack_topic}`);\n lines.push('');\n lines.push(`**Pack ID:** \\`${p.pack_id}\\``);\n lines.push(`**Verdict:** ${VERDICT_GLYPH[p.verdict]} ${p.verdict}`);\n lines.push(`**Synthesis allowed:** ${p.synthesis_allowed ? 'yes' : 'no'}`);\n lines.push(`**Generated:** ${p.generated_at}`);\n lines.push(`**Cowork handoff mode:** ${p.readiness_summary.cowork_handoff_mode}`);\n lines.push(`**Workspace allowed:** ${p.readiness_summary.workspace_allowed ? 'yes' : 'no'}`);\n lines.push('');\n lines.push(COMMON_LAW);\n lines.push('');\n\n if (p.blocking_reasons.length > 0) {\n lines.push('## Blocking reasons');\n lines.push('');\n for (const r of p.blocking_reasons) lines.push(`- ${r}`);\n lines.push('');\n }\n\n lines.push('## Counts at a glance');\n lines.push('');\n lines.push(`- **Sections:** ${p.readiness_summary.total_sections} total — ${p.readiness_summary.ready_sections} ready, ${p.readiness_summary.repair_sections} in repair, ${p.readiness_summary.blocked_sections} blocked, ${p.readiness_summary.no_gate_sections} without gate, ${p.readiness_summary.no_review_sections} without review`);\n lines.push(`- **Claims:** ${p.claim_summary.total} total (${p.claim_summary.candidate} candidate; ${p.claim_summary.accepted_for_synthesis} accepted, ${p.claim_summary.needs_repair} repair, ${p.claim_summary.rejected} rejected, ${p.claim_summary.no_review} no_review, ${p.claim_summary.orphans} orphan)`);\n lines.push(`- **Sources:** ${p.source_summary.total} total (${p.source_summary.primary} primary, ${p.source_summary.secondary} secondary, ${p.source_summary.docs} docs, ${p.source_summary.forum} forum, ${p.source_summary.benchmark} benchmark, ${p.source_summary.unknown} unknown), ${p.source_summary.independent_publishers} publishers, ${p.source_summary.failed_fetches} failed fetches; ${p.source_summary.sections_with_sources}/${p.readiness_summary.total_sections} sections have at least one source`);\n lines.push(`- **Contradictions:** ${p.contradiction_summary.total} total (${p.contradiction_summary.unresolved} unresolved, ${p.contradiction_summary.blocking} high/blocking, ${p.contradiction_summary.reconciled} reconciled, ${p.contradiction_summary.preserved_deliberately} preserved_deliberately, ${p.contradiction_summary.rejected} rejected); ${p.contradiction_summary.sections_with_clean_ledger} sections have an empty contradiction ledger — *empty is not proof of completeness, only that the configured detector found nothing*`);\n lines.push(`- **Review:** ${p.review_summary.sections_with_review_run}/${p.readiness_summary.total_sections} sections have had \\`research-os review\\` run; ${p.review_summary.blocking_findings} blocking findings recorded`);\n lines.push(`- **Waivers:** ${p.waiver_summary.total} total (${p.waiver_summary.invalid} invalid)`);\n lines.push('');\n\n lines.push('## Section synthesis-readiness');\n lines.push('');\n lines.push('| Section | Status | Gate | Synthesis-eligible | Candidates | Accepted | Repair | Rejected |');\n lines.push('|---|---|---|---|---|---|---|---|');\n for (const r of p.section_summaries) {\n lines.push(`| \\`${r.section_id}\\` | ${r.status} | ${r.gate_verdict ?? '—'} | ${r.synthesis_eligible ? 'yes' : 'no'} | ${r.candidate_claims} | ${r.accepted_claims} | ${r.repair_claims} | ${r.rejected_claims} |`);\n }\n lines.push('');\n\n lines.push('## Audit files (canonical pointers)');\n lines.push('');\n for (const f of p.audit_files) lines.push(`- \\`${f}\\``);\n lines.push('');\n\n lines.push('## Recommended next actions');\n lines.push('');\n if (p.next_actions.length === 0) {\n lines.push('_(none recommended)_');\n } else {\n let i = 1;\n for (const a of p.next_actions) {\n lines.push(`${i}. ${a}`);\n i += 1;\n }\n }\n lines.push('');\n\n if (p.warnings.length > 0) {\n lines.push('## Warnings (from audit generation)');\n lines.push('');\n for (const w of p.warnings) lines.push(`- ${w}`);\n lines.push('');\n }\n\n return lines.join('\\n');\n}\n\n\nexport function renderOrphanClaimsMarkdown(rows: OrphanClaimRow[]): string {\n const lines: string[] = [];\n lines.push('# Orphan claims');\n lines.push('');\n lines.push(COMMON_LAW);\n lines.push('');\n if (rows.length === 0) {\n lines.push('_No orphan claims detected. (A clean orphan-claims ledger is a precondition for synthesis, not a proof of completeness.)_');\n return lines.join('\\n') + '\\n';\n }\n lines.push('| Claim ID | Section | Reason | Details | Artifact |');\n lines.push('|---|---|---|---|---|');\n for (const r of rows) {\n lines.push(`| \\`${r.claim_id}\\` | \\`${r.section_id}\\` | ${r.reason} | ${r.details.replace(/\\|/g, '\\\\|')} | \\`${r.artifact_path}\\` |`);\n }\n lines.push('');\n return lines.join('\\n');\n}\n\nexport function renderStaleSourcesMarkdown(rows: StaleSourceRow[]): string {\n const lines: string[] = [];\n lines.push('# Stale sources');\n lines.push('');\n lines.push(COMMON_LAW);\n lines.push('');\n if (rows.length === 0) {\n lines.push('_No stale sources detected (or pack freshness policy not required)._');\n return lines.join('\\n') + '\\n';\n }\n lines.push('| Source | Section | Publisher | Reason | Policy | Details | Artifact |');\n lines.push('|---|---|---|---|---|---|---|');\n for (const r of rows) {\n lines.push(`| \\`${r.source_id}\\` | \\`${r.section_id}\\` | ${r.publisher ?? '—'} | ${r.reason} | ${r.policy.stale_source_policy}${r.policy.max_source_age_months !== null ? ` (max ${r.policy.max_source_age_months}mo)` : ''} | ${r.details.replace(/\\|/g, '\\\\|')} | \\`${r.artifact_path}\\` |`);\n }\n lines.push('');\n return lines.join('\\n');\n}\n\nexport function renderWeakSourcesMarkdown(rows: WeakSourceRow[]): string {\n const lines: string[] = [];\n lines.push('# Weak sources');\n lines.push('');\n lines.push(COMMON_LAW);\n lines.push('');\n if (rows.length === 0) {\n lines.push('_No weak-source signals detected._');\n return lines.join('\\n') + '\\n';\n }\n for (const r of rows) {\n lines.push(`### \\`${r.section_id}\\`: ${r.reason}`);\n lines.push('');\n lines.push(`- **Details:** ${r.details}`);\n lines.push(`- **Evidence IDs:** ${r.evidence_ids.length === 0 ? '_(none)_' : r.evidence_ids.map((e) => `\\`${e}\\``).join(', ')}`);\n lines.push(`- **Artifact:** \\`${r.artifact_path}\\``);\n lines.push('');\n }\n return lines.join('\\n');\n}\n\nexport function renderUnresolvedContradictionsMarkdown(rows: UnresolvedContradictionRow[]): string {\n const lines: string[] = [];\n lines.push('# Unresolved contradictions');\n lines.push('');\n lines.push(COMMON_LAW);\n lines.push('');\n if (rows.length === 0) {\n lines.push('_No unresolved contradictions recorded across the pack. **A clean contradiction ledger is not proof of completeness — it means the configured detector found nothing of tension.** Adversarial review and Cowork synthesis must continue to challenge claims._');\n return lines.join('\\n') + '\\n';\n }\n lines.push('| Contradiction | Section | Type | Severity | Status | Claims | Artifact |');\n lines.push('|---|---|---|---|---|---|---|');\n for (const r of rows) {\n lines.push(`| \\`${r.contradiction_id}\\` | \\`${r.section_id}\\` | ${r.type} | ${r.severity} | ${r.status} | ${r.claim_ids.map((c) => `\\`${c}\\``).join(', ')} | \\`${r.artifact_path}\\` |`);\n }\n lines.push('');\n return lines.join('\\n');\n}\n\nexport function renderScopeWideningRisksMarkdown(rows: ScopeWideningRiskRow[]): string {\n const lines: string[] = [];\n lines.push('# Scope-widening risks');\n lines.push('');\n lines.push(COMMON_LAW);\n lines.push('');\n if (rows.length === 0) {\n lines.push('_No scope-widening risks detected at audit time. Synthesis must still preserve every claim\\'s scope verbatim._');\n return lines.join('\\n') + '\\n';\n }\n lines.push('| Claim | Section | Reason | Details | Artifact |');\n lines.push('|---|---|---|---|---|');\n for (const r of rows) {\n lines.push(`| \\`${r.claim_id}\\` | \\`${r.section_id}\\` | ${r.reason} | ${r.details.replace(/\\|/g, '\\\\|')} | \\`${r.artifact_path}\\` |`);\n }\n lines.push('');\n return lines.join('\\n');\n}\n\nexport function renderSourceDiversityGapsMarkdown(rows: SourceDiversityGapRow[]): string {\n const lines: string[] = [];\n lines.push('# Source-diversity gaps');\n lines.push('');\n lines.push(COMMON_LAW);\n lines.push('');\n if (rows.length === 0) {\n lines.push('_No source-diversity gaps detected._');\n return lines.join('\\n') + '\\n';\n }\n for (const r of rows) {\n lines.push(`### \\`${r.section_id}\\`: ${r.reason}`);\n lines.push('');\n lines.push(`- **Details:** ${r.details}`);\n lines.push(`- **Evidence IDs:** ${r.evidence_ids.length === 0 ? '_(none)_' : r.evidence_ids.map((e) => `\\`${e}\\``).join(', ')}`);\n lines.push('');\n }\n return lines.join('\\n');\n}\n\nexport function renderSynthesisReadinessMarkdown(p: PackAuditPayload): string {\n const lines: string[] = [];\n lines.push('# Synthesis readiness');\n lines.push('');\n lines.push(COMMON_LAW);\n lines.push('');\n lines.push(`**Pack verdict:** ${VERDICT_GLYPH[p.verdict]} ${p.verdict}`);\n lines.push(`**Synthesis allowed:** ${p.synthesis_allowed ? 'yes' : 'no'}`);\n lines.push(`**Cowork handoff mode:** ${p.readiness_summary.cowork_handoff_mode}`);\n lines.push(`**Workspace allowed:** ${p.readiness_summary.workspace_allowed ? 'yes' : 'no'}`);\n lines.push('');\n lines.push('## Section detail');\n lines.push('');\n lines.push('| Section | Status | Gate | Eligible | Candidates | Accepted | Repair | Rejected | Blocking reasons |');\n lines.push('|---|---|---|---|---|---|---|---|---|');\n for (const r of p.section_summaries) {\n const blocking = r.blocking_reasons.length === 0 ? '_(none)_' : r.blocking_reasons.map((b) => b.replace(/\\|/g, '\\\\|')).join('<br>');\n lines.push(`| \\`${r.section_id}\\` | ${r.status} | ${r.gate_verdict ?? '—'} | ${r.synthesis_eligible ? 'yes' : 'no'} | ${r.candidate_claims} | ${r.accepted_claims} | ${r.repair_claims} | ${r.rejected_claims} | ${blocking} |`);\n }\n lines.push('');\n lines.push('## Recommended next actions');\n lines.push('');\n let i = 1;\n for (const a of p.next_actions) {\n lines.push(`${i}. ${a}`);\n i += 1;\n }\n lines.push('');\n return lines.join('\\n');\n}\n","import { existsSync } from 'node:fs';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { join, resolve } from 'node:path';\nimport { parse as yamlParse } from 'yaml';\n\nimport { PackNotFoundError } from '../errors.js';\nimport { ResearchYamlSchema, type ResearchYaml } from '../intake/schema.js';\nimport { ClaimSchema, type Claim } from '../claims/schema.js';\nimport { ContradictionSchema, type Contradiction } from '../contradictions/schema.js';\nimport {\n ContradictionResolutionSchema,\n type ContradictionResolution,\n} from '../contradictions/resolution-schema.js';\nimport {\n ClaimSynthesisDispositionSchema,\n type ClaimSynthesisDisposition,\n} from '../dispositions/schema.js';\nimport {\n FetchReceiptSchema,\n SourceCardSchema,\n type FetchReceipt,\n type SourceCard,\n} from '../sources/schema.js';\nimport { SectionGateResultSchema, type SectionGateResult } from '../gates/schema.js';\nimport {\n ClaimReviewSchema,\n ReviewFindingSchema,\n type ClaimReview,\n type ReviewFinding,\n} from '../review/schema.js';\nimport {\n CoworkHandoffPayloadSchema,\n type CoworkHandoffPayload,\n} from '../cowork/schema.js';\n\nimport { aggregate, type AggregateInput } from './aggregate.js';\nimport { PackAuditPayloadSchema } from './schema.js';\nimport {\n renderOrphanClaimsMarkdown,\n renderPackAuditMarkdown,\n renderScopeWideningRisksMarkdown,\n renderSourceDiversityGapsMarkdown,\n renderStaleSourcesMarkdown,\n renderSynthesisReadinessMarkdown,\n renderUnresolvedContradictionsMarkdown,\n renderWeakSourcesMarkdown,\n} from './markdown.js';\nimport type { AuditOptions, AuditSummary } from './types.js';\n\nasync function readJsonl<T>(\n path: string,\n parse: (raw: unknown) => T,\n warnings: string[],\n): Promise<T[]> {\n if (!existsSync(path)) return [];\n const text = await readFile(path, 'utf8');\n const out: T[] = [];\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n out.push(parse(JSON.parse(line)));\n } catch (err) {\n warnings.push(`malformed line in ${path}: ${err instanceof Error ? err.message : 'parse error'}`);\n }\n }\n return out;\n}\n\nasync function readSourceCards(\n packPath: string,\n warnings: string[],\n): Promise<SourceCard[]> {\n const dir = join(packPath, 'evidence', 'source-cards');\n if (!existsSync(dir)) return [];\n const { readdir } = await import('node:fs/promises');\n const entries = await readdir(dir);\n const cards: SourceCard[] = [];\n for (const entry of entries) {\n if (!entry.endsWith('.json')) continue;\n try {\n const text = await readFile(join(dir, entry), 'utf8');\n cards.push(SourceCardSchema.parse(JSON.parse(text)));\n } catch (err) {\n warnings.push(`malformed source card ${entry}: ${err instanceof Error ? err.message : 'parse error'}`);\n }\n }\n return cards;\n}\n\nasync function readGate(\n packPath: string,\n sectionId: string,\n warnings: string[],\n): Promise<SectionGateResult | null> {\n const path = join(packPath, 'audits', `${sectionId}-gate.json`);\n if (!existsSync(path)) return null;\n try {\n return SectionGateResultSchema.parse(JSON.parse(await readFile(path, 'utf8')));\n } catch (err) {\n warnings.push(`malformed gate result for ${sectionId}: ${err instanceof Error ? err.message : 'parse error'}`);\n return null;\n }\n}\n\nasync function readHandoff(\n packPath: string,\n warnings: string[],\n): Promise<CoworkHandoffPayload | null> {\n const path = join(packPath, 'handoffs', 'cowork-handoff.json');\n if (!existsSync(path)) return null;\n try {\n return CoworkHandoffPayloadSchema.parse(JSON.parse(await readFile(path, 'utf8')));\n } catch (err) {\n warnings.push(`malformed handoff: ${err instanceof Error ? err.message : 'parse error'}`);\n return null;\n }\n}\n\nasync function readSourceIdsForSection(\n packPath: string,\n sectionId: string,\n): Promise<string[]> {\n const path = join(packPath, 'sections', sectionId, 'sources.jsonl');\n if (!existsSync(path)) return [];\n const text = await readFile(path, 'utf8');\n const ids: string[] = [];\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n const parsed = JSON.parse(line) as { source_id?: string };\n if (typeof parsed.source_id === 'string') ids.push(parsed.source_id);\n } catch {\n /* skip */\n }\n }\n return ids;\n}\n\nexport async function audit(options: AuditOptions): Promise<AuditSummary> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n const yamlPath = join(packPath, 'research.yaml');\n if (!existsSync(yamlPath)) throw new PackNotFoundError(packPath);\n const research: ResearchYaml = ResearchYamlSchema.parse(yamlParse(await readFile(yamlPath, 'utf8')));\n\n const warnings: string[] = [];\n const perSection: AggregateInput['perSection'] = new Map();\n for (const section of research.sections) {\n const sid = section.id;\n const claims = await readJsonl<Claim>(\n join(packPath, 'sections', sid, 'claims.jsonl'),\n (r) => ClaimSchema.parse(r),\n warnings,\n );\n const candidateClaims = claims.filter((c) => c.review_state === 'candidate');\n const claimReviews = await readJsonl<ClaimReview>(\n join(packPath, 'sections', sid, 'claim-reviews.jsonl'),\n (r) => ClaimReviewSchema.parse(r),\n warnings,\n );\n const contradictions = await readJsonl<Contradiction>(\n join(packPath, 'sections', sid, 'contradictions.jsonl'),\n (r) => ContradictionSchema.parse(r),\n warnings,\n );\n const resolutions = await readJsonl<ContradictionResolution>(\n join(packPath, 'sections', sid, 'contradiction-resolutions.jsonl'),\n (r) => ContradictionResolutionSchema.parse(r),\n warnings,\n );\n const dispositions = await readJsonl<ClaimSynthesisDisposition>(\n join(packPath, 'sections', sid, 'claim-synthesis-dispositions.jsonl'),\n (r) => ClaimSynthesisDispositionSchema.parse(r),\n warnings,\n );\n const findings = await readJsonl<ReviewFinding>(\n join(packPath, 'audits', `${sid}-findings.jsonl`),\n (r) => ReviewFindingSchema.parse(r),\n warnings,\n );\n const gate = await readGate(packPath, sid, warnings);\n const sourceIdsForSection = await readSourceIdsForSection(packPath, sid);\n perSection.set(sid, {\n claims,\n candidateClaims,\n claimReviews,\n contradictions,\n resolutions,\n dispositions,\n gate,\n findings,\n sourceIdsForSection,\n });\n }\n\n const sources = await readSourceCards(packPath, warnings);\n const receipts = await readJsonl<FetchReceipt>(\n join(packPath, 'evidence', 'fetch-log.jsonl'),\n (r) => FetchReceiptSchema.parse(r),\n warnings,\n );\n const handoff = await readHandoff(packPath, warnings);\n\n const generatedAt = new Date().toISOString();\n const result = aggregate({\n research,\n perSection,\n sources,\n receipts,\n handoff,\n generatedAt,\n warnings,\n });\n\n // Validate the payload before writing\n const payload = PackAuditPayloadSchema.parse(result.payload);\n\n const auditsDir = join(packPath, 'audits');\n await mkdir(auditsDir, { recursive: true });\n const filesWritten: string[] = [];\n\n const writeFileAndTrack = async (rel: string, content: string): Promise<void> => {\n const abs = join(packPath, rel);\n await writeFile(abs, content, 'utf8');\n filesWritten.push(abs);\n };\n\n await writeFileAndTrack('audits/pack-audit.json', JSON.stringify(payload, null, 2));\n await writeFileAndTrack('audits/pack-audit.md', renderPackAuditMarkdown(payload));\n\n await writeFileAndTrack('audits/orphan-claims.json', JSON.stringify(result.orphanClaims, null, 2));\n await writeFileAndTrack('audits/orphan-claims.md', renderOrphanClaimsMarkdown(result.orphanClaims));\n\n await writeFileAndTrack('audits/stale-sources.json', JSON.stringify(result.staleSources, null, 2));\n await writeFileAndTrack('audits/stale-sources.md', renderStaleSourcesMarkdown(result.staleSources));\n\n await writeFileAndTrack('audits/weak-sources.json', JSON.stringify(result.weakSources, null, 2));\n await writeFileAndTrack('audits/weak-sources.md', renderWeakSourcesMarkdown(result.weakSources));\n\n await writeFileAndTrack(\n 'audits/unresolved-contradictions.json',\n JSON.stringify(result.unresolvedContradictions, null, 2),\n );\n await writeFileAndTrack(\n 'audits/unresolved-contradictions.md',\n renderUnresolvedContradictionsMarkdown(result.unresolvedContradictions),\n );\n\n await writeFileAndTrack(\n 'audits/scope-widening-risks.json',\n JSON.stringify(result.scopeWideningRisks, null, 2),\n );\n await writeFileAndTrack(\n 'audits/scope-widening-risks.md',\n renderScopeWideningRisksMarkdown(result.scopeWideningRisks),\n );\n\n await writeFileAndTrack(\n 'audits/source-diversity-gaps.json',\n JSON.stringify(result.sourceDiversityGaps, null, 2),\n );\n await writeFileAndTrack(\n 'audits/source-diversity-gaps.md',\n renderSourceDiversityGapsMarkdown(result.sourceDiversityGaps),\n );\n\n await writeFileAndTrack('audits/synthesis-readiness.json', JSON.stringify(payload.section_summaries, null, 2));\n await writeFileAndTrack('audits/synthesis-readiness.md', renderSynthesisReadinessMarkdown(payload));\n\n return {\n packPath,\n verdict: payload.verdict,\n synthesisAllowed: payload.synthesis_allowed,\n filesWritten,\n warnings: payload.warnings,\n blockingReasons: payload.blocking_reasons,\n orphans: result.orphanClaims.length,\n staleSources: result.staleSources.length,\n weakSources: result.weakSources.length,\n unresolvedContradictions: result.unresolvedContradictions.length,\n scopeWideningRisks: result.scopeWideningRisks.length,\n sourceDiversityGaps: result.sourceDiversityGaps.length,\n };\n}\n","export { audit } from './run.js';\nexport { aggregate } from './aggregate.js';\nexport {\n renderPackAuditMarkdown,\n renderOrphanClaimsMarkdown,\n renderStaleSourcesMarkdown,\n renderWeakSourcesMarkdown,\n renderUnresolvedContradictionsMarkdown,\n renderScopeWideningRisksMarkdown,\n renderSourceDiversityGapsMarkdown,\n renderSynthesisReadinessMarkdown,\n} from './markdown.js';\nexport {\n PackVerdictSchema,\n HandoffModeSchema as AuditHandoffModeSchema,\n OrphanClaimRowSchema,\n StaleSourceRowSchema,\n WeakSourceRowSchema,\n UnresolvedContradictionRowSchema,\n ScopeWideningRiskRowSchema,\n SourceDiversityGapRowSchema,\n SynthesisReadinessRowSchema,\n PackAuditPayloadSchema,\n} from './schema.js';\nexport type {\n PackVerdict,\n HandoffMode as AuditHandoffMode,\n OrphanClaimRow,\n StaleSourceRow,\n WeakSourceRow,\n UnresolvedContradictionRow,\n ScopeWideningRiskRow,\n SourceDiversityGapRow,\n SynthesisReadinessRow,\n PackAuditPayload,\n ClaimSummary,\n SourceSummary,\n ContradictionSummary,\n ReviewSummary,\n WaiverSummary,\n ReadinessSummary,\n AuditOptions,\n AuditSummary,\n} from './types.js';\n","import { existsSync } from 'node:fs';\nimport { readFile, stat } from 'node:fs/promises';\nimport { createHash } from 'node:crypto';\nimport { join } from 'node:path';\n\nimport type { ArtifactHash, IntegrityCheck } from './types.js';\n\nexport interface CheckContext {\n packPath: string;\n invalidArtifacts: Array<{ path: string; error: string }>;\n missingArtifacts: string[];\n}\n\nexport async function fileSha256(absPath: string): Promise<ArtifactHash> {\n const buf = await readFile(absPath);\n const sha = createHash('sha256').update(buf).digest('hex');\n return { path: absPath, sha256: sha, bytes: buf.byteLength };\n}\n\nexport async function hashArtifact(\n ctx: CheckContext,\n rel: string,\n): Promise<ArtifactHash | null> {\n const abs = join(ctx.packPath, rel);\n if (!existsSync(abs)) {\n ctx.missingArtifacts.push(rel);\n return null;\n }\n try {\n const s = await stat(abs);\n if (!s.isFile()) {\n ctx.invalidArtifacts.push({ path: rel, error: 'not a regular file' });\n return null;\n }\n const h = await fileSha256(abs);\n return { ...h, path: rel };\n } catch (err) {\n ctx.invalidArtifacts.push({\n path: rel,\n error: err instanceof Error ? err.message : 'read error',\n });\n return null;\n }\n}\n\nexport function pass(name: string, detail = ''): IntegrityCheck {\n return { name, passed: true, detail: detail || 'ok' };\n}\n\nexport function fail(name: string, detail: string): IntegrityCheck {\n return { name, passed: false, detail };\n}\n","// Permissive at extract; strict at validate. Anything inside [claim:...] counts as\n// an attempted citation — freeze then checks whether the captured id resolves.\nconst CITATION_PATTERN = /\\[claim:([^\\]\\s]+)\\]/g;\nconst STRICT_CLAIM_ID_PATTERN = /^clm_[a-f0-9]{12}_(heuristic|ollama_intern)_\\d+$/;\n\nexport function isWellFormedClaimId(id: string): boolean {\n return STRICT_CLAIM_ID_PATTERN.test(id);\n}\n\nexport function extractClaimCitations(text: string): string[] {\n const out = new Set<string>();\n let match: RegExpExecArray | null;\n while ((match = CITATION_PATTERN.exec(text)) !== null) {\n out.add(match[1]!);\n }\n return Array.from(out);\n}\n\nexport function extractContradictionDisclosures(text: string, contradictionIds: string[]): string[] {\n const out: string[] = [];\n for (const id of contradictionIds) {\n if (text.includes(id)) out.push(id);\n }\n return out;\n}\n\nexport function extractWaiverDisclosures(\n text: string,\n waivers: Array<{ family: string; applied_to: string; reason: string }>,\n): string[] {\n // A waiver counts as disclosed if its applied_to identifier OR its family appears\n // verbatim in the synthesis text.\n const out: string[] = [];\n for (const w of waivers) {\n if (\n text.includes(w.applied_to) ||\n text.includes(w.family) ||\n (w.reason && w.reason.length > 12 && text.includes(w.reason.slice(0, 40)))\n ) {\n out.push(`${w.family}.${w.applied_to}`);\n }\n }\n return out;\n}\n","import type { FreezeReceiptPayload, FreezeRefusalPayload } from './types.js';\n\nexport function renderFreezeReceiptMarkdown(p: FreezeReceiptPayload): string {\n const lines: string[] = [];\n lines.push(`# Freeze Receipt: ${p.pack_topic}`);\n lines.push('');\n lines.push(`**Verdict:** [FROZEN]`);\n lines.push(`**Pack ID:** \\`${p.pack_id}\\``);\n lines.push(`**Frozen at:** ${p.frozen_at}`);\n lines.push('');\n lines.push(\n '> Freeze locks completed research truth. Every artifact below carries a sha256 fingerprint. The pack is now immutable evidence; any further mutation invalidates the receipt.',\n );\n lines.push('');\n\n lines.push('## Counts');\n lines.push('');\n lines.push(`- **Sources:** ${p.source_count}`);\n lines.push(`- **Claims:** ${p.claim_count}`);\n lines.push(`- **Contradictions:** ${p.contradiction_count}`);\n lines.push(`- **Review findings:** ${p.review_finding_count}`);\n lines.push(`- **Gate results:** ${p.gate_result_count}`);\n lines.push('');\n\n lines.push('## Sections');\n lines.push('');\n lines.push('| Section | Status | Accepted claims | Sources | Contradictions |');\n lines.push('|---|---|---|---|---|');\n for (const s of p.sections) {\n lines.push(`| \\`${s.section_id}\\` | ${s.status} | ${s.accepted_claims} | ${s.sources} | ${s.contradictions} |`);\n }\n lines.push('');\n\n lines.push('## Citation coverage');\n lines.push('');\n lines.push(`- **Accepted claims:** ${p.accepted_claim_ids.length}`);\n lines.push(`- **Cited in synthesis:** ${p.cited_claim_ids.length}`);\n lines.push(`- **Uncited accepted (informational):** ${p.uncited_accepted_claim_ids.length}`);\n if (p.uncited_accepted_claim_ids.length > 0) {\n lines.push('');\n lines.push('Uncited accepted claim_ids (preserved for future synthesis):');\n for (const cid of p.uncited_accepted_claim_ids) lines.push(`- \\`${cid}\\``);\n }\n lines.push('');\n\n lines.push('## Unresolved contradictions disclosed');\n lines.push('');\n if (p.unresolved_contradictions.length === 0) {\n lines.push('_None._');\n } else {\n for (const c of p.unresolved_contradictions) {\n lines.push(`- \\`${c.contradiction_id}\\` (\\`${c.section_id}\\`, ${c.type}, ${c.severity}) — disclosed in ${c.disclosed_in.map((d) => `\\`${d}\\``).join(', ')}`);\n }\n }\n lines.push('');\n\n lines.push('## Waivers disclosed');\n lines.push('');\n if (p.waivers_disclosed.length === 0) {\n lines.push('_None active._');\n } else {\n for (const w of p.waivers_disclosed) {\n lines.push(`- **${w.family}.${w.applied_to}** — disclosed in ${w.disclosed_in.map((d) => `\\`${d}\\``).join(', ')}`);\n lines.push(` - Reason: ${w.reason}`);\n for (const cc of w.compensating_controls) lines.push(` - Compensating: ${cc}`);\n }\n }\n lines.push('');\n\n lines.push('## Integrity checks');\n lines.push('');\n for (const c of p.integrity_checks) {\n const glyph = c.passed ? '[PASS]' : '[FAIL]';\n lines.push(`- ${glyph} **${c.name}** — ${c.detail}`);\n }\n lines.push('');\n\n lines.push('## Synthesis fingerprints');\n lines.push('');\n lines.push('| Path | Bytes | sha256 |');\n lines.push('|---|---|---|');\n for (const h of p.synthesis_hashes) {\n lines.push(`| \\`${h.path}\\` | ${h.bytes} | \\`${h.sha256.slice(0, 16)}…\\` |`);\n }\n lines.push('');\n\n lines.push('## Canonical artifact fingerprints');\n lines.push('');\n lines.push(`Total: ${p.canonical_artifact_hashes.length} files`);\n lines.push('');\n lines.push('| Path | Bytes | sha256 |');\n lines.push('|---|---|---|');\n for (const h of p.canonical_artifact_hashes) {\n lines.push(`| \\`${h.path}\\` | ${h.bytes} | \\`${h.sha256.slice(0, 16)}…\\` |`);\n }\n lines.push('');\n\n return lines.join('\\n');\n}\n\nexport function renderFreezeRefusalMarkdown(p: FreezeRefusalPayload): string {\n const lines: string[] = [];\n lines.push(`# Freeze Refusal: ${p.pack_topic}`);\n lines.push('');\n lines.push(`**Verdict:** [REFUSED]`);\n lines.push(`**Pack ID:** \\`${p.pack_id}\\``);\n lines.push(`**Checked at:** ${p.checked_at}`);\n lines.push(`**Would freeze:** no`);\n lines.push('');\n lines.push(\n '> Freeze locks completed research truth. It does not complete unfinished research, excuse missing synthesis, or convert repair state into evidence. The conditions below were not met; the pack remains active.',\n );\n lines.push('');\n\n if (p.blocking_reasons.length > 0) {\n lines.push('## Blocking reasons');\n lines.push('');\n for (const r of p.blocking_reasons) lines.push(`- ${r}`);\n lines.push('');\n }\n\n if (p.reasons.length > 0) {\n lines.push('## All reasons');\n lines.push('');\n for (const r of p.reasons) lines.push(`- ${r}`);\n lines.push('');\n }\n\n if (p.missing_artifacts.length > 0) {\n lines.push('## Missing artifacts');\n lines.push('');\n for (const a of p.missing_artifacts) lines.push(`- \\`${a}\\``);\n lines.push('');\n }\n\n if (p.invalid_artifacts.length > 0) {\n lines.push('## Invalid artifacts');\n lines.push('');\n for (const ia of p.invalid_artifacts) lines.push(`- \\`${ia.path}\\` — ${ia.error}`);\n lines.push('');\n }\n\n if (p.next_actions.length > 0) {\n lines.push('## Next actions');\n lines.push('');\n let i = 1;\n for (const a of p.next_actions) {\n lines.push(`${i}. ${a}`);\n i += 1;\n }\n lines.push('');\n }\n\n return lines.join('\\n');\n}\n","import { z } from 'zod';\n\nexport const ArtifactHashSchema = z.object({\n path: z.string(),\n sha256: z.string().regex(/^[a-f0-9]{64}$/),\n bytes: z.number().int().nonnegative(),\n});\n\nexport const IntegrityCheckSchema = z.object({\n name: z.string().min(1),\n passed: z.boolean(),\n detail: z.string(),\n});\n\nexport const FreezeReceiptPayloadSchema = z.object({\n pack_id: z.string(),\n pack_topic: z.string(),\n frozen_at: z.string(),\n verdict: z.literal('frozen'),\n pack_audit_hash: z.string().regex(/^[a-f0-9]{64}$/),\n handoff_hash: z.string().regex(/^[a-f0-9]{64}$/),\n synthesis_hashes: z.array(ArtifactHashSchema),\n canonical_artifact_hashes: z.array(ArtifactHashSchema),\n accepted_claim_ids: z.array(z.string()),\n cited_claim_ids: z.array(z.string()),\n uncited_accepted_claim_ids: z.array(z.string()),\n unresolved_contradictions: z.array(\n z.object({\n contradiction_id: z.string(),\n section_id: z.string(),\n type: z.string(),\n severity: z.string(),\n status: z.string(),\n disclosed_in: z.array(z.string()),\n }),\n ),\n waivers_disclosed: z.array(\n z.object({\n family: z.string(),\n applied_to: z.string(),\n reason: z.string(),\n compensating_controls: z.array(z.string()),\n disclosed_in: z.array(z.string()),\n }),\n ),\n sections: z.array(\n z.object({\n section_id: z.string(),\n status: z.string(),\n accepted_claims: z.number().int().nonnegative(),\n sources: z.number().int().nonnegative(),\n contradictions: z.number().int().nonnegative(),\n }),\n ),\n source_count: z.number().int().nonnegative(),\n claim_count: z.number().int().nonnegative(),\n contradiction_count: z.number().int().nonnegative(),\n review_finding_count: z.number().int().nonnegative(),\n gate_result_count: z.number().int().nonnegative(),\n integrity_checks: z.array(IntegrityCheckSchema),\n});\n\nexport const FreezeRefusalPayloadSchema = z.object({\n pack_id: z.string(),\n pack_topic: z.string(),\n checked_at: z.string(),\n verdict: z.literal('refused'),\n reasons: z.array(z.string()),\n blocking_reasons: z.array(z.string()),\n missing_artifacts: z.array(z.string()),\n invalid_artifacts: z.array(z.object({ path: z.string(), error: z.string() })),\n next_actions: z.array(z.string()),\n would_freeze: z.literal(false),\n});\n\nexport type FreezeReceiptPayload = z.infer<typeof FreezeReceiptPayloadSchema>;\nexport type FreezeRefusalPayload = z.infer<typeof FreezeRefusalPayloadSchema>;\n","import { existsSync } from 'node:fs';\nimport { mkdir, readFile, readdir, unlink, writeFile } from 'node:fs/promises';\nimport { createHash } from 'node:crypto';\nimport { join, resolve } from 'node:path';\nimport { parse as yamlParse, stringify as yamlStringify } from 'yaml';\n\nimport { PackNotFoundError } from '../errors.js';\nimport { ResearchYamlSchema, type ResearchYaml } from '../intake/schema.js';\nimport {\n PackAuditPayloadSchema,\n type PackAuditPayload,\n} from '../audit/schema.js';\nimport {\n CoworkHandoffPayloadSchema,\n type CoworkHandoffPayload,\n} from '../cowork/schema.js';\nimport { CrossSectionMapSchema } from '../synth/schema.js';\nimport { ClaimSchema } from '../claims/schema.js';\nimport { ClaimReviewSchema, type ClaimReview } from '../review/schema.js';\n\nimport { hashArtifact, pass, type CheckContext } from './checks.js';\nimport {\n extractClaimCitations,\n extractWaiverDisclosures,\n isWellFormedClaimId,\n} from './citations.js';\nimport { renderFreezeReceiptMarkdown, renderFreezeRefusalMarkdown } from './markdown.js';\nimport {\n FreezeReceiptPayloadSchema,\n FreezeRefusalPayloadSchema,\n} from './schema.js';\nimport type {\n ArtifactHash,\n FreezeOptions,\n FreezeReceiptPayload,\n FreezeRefusalPayload,\n FreezeSummary,\n IntegrityCheck,\n} from './types.js';\n\nconst REQUIRED_PACK_ARTIFACTS = ['research.yaml', 'audits/pack-audit.json', 'handoffs/cowork-handoff.json'];\nconst SYNTHESIS_FILES = [\n 'synthesis/cross-section-map.json',\n 'synthesis/cross-section-map.md',\n 'synthesis/decision-brief.md',\n 'synthesis/working-report.md',\n 'synthesis/final-report.md',\n];\n\nfunction packId(research: ResearchYaml): string {\n const fingerprint = `${research.topic}|${research.created_at}`;\n let hash = 0;\n for (let i = 0; i < fingerprint.length; i += 1) {\n hash = Math.imul(31, hash) + fingerprint.charCodeAt(i);\n hash |= 0;\n }\n return Math.abs(hash).toString(16).padStart(12, '0').slice(-12);\n}\n\nfunction fileSha256Of(text: string): string {\n return createHash('sha256').update(text).digest('hex');\n}\n\ninterface RefusalContext {\n reasons: string[];\n blockingReasons: string[];\n missingArtifacts: string[];\n invalidArtifacts: Array<{ path: string; error: string }>;\n}\n\nfunction noteRefusal(ctx: RefusalContext, reason: string, blocking = true): void {\n ctx.reasons.push(reason);\n if (blocking) ctx.blockingReasons.push(reason);\n}\n\nasync function tryReadJson<T>(\n packPath: string,\n rel: string,\n parse: (raw: unknown) => T,\n invalid: Array<{ path: string; error: string }>,\n): Promise<T | null> {\n const abs = join(packPath, rel);\n if (!existsSync(abs)) return null;\n try {\n return parse(JSON.parse(await readFile(abs, 'utf8')));\n } catch (err) {\n invalid.push({ path: rel, error: err instanceof Error ? err.message : 'parse error' });\n return null;\n }\n}\n\nexport async function freeze(options: FreezeOptions): Promise<FreezeSummary> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n const yamlPath = join(packPath, 'research.yaml');\n if (!existsSync(yamlPath)) throw new PackNotFoundError(packPath);\n\n const refusal: RefusalContext = {\n reasons: [],\n blockingReasons: [],\n missingArtifacts: [],\n invalidArtifacts: [],\n };\n let research: ResearchYaml;\n try {\n research = ResearchYamlSchema.parse(yamlParse(await readFile(yamlPath, 'utf8')));\n } catch (err) {\n refusal.invalidArtifacts.push({ path: 'research.yaml', error: err instanceof Error ? err.message : 'parse error' });\n return writeRefusal({\n packPath,\n pid: 'unknown',\n topic: 'unknown',\n refusal,\n });\n }\n\n const pid = packId(research);\n\n // Required artifacts presence\n for (const rel of REQUIRED_PACK_ARTIFACTS) {\n if (!existsSync(join(packPath, rel))) {\n refusal.missingArtifacts.push(rel);\n noteRefusal(refusal, `Required artifact missing: ${rel}.`);\n }\n }\n for (const rel of SYNTHESIS_FILES) {\n if (!existsSync(join(packPath, rel))) {\n refusal.missingArtifacts.push(rel);\n noteRefusal(refusal, `Synthesis artifact missing: ${rel}. Run \\`research-os synth workspace\\` after the pack reaches synthesis_ready.`);\n }\n }\n\n const packAudit = await tryReadJson<PackAuditPayload>(\n packPath,\n 'audits/pack-audit.json',\n (r) => PackAuditPayloadSchema.parse(r),\n refusal.invalidArtifacts,\n );\n const handoff = await tryReadJson<CoworkHandoffPayload>(\n packPath,\n 'handoffs/cowork-handoff.json',\n (r) => CoworkHandoffPayloadSchema.parse(r),\n refusal.invalidArtifacts,\n );\n const crossSectionMap = await tryReadJson(\n packPath,\n 'synthesis/cross-section-map.json',\n (r) => CrossSectionMapSchema.parse(r),\n refusal.invalidArtifacts,\n );\n\n if (refusal.invalidArtifacts.length > 0) {\n for (const ia of refusal.invalidArtifacts) {\n noteRefusal(refusal, `Canonical artifact failed to parse: ${ia.path}: ${ia.error}`);\n }\n }\n\n if (packAudit && packAudit.verdict !== 'ready_for_synthesis') {\n noteRefusal(refusal, `Pack audit verdict is \"${packAudit.verdict}\", not \"ready_for_synthesis\".`);\n }\n if (handoff && handoff.mode !== 'synthesis_ready') {\n noteRefusal(refusal, `Cowork handoff mode is \"${handoff.mode}\", not \"synthesis_ready\".`);\n }\n\n // Citation analysis\n const finalReportAbs = join(packPath, 'synthesis/final-report.md');\n const decisionBriefAbs = join(packPath, 'synthesis/decision-brief.md');\n const workingReportAbs = join(packPath, 'synthesis/working-report.md');\n let finalReportText = '';\n let decisionBriefText = '';\n let workingReportText = '';\n if (existsSync(finalReportAbs)) finalReportText = await readFile(finalReportAbs, 'utf8');\n if (existsSync(decisionBriefAbs)) decisionBriefText = await readFile(decisionBriefAbs, 'utf8');\n if (existsSync(workingReportAbs)) workingReportText = await readFile(workingReportAbs, 'utf8');\n\n // Defense in depth: read live claims + claim-reviews directly rather than\n // trusting the cross-section-map snapshot. If reviews changed after synth\n // workspace ran, we want to catch it at freeze.\n const livePackClaimIds = new Set<string>();\n const liveLatestDecisionByClaim = new Map<string, string>();\n const liveLatestCreatedAtByClaim = new Map<string, string>();\n for (const section of research.sections) {\n const claimsFile = join(packPath, 'sections', section.id, 'claims.jsonl');\n if (existsSync(claimsFile)) {\n const text = await readFile(claimsFile, 'utf8');\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n const c = ClaimSchema.parse(JSON.parse(line));\n livePackClaimIds.add(c.claim_id);\n } catch (err) {\n refusal.invalidArtifacts.push({\n path: `sections/${section.id}/claims.jsonl`,\n error: err instanceof Error ? err.message : 'parse error',\n });\n }\n }\n }\n const reviewsFile = join(packPath, 'sections', section.id, 'claim-reviews.jsonl');\n if (existsSync(reviewsFile)) {\n const text = await readFile(reviewsFile, 'utf8');\n const reviews: ClaimReview[] = [];\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n reviews.push(ClaimReviewSchema.parse(JSON.parse(line)));\n } catch (err) {\n refusal.invalidArtifacts.push({\n path: `sections/${section.id}/claim-reviews.jsonl`,\n error: err instanceof Error ? err.message : 'parse error',\n });\n }\n }\n // Latest by created_at wins\n for (const r of reviews) {\n const existingCreatedAt = liveLatestCreatedAtByClaim.get(r.claim_id);\n if (!existingCreatedAt || r.created_at > existingCreatedAt) {\n liveLatestCreatedAtByClaim.set(r.claim_id, r.created_at);\n liveLatestDecisionByClaim.set(r.claim_id, r.decision);\n }\n }\n }\n }\n\n const acceptedClaimIds: string[] = [];\n for (const [cid, decision] of liveLatestDecisionByClaim) {\n if (decision === 'accepted_for_synthesis') acceptedClaimIds.push(cid);\n }\n acceptedClaimIds.sort();\n\n const allClaimIds = livePackClaimIds;\n const repairOrRejected = new Set<string>();\n for (const [cid, decision] of liveLatestDecisionByClaim) {\n if (decision === 'rejected' || decision.startsWith('needs_')) {\n repairOrRejected.add(cid);\n }\n }\n\n const citationsInFinal = extractClaimCitations(finalReportText);\n const citationsInBrief = extractClaimCitations(decisionBriefText);\n const citationsInWorking = extractClaimCitations(workingReportText);\n const allCitedSet = new Set<string>([...citationsInFinal, ...citationsInBrief, ...citationsInWorking]);\n const allCited = Array.from(allCitedSet);\n\n const unknownCitations = allCited.filter((c) => isWellFormedClaimId(c) && !allClaimIds.has(c));\n const repairCitations = allCited.filter((c) => repairOrRejected.has(c));\n const uncitedAccepted = acceptedClaimIds.filter((c) => !allCitedSet.has(c));\n\n if (existsSync(finalReportAbs) && finalReportText.trim().length > 0) {\n if (citationsInFinal.length === 0 && acceptedClaimIds.length > 0) {\n noteRefusal(refusal, 'final-report.md contains no [claim:...] citations even though accepted claims exist.');\n }\n }\n if (unknownCitations.length > 0) {\n noteRefusal(refusal, `Synthesis cites unknown claim_id(s) not present in the pack: ${unknownCitations.join(', ')}.`);\n }\n if (repairCitations.length > 0) {\n noteRefusal(refusal, `Synthesis cites claim(s) that are in repair or rejected state: ${repairCitations.join(', ')}.`);\n }\n\n // Disclosure check: every unresolved contradiction must appear in decision-brief.md OR final-report.md\n const unresolvedContradictionRefs: FreezeReceiptPayload['unresolved_contradictions'] = [];\n if (crossSectionMap) {\n for (const c of crossSectionMap.cross_section_contradictions) {\n if (c.status !== 'unresolved') continue;\n const disclosedIn: string[] = [];\n if (decisionBriefText.includes(c.contradiction_id)) disclosedIn.push('synthesis/decision-brief.md');\n if (finalReportText.includes(c.contradiction_id)) disclosedIn.push('synthesis/final-report.md');\n if (disclosedIn.length === 0) {\n noteRefusal(refusal, `Unresolved contradiction ${c.contradiction_id} not disclosed in decision-brief.md or final-report.md.`);\n }\n unresolvedContradictionRefs.push({\n contradiction_id: c.contradiction_id,\n section_id: c.sections.join(','),\n type: c.type,\n severity: c.severity,\n status: c.status,\n disclosed_in: disclosedIn,\n });\n }\n }\n\n // Waiver disclosure\n const waiversDisclosed: FreezeReceiptPayload['waivers_disclosed'] = [];\n if (handoff) {\n for (const w of handoff.waivers) {\n const disclosedInBrief = extractWaiverDisclosures(decisionBriefText, [w]);\n const disclosedInFinal = extractWaiverDisclosures(finalReportText, [w]);\n const disclosedIn: string[] = [];\n if (disclosedInBrief.length > 0) disclosedIn.push('synthesis/decision-brief.md');\n if (disclosedInFinal.length > 0) disclosedIn.push('synthesis/final-report.md');\n if (disclosedIn.length === 0) {\n noteRefusal(refusal, `Waiver \"${w.family}.${w.applied_to}\" is not disclosed in decision-brief.md or final-report.md.`);\n }\n waiversDisclosed.push({\n family: w.family,\n applied_to: w.applied_to,\n reason: w.reason,\n compensating_controls: w.compensating_controls,\n disclosed_in: disclosedIn,\n });\n }\n }\n\n // Section status — every section must have a gate audit on file\n for (const section of research.sections) {\n if (!existsSync(join(packPath, 'audits', `${section.id}-gate.json`))) {\n noteRefusal(refusal, `Section ${section.id} has no gate result on file.`);\n refusal.missingArtifacts.push(`audits/${section.id}-gate.json`);\n }\n }\n\n // If we have refusal reasons, write the refusal artifact and return\n if (refusal.reasons.length > 0) {\n return writeRefusal({\n packPath,\n pid,\n topic: research.topic,\n refusal,\n });\n }\n\n // PASS PATH\n // Compute integrity checks\n const checks: IntegrityCheck[] = [];\n const ctx: CheckContext = {\n packPath,\n invalidArtifacts: [],\n missingArtifacts: [],\n };\n\n const synthesisHashes: ArtifactHash[] = [];\n for (const rel of SYNTHESIS_FILES) {\n const h = await hashArtifact(ctx, rel);\n if (h) synthesisHashes.push(h);\n }\n\n const canonicalPaths: string[] = [];\n canonicalPaths.push('research.yaml');\n for (const section of research.sections) {\n canonicalPaths.push(\n `sections/${section.id}/claims.jsonl`,\n `sections/${section.id}/sources.jsonl`,\n `sections/${section.id}/contradictions.jsonl`,\n `sections/${section.id}/claim-reviews.jsonl`,\n `sections/${section.id}/gates.yaml`,\n `audits/${section.id}-gate.json`,\n `audits/${section.id}-review.json`,\n `audits/${section.id}-findings.jsonl`,\n );\n }\n canonicalPaths.push('evidence/fetch-log.jsonl');\n canonicalPaths.push('evidence/citation-ledger.jsonl');\n if (existsSync(join(packPath, 'evidence', 'source-cards'))) {\n const entries = await readdir(join(packPath, 'evidence', 'source-cards'));\n for (const e of entries) {\n if (e.endsWith('.json')) canonicalPaths.push(`evidence/source-cards/${e}`);\n }\n }\n\n const canonicalHashes: ArtifactHash[] = [];\n for (const rel of canonicalPaths) {\n const abs = join(packPath, rel);\n if (!existsSync(abs)) continue;\n const h = await hashArtifact(ctx, rel);\n if (h) canonicalHashes.push(h);\n }\n\n checks.push(pass('pack_audit_ready', `pack-audit verdict=${packAudit?.verdict}`));\n checks.push(pass('handoff_synthesis_ready', `cowork-handoff mode=${handoff?.mode}`));\n checks.push(pass('synthesis_workspace_present', `${synthesisHashes.length}/${SYNTHESIS_FILES.length} synthesis files hashed`));\n checks.push(\n pass(\n 'final_report_cites_accepted_claims_only',\n `${citationsInFinal.length} citation(s); 0 unknown, 0 repair/rejected`,\n ),\n );\n checks.push(\n pass(\n 'unresolved_contradictions_disclosed',\n `${unresolvedContradictionRefs.length} contradiction(s) checked`,\n ),\n );\n checks.push(pass('waivers_disclosed', `${waiversDisclosed.length} waiver(s) checked`));\n checks.push(pass('canonical_artifacts_fingerprinted', `${canonicalHashes.length} artifact(s) hashed`));\n\n const packAuditHash = packAudit ? fileSha256Of(JSON.stringify(packAudit)) : '0'.repeat(64);\n const handoffHash = handoff ? fileSha256Of(JSON.stringify(handoff)) : '0'.repeat(64);\n\n // Section summaries\n const sections = research.sections.map((s) => {\n const handoffSection = handoff?.sections.find((hs) => hs.section_id === s.id);\n return {\n section_id: s.id,\n status: 'frozen',\n accepted_claims: handoffSection?.accepted_claim_ids.length ?? 0,\n sources: 0, // populated below if cross-section-map has data\n contradictions: handoffSection?.unresolved_contradiction_ids.length ?? 0,\n };\n });\n\n const frozenAt = new Date().toISOString();\n const receipt: FreezeReceiptPayload = FreezeReceiptPayloadSchema.parse({\n pack_id: pid,\n pack_topic: research.topic,\n frozen_at: frozenAt,\n verdict: 'frozen',\n pack_audit_hash: packAuditHash,\n handoff_hash: handoffHash,\n synthesis_hashes: synthesisHashes,\n canonical_artifact_hashes: canonicalHashes,\n accepted_claim_ids: acceptedClaimIds,\n cited_claim_ids: allCited,\n uncited_accepted_claim_ids: uncitedAccepted,\n unresolved_contradictions: unresolvedContradictionRefs,\n waivers_disclosed: waiversDisclosed,\n sections,\n source_count: canonicalHashes.filter((h) => h.path.includes('source-cards/')).length,\n claim_count: acceptedClaimIds.length,\n contradiction_count: unresolvedContradictionRefs.length,\n review_finding_count: 0,\n gate_result_count: research.sections.filter((s) => existsSync(join(packPath, 'audits', `${s.id}-gate.json`))).length,\n integrity_checks: checks,\n });\n\n // Update research.yaml: frozen_at + bump section statuses to 'frozen'\n const frozenResearch: ResearchYaml = {\n ...research,\n frozen_at: frozenAt,\n sections: research.sections.map((s) => ({ ...s, status: 'frozen' as const })),\n };\n await writeFile(yamlPath, yamlStringify(frozenResearch, { lineWidth: 0 }), 'utf8');\n\n const auditsDir = join(packPath, 'audits');\n await mkdir(auditsDir, { recursive: true });\n // Remove any stale refusal from a previous run\n for (const stale of ['freeze-refusal.json', 'freeze-refusal.md']) {\n const p = join(auditsDir, stale);\n if (existsSync(p)) await unlink(p);\n }\n const jsonPath = join(auditsDir, 'freeze-receipt.json');\n const mdPath = join(auditsDir, 'freeze-receipt.md');\n await writeFile(jsonPath, JSON.stringify(receipt, null, 2), 'utf8');\n await writeFile(mdPath, renderFreezeReceiptMarkdown(receipt), 'utf8');\n\n return {\n packPath,\n verdict: 'frozen',\n jsonPath,\n markdownPath: mdPath,\n receiptPayload: receipt,\n refusalPayload: null,\n reasonsCount: 0,\n citedClaimCount: allCited.length,\n uncitedAcceptedClaimCount: uncitedAccepted.length,\n };\n}\n\nasync function writeRefusal(args: {\n packPath: string;\n pid: string;\n topic: string;\n refusal: RefusalContext;\n}): Promise<FreezeSummary> {\n const checkedAt = new Date().toISOString();\n const nextActions = buildRefusalNextActions(args.refusal);\n const payload: FreezeRefusalPayload = FreezeRefusalPayloadSchema.parse({\n pack_id: args.pid,\n pack_topic: args.topic,\n checked_at: checkedAt,\n verdict: 'refused',\n reasons: args.refusal.reasons,\n blocking_reasons: args.refusal.blockingReasons,\n missing_artifacts: args.refusal.missingArtifacts,\n invalid_artifacts: args.refusal.invalidArtifacts,\n next_actions: nextActions,\n would_freeze: false,\n });\n\n const auditsDir = join(args.packPath, 'audits');\n await mkdir(auditsDir, { recursive: true });\n // Remove any stale receipt from a previous successful freeze that has now regressed\n for (const stale of ['freeze-receipt.json', 'freeze-receipt.md']) {\n const p = join(auditsDir, stale);\n if (existsSync(p)) await unlink(p);\n }\n const jsonPath = join(auditsDir, 'freeze-refusal.json');\n const mdPath = join(auditsDir, 'freeze-refusal.md');\n await writeFile(jsonPath, JSON.stringify(payload, null, 2), 'utf8');\n await writeFile(mdPath, renderFreezeRefusalMarkdown(payload), 'utf8');\n\n return {\n packPath: args.packPath,\n verdict: 'refused',\n jsonPath,\n markdownPath: mdPath,\n receiptPayload: null,\n refusalPayload: payload,\n reasonsCount: payload.reasons.length,\n citedClaimCount: 0,\n uncitedAcceptedClaimCount: 0,\n };\n}\n\nfunction buildRefusalNextActions(refusal: RefusalContext): string[] {\n const actions = new Set<string>();\n for (const r of refusal.reasons) {\n if (r.includes('pack-audit') || r.includes('Pack audit')) {\n actions.add('Run `research-os audit` after addressing repair items; freeze requires verdict=ready_for_synthesis.');\n }\n if (r.includes('handoff') || r.includes('Cowork handoff')) {\n actions.add('Run `research-os cowork handoff` after the pack reaches synthesis_ready.');\n }\n if (r.includes('synth') || r.includes('Synthesis')) {\n actions.add('Run `research-os synth workspace` to lay out the synthesis area (it refuses unless mode=synthesis_ready).');\n }\n if (r.includes('final-report')) {\n actions.add('Edit synthesis/final-report.md to cite accepted claims via [claim:clm_...] references.');\n }\n if (r.includes('unknown claim_id')) {\n actions.add('Replace any [claim:...] citation in synthesis with a claim_id that exists in the pack.');\n }\n if (r.includes('repair or rejected')) {\n actions.add('Remove citations to repair/rejected claims from synthesis or repair them via review.');\n }\n if (r.includes('contradiction') && r.includes('not disclosed')) {\n actions.add('Disclose every unresolved contradiction by id in decision-brief.md or final-report.md.');\n }\n if (r.includes('Waiver') && r.includes('not disclosed')) {\n actions.add('Disclose each active waiver by family.applied_to in decision-brief.md or final-report.md.');\n }\n if (r.includes('gate result on file')) {\n actions.add('Run `research-os gate <section>` for any section without a gate audit.');\n }\n if (r.includes('failed to parse')) {\n actions.add('Repair the malformed canonical artifact reported above (zod will not parse a corrupt file).');\n }\n }\n if (actions.size === 0) {\n actions.add('Re-run `research-os audit` to surface a fresh next-actions list.');\n }\n return Array.from(actions);\n}\n","export { freeze } from './run.js';\nexport { extractClaimCitations, extractContradictionDisclosures, extractWaiverDisclosures } from './citations.js';\nexport {\n renderFreezeReceiptMarkdown,\n renderFreezeRefusalMarkdown,\n} from './markdown.js';\nexport {\n ArtifactHashSchema,\n IntegrityCheckSchema,\n FreezeReceiptPayloadSchema,\n FreezeRefusalPayloadSchema,\n} from './schema.js';\nexport type {\n ArtifactHash,\n IntegrityCheck,\n CitationCoverage,\n FreezeReceiptPayload,\n FreezeRefusalPayload,\n FreezeOptions,\n FreezeSummary,\n} from './types.js';\n","import { z } from 'zod';\n\n// An invalidation receipt records that a class of artifacts was archived\n// because the contract that produced them was superseded. It is the\n// truth-preserving alternative to silent deletion: the old artifacts move\n// into audits/legacy/<label>/<timestamp>/, the receipt names what moved and\n// why, and downstream consumers can see that legacy state existed and\n// what replaced it.\n\nexport const ArchivedArtifactSchema = z.object({\n src: z.string(), // path relative to packPath, before archival\n dst: z.string(), // path relative to packPath, after archival\n});\n\nexport const SectionStatusChangeSchema = z.object({\n section_id: z.string().regex(/^[0-9]{2}-[a-z0-9-]+$/),\n before: z.string(),\n after: z.string(),\n});\n\nexport const InvalidationReceiptSchema = z.object({\n receipt_id: z.string().regex(/^inv_[0-9]+_[a-z0-9-]+$/),\n contract_label: z.string().min(1),\n superseded_contract: z.string().min(1).nullable(),\n new_contract: z.string().min(1),\n reason: z.string().min(8),\n invalidated_at: z.string(),\n research_os_version: z.string(),\n affected_sections: z.array(z.string().regex(/^[0-9]{2}-[a-z0-9-]+$/)),\n archived_artifacts: z.array(ArchivedArtifactSchema),\n section_status_changes: z.array(SectionStatusChangeSchema),\n frozen_at_cleared: z.boolean(),\n notes: z.string().nullable(),\n});\n\nexport type InvalidationReceipt = z.infer<typeof InvalidationReceiptSchema>;\nexport type ArchivedArtifact = z.infer<typeof ArchivedArtifactSchema>;\nexport type SectionStatusChange = z.infer<typeof SectionStatusChangeSchema>;\n","import { existsSync } from 'node:fs';\nimport { mkdir, readFile, readdir, rename, writeFile } from 'node:fs/promises';\nimport { dirname, join, posix, relative, resolve, sep } from 'node:path';\nimport { parse as yamlParse, stringify as yamlStringify } from 'yaml';\n\nimport { PackNotFoundError } from '../errors.js';\nimport { ResearchYamlSchema, type ResearchYaml } from '../intake/schema.js';\nimport { RESEARCH_OS_VERSION } from '../index.js';\nimport {\n InvalidationReceiptSchema,\n type ArchivedArtifact,\n type InvalidationReceipt,\n type SectionStatusChange,\n} from './schema.js';\nimport type {\n InvalidateExtractionOptions,\n InvalidateExtractionResult,\n} from './types.js';\n\n// Make all stored paths POSIX-style for cross-platform receipt portability.\nfunction posixify(p: string): string {\n return p.split(sep).join('/');\n}\n\n// A claim authored under the legacy contract has either no\n// evidence_excerpt_ids field at all, or an empty array. Span-first writes\n// always populate >= 1.\nfunction isLegacyClaimLine(line: string): boolean {\n const trimmed = line.trim();\n if (!trimmed) return false;\n try {\n const obj = JSON.parse(trimmed) as { evidence_excerpt_ids?: unknown };\n if (obj.evidence_excerpt_ids === undefined) return true;\n if (!Array.isArray(obj.evidence_excerpt_ids)) return true;\n return obj.evidence_excerpt_ids.length === 0;\n } catch {\n return false;\n }\n}\n\nasync function detectLegacyClaimSections(packPath: string): Promise<string[]> {\n const sectionsDir = join(packPath, 'sections');\n if (!existsSync(sectionsDir)) return [];\n const entries = await readdir(sectionsDir, { withFileTypes: true });\n const affected: string[] = [];\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n const claimsPath = join(sectionsDir, entry.name, 'claims.jsonl');\n if (!existsSync(claimsPath)) continue;\n const text = await readFile(claimsPath, 'utf8');\n let hasLegacy = false;\n for (const line of text.split(/\\r?\\n/)) {\n if (isLegacyClaimLine(line)) {\n hasLegacy = true;\n break;\n }\n }\n if (hasLegacy) affected.push(entry.name);\n }\n return affected.sort();\n}\n\nasync function moveIfExists(\n packPath: string,\n archiveRel: string,\n rel: string,\n): Promise<ArchivedArtifact | null> {\n const src = join(packPath, rel);\n if (!existsSync(src)) return null;\n const dst = join(packPath, archiveRel, rel);\n await mkdir(dirname(dst), { recursive: true });\n await rename(src, dst);\n return { src: posixify(rel), dst: posixify(join(archiveRel, rel)) };\n}\n\nasync function moveDirContentsIfExists(\n packPath: string,\n archiveRel: string,\n relDir: string,\n // Skip any path under the new archive itself so we never archive into ourselves.\n // skipPrefix is POSIX-style (forward slashes); we compare against POSIX form\n // of relative paths to keep behaviour identical across Windows and POSIX.\n skipPrefix: string,\n): Promise<ArchivedArtifact[]> {\n const fullDir = join(packPath, relDir);\n if (!existsSync(fullDir)) return [];\n const entries = await readdir(fullDir, { withFileTypes: true });\n const moved: ArchivedArtifact[] = [];\n for (const entry of entries) {\n // Always join in POSIX form for stable cross-platform comparisons.\n const childRelPosix = posix.join(posixify(relDir), entry.name);\n if (childRelPosix === skipPrefix || childRelPosix.startsWith(skipPrefix + '/')) continue;\n if (entry.isDirectory()) {\n moved.push(\n ...(await moveDirContentsIfExists(packPath, archiveRel, childRelPosix, skipPrefix)),\n );\n } else if (entry.isFile()) {\n const m = await moveIfExists(packPath, archiveRel, childRelPosix);\n if (m) moved.push(m);\n }\n }\n return moved;\n}\n\nfunction buildReceiptMarkdown(receipt: InvalidationReceipt): string {\n const lines: string[] = [];\n lines.push(`# Invalidation receipt: ${receipt.contract_label}`);\n lines.push('');\n lines.push(`- **Receipt ID:** \\`${receipt.receipt_id}\\``);\n lines.push(`- **Invalidated at:** ${receipt.invalidated_at}`);\n lines.push(`- **research-os version:** ${receipt.research_os_version}`);\n lines.push(`- **New contract:** ${receipt.new_contract}`);\n if (receipt.superseded_contract) {\n lines.push(`- **Superseded contract:** ${receipt.superseded_contract}`);\n }\n lines.push(`- **frozen_at cleared:** ${receipt.frozen_at_cleared ? 'yes' : 'no'}`);\n lines.push('');\n lines.push('## Reason');\n lines.push('');\n lines.push(receipt.reason);\n lines.push('');\n if (receipt.notes) {\n lines.push('## Notes');\n lines.push('');\n lines.push(receipt.notes);\n lines.push('');\n }\n lines.push(`## Affected sections (${receipt.affected_sections.length})`);\n lines.push('');\n if (receipt.affected_sections.length === 0) {\n lines.push('_None at the section level — only pack-level downstream artifacts were archived._');\n } else {\n for (const id of receipt.affected_sections) lines.push(`- \\`${id}\\``);\n }\n lines.push('');\n lines.push(`## Section status changes (${receipt.section_status_changes.length})`);\n lines.push('');\n if (receipt.section_status_changes.length === 0) {\n lines.push('_No section status changes._');\n } else {\n lines.push('| Section | Before | After |');\n lines.push('|---|---|---|');\n for (const c of receipt.section_status_changes) {\n lines.push(`| \\`${c.section_id}\\` | ${c.before} | ${c.after} |`);\n }\n }\n lines.push('');\n lines.push(`## Archived artifacts (${receipt.archived_artifacts.length})`);\n lines.push('');\n if (receipt.archived_artifacts.length === 0) {\n lines.push('_No artifacts archived._');\n } else {\n lines.push('Each row shows where the artifact was, and where it lives now.');\n lines.push('');\n lines.push('| From | To |');\n lines.push('|---|---|');\n for (const a of receipt.archived_artifacts) {\n lines.push(`| \\`${a.src}\\` | \\`${a.dst}\\` |`);\n }\n }\n lines.push('');\n return lines.join('\\n');\n}\n\nexport async function invalidateExtraction(\n options: InvalidateExtractionOptions,\n): Promise<InvalidateExtractionResult> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n const yamlPath = join(packPath, 'research.yaml');\n if (!existsSync(yamlPath)) throw new PackNotFoundError(packPath);\n\n const reason = options.reason.trim();\n if (reason.length < 8) {\n throw new Error('invalidation reason must be at least 8 characters');\n }\n\n const label = (options.label ?? 'pre-span-extraction').trim();\n if (!/^[a-z0-9-]+$/.test(label)) {\n throw new Error('invalidation label must be a kebab-case slug');\n }\n const newContract = options.newContract ?? 'span-first-extraction';\n const supersededContract = options.supersededContract ?? 'authored-evidence-excerpt';\n\n const now = options.now ?? (() => new Date());\n const stamp = now();\n const stampMs = stamp.getTime();\n const stampIso = stamp.toISOString();\n // Folder-friendly ISO without colons.\n const stampPath = stampIso.replace(/[:]/g, '').replace(/\\.\\d+Z$/, 'Z');\n const archiveRel = posix.join('audits', 'legacy', label, stampPath);\n\n const affectedSections = await detectLegacyClaimSections(packPath);\n\n const research = ResearchYamlSchema.parse(yamlParse(await readFile(yamlPath, 'utf8')));\n\n // Pack-level downstream artifacts that depend on extraction truth. Even if\n // only one section's claims are legacy, these aggregate over all sections\n // and reflect a state that no longer exists. Re-run audit/handoff/synth\n // after invalidation to rebuild them.\n const packLevelDirs = ['handoffs', 'synthesis', 'audits'];\n\n // If no affected sections AND no pack-level artifacts to archive, nothing\n // to do — return idempotent no-op.\n let probeArtifactsExist = affectedSections.length > 0;\n if (!probeArtifactsExist) {\n for (const d of packLevelDirs) {\n const full = join(packPath, d);\n if (!existsSync(full)) continue;\n // For audits/, a pre-existing legacy/ tree alone shouldn't trigger.\n const entries = await readdir(full, { withFileTypes: true });\n const meaningful = entries.some(\n (e) => !(d === 'audits' && e.isDirectory() && e.name === 'legacy'),\n );\n if (meaningful) {\n probeArtifactsExist = true;\n break;\n }\n }\n }\n\n if (!probeArtifactsExist) {\n return {\n performed: false,\n receiptId: null,\n contractLabel: label,\n affectedSections: [],\n archivedCount: 0,\n archiveDir: null,\n message: 'No legacy artifacts found. Pack is on the current extraction contract.',\n };\n }\n\n // Make the archive root early so moveIfExists has a stable target.\n await mkdir(join(packPath, archiveRel), { recursive: true });\n\n const archived: ArchivedArtifact[] = [];\n\n // Per-section files for affected sections.\n for (const sectionId of affectedSections) {\n for (const filename of [\n 'claims.jsonl',\n 'claim-reviews.jsonl',\n 'findings.jsonl',\n 'contradictions.jsonl',\n 'contradictions.md',\n 'claims.md',\n ]) {\n const rel = posix.join('sections', sectionId, filename);\n const a = await moveIfExists(packPath, archiveRel, rel);\n if (a) archived.push(a);\n }\n }\n\n // Pack-level downstream artifacts. Skip the archive's own subtree so we\n // don't try to archive ourselves.\n const skipPrefix = posix.join('audits', 'legacy');\n for (const d of packLevelDirs) {\n archived.push(...(await moveDirContentsIfExists(packPath, archiveRel, d, skipPrefix)));\n }\n\n // Reset section statuses for affected sections; remember the original.\n const statusChanges: SectionStatusChange[] = [];\n const affectedSet = new Set(affectedSections);\n const updatedSections = research.sections.map((s) => {\n if (!affectedSet.has(s.id)) return s;\n if (s.status === 'draft') return s;\n statusChanges.push({ section_id: s.id, before: s.status, after: 'draft' });\n return { ...s, status: 'draft' as const };\n });\n const frozenAtCleared = research.frozen_at !== null;\n const updated: ResearchYaml = {\n ...research,\n sections: updatedSections,\n frozen_at: null,\n };\n await writeFile(yamlPath, yamlStringify(updated, { lineWidth: 0 }), 'utf8');\n\n const receipt: InvalidationReceipt = InvalidationReceiptSchema.parse({\n receipt_id: `inv_${stampMs}_${label}`,\n contract_label: label,\n superseded_contract: supersededContract,\n new_contract: newContract,\n reason,\n invalidated_at: stampIso,\n research_os_version: RESEARCH_OS_VERSION,\n affected_sections: affectedSections,\n archived_artifacts: archived,\n section_status_changes: statusChanges,\n frozen_at_cleared: frozenAtCleared,\n notes: options.notes ?? null,\n });\n\n const receiptDir = join(packPath, archiveRel);\n await writeFile(\n join(receiptDir, 'invalidation.json'),\n JSON.stringify(receipt, null, 2),\n 'utf8',\n );\n await writeFile(\n join(receiptDir, 'invalidation.md'),\n buildReceiptMarkdown(receipt),\n 'utf8',\n );\n\n const archiveDirRel = posixify(relative(packPath, receiptDir));\n return {\n performed: true,\n receiptId: receipt.receipt_id,\n contractLabel: label,\n affectedSections,\n archivedCount: archived.length,\n archiveDir: archiveDirRel,\n message: `Archived ${archived.length} artifact(s) across ${affectedSections.length} affected section(s) → ${archiveDirRel}`,\n };\n}\n","import { existsSync } from 'node:fs';\nimport { mkdir, rename, writeFile } from 'node:fs/promises';\nimport { dirname, join, posix, relative, resolve, sep } from 'node:path';\n\nimport { PackNotFoundError, SectionNotFoundError } from '../errors.js';\nimport { RESEARCH_OS_VERSION } from '../index.js';\nimport {\n ArchivedArtifactSchema,\n type ArchivedArtifact,\n} from './schema.js';\nimport { z } from 'zod';\n\n// Review-scoped invalidation receipt. Distinct from the extraction\n// invalidation receipt because it operates on a different artifact set\n// and a different scope (per-section, not pack-wide), but follows the\n// same truth-preserving pattern: archive + receipt, never silent delete.\n\nexport const ReviewInvalidationReceiptSchema = z.object({\n receipt_id: z.string().regex(/^invr_[0-9]+_[a-z0-9-]+$/),\n section_id: z.string().regex(/^[0-9]{2}-[a-z0-9-]+$/),\n contract_label: z.string().min(1),\n reason: z.string().min(8),\n invalidated_at: z.string(),\n research_os_version: z.string(),\n archived_artifacts: z.array(ArchivedArtifactSchema),\n notes: z.string().nullable(),\n});\n\nexport type ReviewInvalidationReceipt = z.infer<typeof ReviewInvalidationReceiptSchema>;\n\nexport interface InvalidateReviewOptions {\n packPath?: string;\n sectionId: string;\n reason: string;\n // Folder label under sections/<id>/legacy/. Default: 'pre-review-profiles'.\n label?: string;\n notes?: string;\n now?: () => Date;\n}\n\nexport interface InvalidateReviewResult {\n performed: boolean;\n receiptId: string | null;\n sectionId: string;\n contractLabel: string;\n archivedCount: number;\n archiveDir: string | null;\n message: string;\n}\n\nfunction posixify(p: string): string {\n return p.split(sep).join('/');\n}\n\nasync function moveIfExists(\n packPath: string,\n archiveRel: string,\n rel: string,\n): Promise<ArchivedArtifact | null> {\n const src = join(packPath, rel);\n if (!existsSync(src)) return null;\n const dst = join(packPath, archiveRel, rel);\n await mkdir(dirname(dst), { recursive: true });\n await rename(src, dst);\n return { src: posixify(rel), dst: posixify(join(archiveRel, rel)) };\n}\n\nfunction buildReceiptMarkdown(receipt: ReviewInvalidationReceipt): string {\n const lines: string[] = [];\n lines.push(`# Review invalidation receipt: ${receipt.section_id}`);\n lines.push('');\n lines.push(`- **Receipt ID:** \\`${receipt.receipt_id}\\``);\n lines.push(`- **Contract label:** ${receipt.contract_label}`);\n lines.push(`- **Invalidated at:** ${receipt.invalidated_at}`);\n lines.push(`- **research-os version:** ${receipt.research_os_version}`);\n lines.push('');\n lines.push('## Reason');\n lines.push('');\n lines.push(receipt.reason);\n lines.push('');\n if (receipt.notes) {\n lines.push('## Notes');\n lines.push('');\n lines.push(receipt.notes);\n lines.push('');\n }\n lines.push(`## Archived artifacts (${receipt.archived_artifacts.length})`);\n lines.push('');\n if (receipt.archived_artifacts.length === 0) {\n lines.push('_No artifacts found to archive (canonical review state was already empty)._');\n } else {\n lines.push('| From | To |');\n lines.push('|---|---|');\n for (const a of receipt.archived_artifacts) {\n lines.push(`| \\`${a.src}\\` | \\`${a.dst}\\` |`);\n }\n }\n lines.push('');\n lines.push('---');\n lines.push('');\n lines.push(\n '_The reviewer profile data under `sections/<id>/reviews/<profile>/` is unaffected; this receipt only invalidates canonical (active) review state. Promote a profile via `research-os review-promote` to set new canonical truth._',\n );\n return lines.join('\\n');\n}\n\n// Archive the canonical review artifacts for a single section. The pre-profile\n// dogfood pack accumulated mixed Hermes/Qwen review history before profile\n// isolation existed; that ambiguity is itself a truth-seam and must be\n// invalidated explicitly, not papered over by the next promote.\nexport async function invalidateReview(\n options: InvalidateReviewOptions,\n): Promise<InvalidateReviewResult> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n if (!existsSync(join(packPath, 'research.yaml'))) throw new PackNotFoundError(packPath);\n if (!existsSync(join(packPath, 'sections', options.sectionId)))\n throw new SectionNotFoundError(options.sectionId);\n\n const reason = options.reason.trim();\n if (reason.length < 8) {\n throw new Error('invalidation reason must be at least 8 characters');\n }\n const label = (options.label ?? 'pre-review-profiles').trim();\n if (!/^[a-z0-9-]+$/.test(label)) {\n throw new Error('invalidation label must be a kebab-case slug');\n }\n\n const stamp = (options.now ?? (() => new Date()))();\n const stampMs = stamp.getTime();\n const stampIso = stamp.toISOString();\n const stampPath = stampIso.replace(/[:]/g, '').replace(/\\.\\d+Z$/, 'Z');\n const archiveRel = posix.join('sections', options.sectionId, 'legacy', label, stampPath);\n\n // Canonical review artifacts to archive.\n const candidatePaths = [\n posix.join('audits', `${options.sectionId}-review.json`),\n posix.join('audits', `${options.sectionId}-review.md`),\n posix.join('audits', `${options.sectionId}-findings.jsonl`),\n posix.join('sections', options.sectionId, 'claim-reviews.jsonl'),\n // Also clear review-active.json so the next review run is unambiguous.\n posix.join('sections', options.sectionId, 'review-active.json'),\n ];\n\n // No-op if there's nothing to archive.\n const present = candidatePaths.filter((rel) => existsSync(join(packPath, rel)));\n if (present.length === 0) {\n return {\n performed: false,\n receiptId: null,\n sectionId: options.sectionId,\n contractLabel: label,\n archivedCount: 0,\n archiveDir: null,\n message:\n 'No canonical review artifacts found to invalidate. Section has no active review state.',\n };\n }\n\n await mkdir(join(packPath, archiveRel), { recursive: true });\n const archived: ArchivedArtifact[] = [];\n for (const rel of present) {\n const a = await moveIfExists(packPath, archiveRel, rel);\n if (a) archived.push(a);\n }\n\n const receipt: ReviewInvalidationReceipt = ReviewInvalidationReceiptSchema.parse({\n receipt_id: `invr_${stampMs}_${options.sectionId}`,\n section_id: options.sectionId,\n contract_label: label,\n reason,\n invalidated_at: stampIso,\n research_os_version: RESEARCH_OS_VERSION,\n archived_artifacts: archived,\n notes: options.notes ?? null,\n });\n\n const receiptDir = join(packPath, archiveRel);\n await writeFile(\n join(receiptDir, 'invalidation.json'),\n JSON.stringify(receipt, null, 2),\n 'utf8',\n );\n await writeFile(\n join(receiptDir, 'invalidation.md'),\n buildReceiptMarkdown(receipt),\n 'utf8',\n );\n\n return {\n performed: true,\n receiptId: receipt.receipt_id,\n sectionId: options.sectionId,\n contractLabel: label,\n archivedCount: archived.length,\n archiveDir: posixify(relative(packPath, receiptDir)),\n message: `Archived ${archived.length} canonical review artifact(s) → ${posixify(relative(packPath, receiptDir))}`,\n };\n}\n","export { invalidateExtraction } from './run.js';\nexport {\n invalidateReview,\n ReviewInvalidationReceiptSchema,\n type ReviewInvalidationReceipt,\n type InvalidateReviewOptions,\n type InvalidateReviewResult,\n} from './review.js';\nexport {\n InvalidationReceiptSchema,\n ArchivedArtifactSchema,\n SectionStatusChangeSchema,\n type InvalidationReceipt,\n type ArchivedArtifact,\n type SectionStatusChange,\n} from './schema.js';\nexport type {\n InvalidateExtractionOptions,\n InvalidateExtractionResult,\n} from './types.js';\n","export { triage, readTriagedClaimIds } from './run.js';\nexport {\n ClaimTriageSchema,\n TriageDecisionSchema,\n TriageSummarySchema,\n type ClaimTriage,\n type TriageDecision,\n type TriageSummary,\n} from './schema.js';\nexport type { TriageOptions, TriageRunResult } from './types.js';\n","import { z } from 'zod';\n\n// Discovery proposes leads. A lead is NOT evidence. A lead becomes evidence\n// only after fetch receipt + source card + excerpt ledger + claim extraction.\n//\n// The boundary is enforced structurally: discovery writes to its own\n// per-section ledger and produces an `urls.approved.txt` file for `gather`\n// to consume. `gather` is unaware of how URLs were proposed; it just fetches\n// and emits receipts. If a discovered URL doesn't fetch, the operator sees a\n// failed receipt — exactly as if they'd typed the URL themselves.\n\nexport const DiscoveryCandidateStatusSchema = z.enum([\n 'candidate',\n 'approved',\n 'rejected',\n]);\n\nexport const SourceTypeGuessSchema = z.enum([\n 'primary',\n 'docs',\n 'paper',\n 'standard',\n 'article',\n 'forum',\n 'benchmark',\n 'unknown',\n]);\n\nexport const DiscoveryCandidateSchema = z.object({\n candidate_id: z.string().regex(/^disc_[a-f0-9]{12}$/),\n section_id: z.string().regex(/^[0-9]{2}-[a-z0-9-]+$/),\n url: z.string().url(),\n title: z.string().min(1),\n publisher: z.string().nullable(),\n source_type_guess: SourceTypeGuessSchema,\n why_relevant: z.string().min(1),\n // The free-text query that produced this candidate (for traceability).\n query: z.string().min(1),\n // Lower rank = more central. Stable per-(query, provider) ordering.\n rank: z.number().int().positive(),\n discovered_at: z.string(),\n // 'candidate' | 'approved' | 'rejected'. Append-only: new entries with\n // same candidate_id supersede older ones; the latest entry's status wins.\n status: DiscoveryCandidateStatusSchema,\n discovered_by: z.string().min(1),\n reason: z.string().nullable().default(null),\n});\n\nexport const DiscoverySummarySchema = z.object({\n summary_id: z.string().regex(/^disum_[0-9]+_[a-z0-9-]+$/),\n section_id: z.string().regex(/^[0-9]{2}-[a-z0-9-]+$/),\n ran_at: z.string(),\n research_os_version: z.string(),\n query: z.string().min(1),\n provider: z.string().min(1),\n candidates_proposed: z.number().int().nonnegative(),\n candidates_validated: z.number().int().nonnegative(),\n candidates_rejected_invalid_url: z.number().int().nonnegative(),\n warnings: z.array(z.string()),\n});\n\nexport type DiscoveryCandidate = z.infer<typeof DiscoveryCandidateSchema>;\nexport type DiscoveryCandidateStatus = z.infer<typeof DiscoveryCandidateStatusSchema>;\nexport type SourceTypeGuess = z.infer<typeof SourceTypeGuessSchema>;\nexport type DiscoverySummary = z.infer<typeof DiscoverySummarySchema>;\n","import { normalizeOllamaHost } from '../../sources/extractors/ollama-intern.js';\nimport type {\n DiscoverProposal,\n DiscoverProvider,\n DiscoverProviderInput,\n DiscoverProviderResult,\n} from '../types.js';\nimport type { SourceTypeGuess } from '../schema.js';\n\nconst DEFAULT_HOST = 'http://localhost:11434';\nconst DEFAULT_MODEL = 'hermes3:8b';\nconst DEFAULT_TIMEOUT_MS = 240_000;\n\nconst SYSTEM_PROMPT = `You are proposing source URLs for a research-pack section. You produce LEADS, not evidence. The system fetches each lead and decides on its own whether the URL is real and the content is acceptable.\n\nReturn ONE JSON object: {\"candidates\": [...]}.\n\nFor each candidate:\n{\n \"url\": \"absolute https URL\",\n \"title\": \"short human-readable title\",\n \"publisher\": \"the entity that hosts/publishes this page, or null if unknown\",\n \"source_type_guess\": one of \"primary\" | \"docs\" | \"paper\" | \"standard\" | \"article\" | \"forum\" | \"benchmark\" | \"unknown\",\n \"why_relevant\": \"ONE sentence on why this source is relevant to the section purpose\",\n \"rank\": integer 1..N where 1 is most central\n}\n\nHard rules:\n- Propose ONLY URLs you have high confidence exist. Canonical documentation, well-known papers, foundational standards, recognized authority sites. If you would have to guess, do not propose it.\n- Prefer primary sources (specs, official docs, peer-reviewed papers, standards bodies) over blog posts or forum threads.\n- Each URL must be a syntactically valid absolute https://… URL. No relative paths. No placeholder URLs.\n- Each title must be the actual page title or a tight summary, not a generic search-keyword string.\n- Be honest about source_type_guess; use \"unknown\" if truly unsure.\n- Order by rank — most central first. Do not return more than the requested target count.\n- If you cannot find enough confident candidates, return fewer. Quality over quantity.`;\n\nexport interface LlmHeuristicConfig {\n host?: string;\n model?: string;\n timeoutMs?: number;\n fetchImpl?: typeof fetch;\n}\n\ninterface ChatResponse {\n message?: { content?: string };\n response?: string;\n}\n\nconst VALID_SOURCE_TYPES: SourceTypeGuess[] = [\n 'primary',\n 'docs',\n 'paper',\n 'standard',\n 'article',\n 'forum',\n 'benchmark',\n 'unknown',\n];\n\nfunction asString(v: unknown, fallback = ''): string {\n return typeof v === 'string' && v.trim().length > 0 ? v.trim() : fallback;\n}\n\nfunction asStringOrNull(v: unknown): string | null {\n return typeof v === 'string' && v.trim().length > 0 ? v.trim() : null;\n}\n\nfunction asSourceType(v: unknown): SourceTypeGuess {\n return typeof v === 'string' && (VALID_SOURCE_TYPES as readonly string[]).includes(v)\n ? (v as SourceTypeGuess)\n : 'unknown';\n}\n\nexport class LlmHeuristicDiscoverProvider implements DiscoverProvider {\n readonly name = 'llm-heuristic';\n private readonly host: string;\n private readonly model: string;\n private readonly timeoutMs: number;\n private readonly fetchImpl: typeof fetch;\n\n constructor(config: LlmHeuristicConfig = {}) {\n this.host = normalizeOllamaHost(config.host ?? process.env.OLLAMA_HOST ?? DEFAULT_HOST);\n this.model = config.model ?? process.env.OLLAMA_INTERN_MODEL ?? DEFAULT_MODEL;\n this.timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n this.fetchImpl = config.fetchImpl ?? globalThis.fetch;\n }\n\n async available(): Promise<boolean> {\n try {\n const ctrl = new AbortController();\n const t = setTimeout(() => ctrl.abort(), 1500);\n const res = await this.fetchImpl(`${this.host}/api/tags`, { signal: ctrl.signal });\n clearTimeout(t);\n if (!res.ok) return false;\n const body = (await res.json()) as { models?: Array<{ name: string }> };\n const names = (body.models ?? []).map((m) => m.name);\n const family = this.model.split(':')[0] ?? this.model;\n return names.some((n) => n === this.model || n === family || n.startsWith(`${family}:`));\n } catch {\n return false;\n }\n }\n\n async propose(input: DiscoverProviderInput): Promise<DiscoverProviderResult> {\n const userMsg = `Section: ${input.sectionId}\nSection purpose: ${input.sectionPurpose}\nQuery: ${input.query}\nTarget candidate count: ${input.targetCount}\n\nPropose source-URL candidates for this section. Quality over quantity.`;\n\n const ctrl = new AbortController();\n const t = setTimeout(() => ctrl.abort(), this.timeoutMs);\n let body: ChatResponse;\n try {\n const res = await this.fetchImpl(`${this.host}/api/chat`, {\n method: 'POST',\n signal: ctrl.signal,\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n model: this.model,\n stream: false,\n format: 'json',\n options: { num_ctx: 8192 },\n messages: [\n { role: 'system', content: SYSTEM_PROMPT },\n { role: 'user', content: userMsg },\n ],\n }),\n });\n if (!res.ok) return { ok: false, error: `Ollama HTTP ${res.status}` };\n body = (await res.json()) as ChatResponse;\n } catch (err) {\n return { ok: false, error: err instanceof Error ? err.message : 'Ollama request failed' };\n } finally {\n clearTimeout(t);\n }\n\n const text = body.message?.content ?? body.response ?? '';\n let parsed: { candidates?: unknown };\n try {\n parsed = JSON.parse(text) as { candidates?: unknown };\n } catch {\n return { ok: false, error: 'Ollama response was not valid JSON' };\n }\n if (!Array.isArray(parsed.candidates)) {\n return { ok: false, error: 'Ollama response did not contain a candidates array' };\n }\n\n const proposals: DiscoverProposal[] = [];\n let nextRank = 1;\n for (const raw of parsed.candidates) {\n if (!raw || typeof raw !== 'object') continue;\n const r = raw as Record<string, unknown>;\n const url = asString(r.url);\n const title = asString(r.title);\n const why = asString(r.why_relevant);\n if (!url || !title || !why) continue;\n const rRank = typeof r.rank === 'number' && r.rank >= 1 ? Math.floor(r.rank) : nextRank;\n proposals.push({\n url,\n title,\n publisher: asStringOrNull(r.publisher),\n source_type_guess: asSourceType(r.source_type_guess),\n why_relevant: why,\n rank: rRank,\n });\n nextRank += 1;\n }\n return { ok: true, proposals, method: 'llm_heuristic_canonical_only' };\n }\n}\n","import { existsSync } from 'node:fs';\nimport { createHash } from 'node:crypto';\nimport { mkdir, readFile, writeFile, appendFile } from 'node:fs/promises';\nimport { join, resolve } from 'node:path';\nimport { parse as yamlParse } from 'yaml';\n\nimport { PackNotFoundError, SectionNotFoundError } from '../errors.js';\nimport { ResearchYamlSchema } from '../intake/schema.js';\nimport { RESEARCH_OS_VERSION } from '../index.js';\nimport {\n DiscoveryCandidateSchema,\n DiscoverySummarySchema,\n type DiscoveryCandidate,\n type DiscoveryCandidateStatus,\n type DiscoverySummary,\n} from './schema.js';\nimport type {\n ApproveOptions,\n ApproveResult,\n DiscoverOptions,\n DiscoverProvider,\n DiscoverProposal,\n DiscoverResult,\n ExportUrlsOptions,\n ExportUrlsResult,\n RejectOptions,\n RejectResult,\n} from './types.js';\nimport { LlmHeuristicDiscoverProvider } from './providers/llm-heuristic.js';\n\nconst DEFAULT_TARGET_COUNT = 12;\n\nfunction makeCandidateId(sectionId: string, url: string): string {\n // Stable per-(section,url) so re-running discover with the same query\n // doesn't generate duplicate candidate ids.\n const hex = createHash('sha256').update(`${sectionId}|${url}`).digest('hex').slice(0, 12);\n return `disc_${hex}`;\n}\n\nfunction isHttpsUrl(s: string): boolean {\n try {\n const u = new URL(s);\n return u.protocol === 'http:' || u.protocol === 'https:';\n } catch {\n return false;\n }\n}\n\nfunction candidatesPath(packPath: string, sectionId: string): string {\n return join(packPath, 'sections', sectionId, 'discovery-candidates.jsonl');\n}\n\nfunction reportPath(packPath: string, sectionId: string): string {\n return join(packPath, 'sections', sectionId, 'discovery-report.md');\n}\n\nfunction summaryPath(packPath: string, sectionId: string): string {\n return join(packPath, 'audits', `${sectionId}-discovery.json`);\n}\n\nfunction approvedUrlsPath(packPath: string, sectionId: string): string {\n return join(packPath, 'sections', sectionId, 'urls.approved.txt');\n}\n\nasync function readCandidates(packPath: string, sectionId: string): Promise<DiscoveryCandidate[]> {\n const path = candidatesPath(packPath, sectionId);\n if (!existsSync(path)) return [];\n const text = await readFile(path, 'utf8');\n const out: DiscoveryCandidate[] = [];\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n out.push(DiscoveryCandidateSchema.parse(JSON.parse(line)));\n } catch {\n /* skip malformed line */\n }\n }\n return out;\n}\n\n// Append-only ledger: latest entry per candidate_id wins. Approve/reject\n// emit a fresh entry with updated status; the ledger preserves history.\nfunction latestPerCandidate(candidates: DiscoveryCandidate[]): Map<string, DiscoveryCandidate> {\n const out = new Map<string, DiscoveryCandidate>();\n for (const c of candidates) {\n const prev = out.get(c.candidate_id);\n if (!prev || prev.discovered_at < c.discovered_at) out.set(c.candidate_id, c);\n }\n return out;\n}\n\nfunction defaultProviders(): DiscoverProvider[] {\n return [new LlmHeuristicDiscoverProvider()];\n}\n\nasync function pickProvider(providers: DiscoverProvider[]): Promise<DiscoverProvider | null> {\n for (const p of providers) {\n if (await p.available()) return p;\n }\n return null;\n}\n\nasync function loadSectionPurpose(packPath: string, sectionId: string): Promise<string> {\n const research = ResearchYamlSchema.parse(\n yamlParse(await readFile(join(packPath, 'research.yaml'), 'utf8')),\n );\n const section = research.sections.find((s) => s.id === sectionId);\n return section?.purpose ?? '';\n}\n\nfunction buildReportMarkdown(args: {\n sectionId: string;\n query: string;\n provider: string;\n ranAt: string;\n candidates: DiscoveryCandidate[];\n}): string {\n const lines: string[] = [];\n lines.push(`# Discovery report: ${args.sectionId}`);\n lines.push('');\n lines.push(`- **Query:** ${args.query}`);\n lines.push(`- **Provider:** ${args.provider}`);\n lines.push(`- **Ran at:** ${args.ranAt}`);\n lines.push(`- **Candidates:** ${args.candidates.length}`);\n lines.push('');\n lines.push('## Candidates');\n lines.push('');\n if (args.candidates.length === 0) {\n lines.push('_No candidates proposed. Provider may have refused on confidence grounds, or returned an empty result._');\n return lines.join('\\n');\n }\n lines.push('Discovery results are LEADS, not evidence. A lead becomes evidence only after `research-os gather` produces a fetch receipt + source card + excerpt ledger + claim extraction.');\n lines.push('');\n lines.push('| Rank | Status | Type | Title | Publisher | Why relevant | URL |');\n lines.push('|---:|---|---|---|---|---|---|');\n const sorted = [...args.candidates].sort((a, b) => a.rank - b.rank);\n for (const c of sorted) {\n lines.push(\n `| ${c.rank} | \\`${c.status}\\` | ${c.source_type_guess} | ${c.title.replace(/\\|/g, '\\\\|')} | ${(c.publisher ?? '—').replace(/\\|/g, '\\\\|')} | ${c.why_relevant.replace(/\\|/g, '\\\\|')} | ${c.url} |`,\n );\n }\n lines.push('');\n lines.push('---');\n lines.push('');\n lines.push('Approve candidates with `research-os discover approve <section> --top N` or `--candidate disc_<hex>`. Reject with `research-os discover reject <section> --candidate disc_<hex> --reason \"...\"`. Export approved URLs for gather with `research-os discover export-urls <section>` (or `gather <section> --approved`).');\n return lines.join('\\n');\n}\n\nexport async function discover(options: DiscoverOptions): Promise<DiscoverResult> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n if (!existsSync(join(packPath, 'research.yaml'))) throw new PackNotFoundError(packPath);\n if (!existsSync(join(packPath, 'sections', options.sectionId)))\n throw new SectionNotFoundError(options.sectionId);\n\n const query = options.query.trim();\n if (query.length < 4) throw new Error('discover query must be at least 4 characters');\n\n const target = options.targetCount ?? DEFAULT_TARGET_COUNT;\n const providers = options.providers ?? defaultProviders();\n const provider = await pickProvider(providers);\n if (!provider) {\n throw new Error('No discover provider available. Default provider is LLM-based and requires Ollama.');\n }\n\n const sectionPurpose = await loadSectionPurpose(packPath, options.sectionId);\n const result = await provider.propose({\n sectionId: options.sectionId,\n query,\n sectionPurpose,\n targetCount: target,\n });\n if (!result.ok) {\n throw new Error(`Discover provider \"${provider.name}\" failed: ${result.error}`);\n }\n\n const stamp = (options.now ?? (() => new Date()))();\n const stampIso = stamp.toISOString();\n\n // Filter syntactically invalid URLs at intake. Track count for the summary;\n // the operator will see it in the report.\n const validProposals: DiscoverProposal[] = [];\n let invalidCount = 0;\n const warnings: string[] = [];\n for (const p of result.proposals) {\n if (!isHttpsUrl(p.url)) {\n invalidCount += 1;\n warnings.push(`Rejected non-https URL: ${p.url}`);\n continue;\n }\n validProposals.push(p);\n }\n\n // De-duplicate against existing candidates for this section. If the same\n // URL was previously proposed (any status), don't append a duplicate.\n const existing = await readCandidates(packPath, options.sectionId);\n const existingByUrl = new Map<string, DiscoveryCandidate>();\n for (const e of latestPerCandidate(existing).values()) existingByUrl.set(e.url, e);\n\n const newCandidates: DiscoveryCandidate[] = [];\n for (const p of validProposals) {\n if (existingByUrl.has(p.url)) {\n warnings.push(`Skipped duplicate (already proposed): ${p.url}`);\n continue;\n }\n const candidate = DiscoveryCandidateSchema.parse({\n candidate_id: makeCandidateId(options.sectionId, p.url),\n section_id: options.sectionId,\n url: p.url,\n title: p.title,\n publisher: p.publisher,\n source_type_guess: p.source_type_guess,\n why_relevant: p.why_relevant,\n query,\n rank: p.rank,\n discovered_at: stampIso,\n status: 'candidate',\n discovered_by: provider.name,\n reason: null,\n });\n newCandidates.push(candidate);\n }\n\n // Append to ledger.\n const ledgerPath = candidatesPath(packPath, options.sectionId);\n await mkdir(join(packPath, 'sections', options.sectionId), { recursive: true });\n for (const c of newCandidates) {\n await appendFile(ledgerPath, JSON.stringify(c) + '\\n', 'utf8');\n }\n\n // Render the human-readable report against the FULL latest set (not just\n // this run's new candidates), so the report reflects current section state.\n const all = await readCandidates(packPath, options.sectionId);\n const latest = Array.from(latestPerCandidate(all).values());\n const md = buildReportMarkdown({\n sectionId: options.sectionId,\n query,\n provider: provider.name,\n ranAt: stampIso,\n candidates: latest,\n });\n await writeFile(reportPath(packPath, options.sectionId), md, 'utf8');\n\n // Run-level summary.\n const summary: DiscoverySummary = DiscoverySummarySchema.parse({\n summary_id: `disum_${stamp.getTime()}_${options.sectionId}`,\n section_id: options.sectionId,\n ran_at: stampIso,\n research_os_version: RESEARCH_OS_VERSION,\n query,\n provider: provider.name,\n candidates_proposed: result.proposals.length,\n candidates_validated: newCandidates.length,\n candidates_rejected_invalid_url: invalidCount,\n warnings,\n });\n await mkdir(join(packPath, 'audits'), { recursive: true });\n await writeFile(summaryPath(packPath, options.sectionId), JSON.stringify(summary, null, 2), 'utf8');\n\n return {\n candidatesAdded: newCandidates.length,\n candidatesProposed: result.proposals.length,\n candidatesRejectedInvalidUrl: invalidCount,\n warnings,\n candidates: newCandidates,\n candidatesPath: ledgerPath,\n reportPath: reportPath(packPath, options.sectionId),\n summaryPath: summaryPath(packPath, options.sectionId),\n };\n}\n\nasync function appendStatusUpdate(\n packPath: string,\n sectionId: string,\n candidate: DiscoveryCandidate,\n newStatus: DiscoveryCandidateStatus,\n reason: string | null,\n stampIso: string,\n): Promise<DiscoveryCandidate> {\n const updated: DiscoveryCandidate = DiscoveryCandidateSchema.parse({\n ...candidate,\n status: newStatus,\n reason,\n discovered_at: stampIso,\n });\n await appendFile(candidatesPath(packPath, sectionId), JSON.stringify(updated) + '\\n', 'utf8');\n return updated;\n}\n\nexport async function approve(options: ApproveOptions): Promise<ApproveResult> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n if (!existsSync(join(packPath, 'research.yaml'))) throw new PackNotFoundError(packPath);\n if (!existsSync(join(packPath, 'sections', options.sectionId)))\n throw new SectionNotFoundError(options.sectionId);\n\n const all = await readCandidates(packPath, options.sectionId);\n const latest = latestPerCandidate(all);\n const stamp = (options.now ?? (() => new Date()))();\n const stampIso = stamp.toISOString();\n\n const targets: DiscoveryCandidate[] = [];\n if (options.candidateIds && options.candidateIds.length > 0) {\n for (const id of options.candidateIds) {\n const c = latest.get(id);\n if (!c) throw new Error(`Candidate ${id} not found in section ${options.sectionId}`);\n targets.push(c);\n }\n } else if (options.topN && options.topN > 0) {\n const eligible = Array.from(latest.values())\n .filter((c) => c.status === 'candidate')\n .sort((a, b) => a.rank - b.rank);\n targets.push(...eligible.slice(0, options.topN));\n } else {\n throw new Error('approve requires --candidate <id> or --top <N>');\n }\n\n const approvedIds: string[] = [];\n for (const t of targets) {\n if (t.status === 'approved') {\n approvedIds.push(t.candidate_id);\n continue;\n }\n await appendStatusUpdate(packPath, options.sectionId, t, 'approved', options.reason ?? null, stampIso);\n approvedIds.push(t.candidate_id);\n }\n const exportPath = await exportUrls({ packPath, sectionId: options.sectionId });\n return { approved: approvedIds.length, approvedIds, exportPath: exportPath.exportPath };\n}\n\nexport async function reject(options: RejectOptions): Promise<RejectResult> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n if (!existsSync(join(packPath, 'research.yaml'))) throw new PackNotFoundError(packPath);\n if (!existsSync(join(packPath, 'sections', options.sectionId)))\n throw new SectionNotFoundError(options.sectionId);\n if (options.reason.trim().length < 4) {\n throw new Error('reject requires --reason of at least 4 characters');\n }\n const all = await readCandidates(packPath, options.sectionId);\n const latest = latestPerCandidate(all);\n const stamp = (options.now ?? (() => new Date()))();\n const stampIso = stamp.toISOString();\n const rejectedIds: string[] = [];\n for (const id of options.candidateIds) {\n const c = latest.get(id);\n if (!c) throw new Error(`Candidate ${id} not found in section ${options.sectionId}`);\n await appendStatusUpdate(\n packPath,\n options.sectionId,\n c,\n 'rejected',\n options.reason.trim(),\n stampIso,\n );\n rejectedIds.push(id);\n }\n // Re-export approved URLs (rejection of an approved candidate removes it).\n await exportUrls({ packPath, sectionId: options.sectionId });\n return { rejected: rejectedIds.length, rejectedIds };\n}\n\nexport async function exportUrls(options: ExportUrlsOptions): Promise<ExportUrlsResult> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n if (!existsSync(join(packPath, 'research.yaml'))) throw new PackNotFoundError(packPath);\n if (!existsSync(join(packPath, 'sections', options.sectionId)))\n throw new SectionNotFoundError(options.sectionId);\n const all = await readCandidates(packPath, options.sectionId);\n const latest = latestPerCandidate(all);\n const approved = Array.from(latest.values())\n .filter((c) => c.status === 'approved')\n .sort((a, b) => a.rank - b.rank);\n const lines = approved.map((c) => c.url).join('\\n');\n const path = approvedUrlsPath(packPath, options.sectionId);\n await mkdir(join(packPath, 'sections', options.sectionId), { recursive: true });\n await writeFile(path, lines + (lines.length > 0 ? '\\n' : ''), 'utf8');\n return { exportPath: path, approvedCount: approved.length };\n}\n","export { discover, approve, reject, exportUrls } from './run.js';\nexport {\n DiscoveryCandidateSchema,\n DiscoveryCandidateStatusSchema,\n SourceTypeGuessSchema,\n DiscoverySummarySchema,\n type DiscoveryCandidate,\n type DiscoveryCandidateStatus,\n type SourceTypeGuess,\n type DiscoverySummary,\n} from './schema.js';\nexport type {\n DiscoverOptions,\n DiscoverResult,\n DiscoverProvider,\n DiscoverProviderInput,\n DiscoverProviderResult,\n DiscoverProposal,\n ApproveOptions,\n ApproveResult,\n RejectOptions,\n RejectResult,\n ExportUrlsOptions,\n ExportUrlsResult,\n} from './types.js';\nexport { LlmHeuristicDiscoverProvider } from './providers/llm-heuristic.js';\n","export * from './intake/index.js';\nexport * from './sections/index.js';\nexport * from './sources/index.js';\nexport * from './claims/index.js';\nexport * from './contradictions/index.js';\nexport * from './gates/index.js';\nexport * from './review/index.js';\nexport * from './indexer/index.js';\nexport * from './cowork/index.js';\nexport * from './synth/index.js';\nexport * from './audit/index.js';\nexport * from './freeze/index.js';\nexport * from './invalidate/index.js';\nexport * from './section_report/index.js';\nexport * from './triage/index.js';\nexport * from './discover/index.js';\nexport {\n ResearchOSError,\n IntakeValidationError,\n PackExistsError,\n TemplateNotFoundError,\n PackNotFoundError,\n SectionExistsError,\n InvalidSectionIdError,\n SectionNotFoundError,\n NoUrlsProvidedError,\n NoSourcesGatheredError,\n HandoffNotFoundError,\n SynthesisNotReadyError,\n} from './errors.js';\n\nexport const RESEARCH_OS_VERSION = '0.3.0';\n","import { z } from 'zod';\n\n// A section report is a read-only roll-up of every research-os artifact for\n// a single section. It does not create new truth; it summarises existing\n// truth. The shape mirrors the workflow chain so a reader can follow the\n// section from gather → extract → density → contradict → review → gate\n// in one document.\n\nexport const SectionReportSourcesSchema = z.object({\n fetched_ok: z.number().int().nonnegative(),\n source_cards: z.number().int().nonnegative(),\n publishers: z.array(z.string()),\n primary_source_waiver: z.object({\n status: z.enum(['none', 'requested', 'granted']),\n reason: z.string().nullable(),\n compensating_controls: z.array(z.string()),\n }),\n});\n\nexport const SectionReportExtractionSchema = z.object({\n candidate_claims: z.number().int().nonnegative(),\n claims_per_source: z.array(\n z.object({\n source_id: z.string(),\n claims: z.number().int().nonnegative(),\n }),\n ),\n claims_per_1k_words: z.number(),\n excerpt_pages_processed: z.number().int().nonnegative().nullable(),\n excerpt_id_failures: z.number().int().nonnegative().nullable(),\n malformed_extractor_outputs: z.number().int().nonnegative().nullable(),\n near_duplicate_clusters: z.number().int().nonnegative(),\n weak_scope_count: z.number().int().nonnegative(),\n generic_scope_count: z.number().int().nonnegative(),\n density_flags: z.number().int().nonnegative(),\n});\n\nexport const SectionReportContradictionsSchema = z.object({\n pairs_compared: z.number().int().nonnegative().nullable(),\n contradiction_candidates: z.number().int().nonnegative(),\n overgeneralization_risks: z.number().int().nonnegative(),\n});\n\nexport const SectionReportReviewSchema = z.object({\n reviewed: z.boolean(),\n accepted_for_synthesis: z.number().int().nonnegative(),\n needs_scope_repair: z.number().int().nonnegative(),\n needs_source_repair: z.number().int().nonnegative(),\n needs_contradiction_mapping: z.number().int().nonnegative(),\n rejected: z.number().int().nonnegative(),\n needs_human_review: z.number().int().nonnegative(),\n rejection_or_repair_by_category: z.array(\n z.object({\n category: z.string(),\n count: z.number().int().nonnegative(),\n }),\n ),\n});\n\nexport const SectionReportAcceptanceSchema = z.object({\n candidate_claims: z.number().int().nonnegative(),\n accepted_for_synthesis: z.number().int().nonnegative(),\n acceptance_ratio: z.number(), // 0..1\n accepted_per_source: z.number(), // accepted / source_count, 0 if no sources\n accepted_per_1k_words: z.number(),\n top_rejection_category: z.string().nullable(),\n claim_overproduction_fired: z.boolean(),\n synthesis_ready: z.boolean(),\n});\n\nexport const SectionReportSchema = z.object({\n report_id: z.string().regex(/^secrep_[0-9]+_[a-z0-9-]+$/),\n section_id: z.string().regex(/^[0-9]{2}-[a-z0-9-]+$/),\n reported_at: z.string(),\n research_os_version: z.string(),\n status: z.string(),\n sources: SectionReportSourcesSchema,\n extraction: SectionReportExtractionSchema,\n contradictions: SectionReportContradictionsSchema,\n review: SectionReportReviewSchema,\n acceptance: SectionReportAcceptanceSchema,\n gate_verdict: z.string().nullable(),\n gate_synthesis_eligible: z.boolean().nullable(),\n});\n\nexport type SectionReport = z.infer<typeof SectionReportSchema>;\n","import { existsSync } from 'node:fs';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { join, resolve } from 'node:path';\nimport { parse as yamlParse } from 'yaml';\n\nimport { PackNotFoundError, SectionNotFoundError } from '../errors.js';\nimport { RESEARCH_OS_VERSION } from '../index.js';\nimport { ResearchYamlSchema } from '../intake/schema.js';\nimport {\n FetchReceiptSchema,\n SourceCardSchema,\n type FetchReceipt,\n type SourceCard,\n} from '../sources/schema.js';\nimport { ClaimSchema, type Claim } from '../claims/schema.js';\nimport { ContradictionSchema } from '../contradictions/schema.js';\nimport {\n ClaimReviewSchema,\n ReviewFindingSchema,\n type ClaimReview,\n} from '../review/schema.js';\nimport { SectionReportSchema, type SectionReport } from './schema.js';\n\nexport interface SectionReportOptions {\n sectionId: string;\n packPath?: string;\n now?: () => Date;\n}\n\nexport interface SectionReportResult {\n report: SectionReport;\n jsonPath: string;\n markdownPath: string;\n}\n\nasync function readJson<T>(path: string, parser: (raw: unknown) => T): Promise<T | null> {\n if (!existsSync(path)) return null;\n try {\n return parser(JSON.parse(await readFile(path, 'utf8')));\n } catch {\n return null;\n }\n}\n\nasync function readJsonl<T>(path: string, parse: (raw: unknown) => T): Promise<T[]> {\n if (!existsSync(path)) return [];\n const text = await readFile(path, 'utf8');\n const out: T[] = [];\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n out.push(parse(JSON.parse(line)));\n } catch {\n /* skip malformed line */\n }\n }\n return out;\n}\n\nfunction countWords(text: string | null | undefined): number {\n if (!text) return 0;\n return text\n .replace(/<[^>]+>/g, ' ')\n .replace(/\\s+/g, ' ')\n .trim()\n .split(' ')\n .filter((w) => w.length > 0).length;\n}\n\nexport async function reportSection(\n options: SectionReportOptions,\n): Promise<SectionReportResult> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n if (!existsSync(join(packPath, 'research.yaml'))) throw new PackNotFoundError(packPath);\n if (!existsSync(join(packPath, 'sections', options.sectionId)))\n throw new SectionNotFoundError(options.sectionId);\n\n const research = ResearchYamlSchema.parse(\n yamlParse(await readFile(join(packPath, 'research.yaml'), 'utf8')),\n );\n const section = research.sections.find((s) => s.id === options.sectionId);\n\n // Sources & receipts.\n const allReceipts = await readJsonl(join(packPath, 'evidence', 'fetch-log.jsonl'), (raw) =>\n FetchReceiptSchema.parse(raw),\n );\n const okReceipts = new Map<string, FetchReceipt>();\n for (const r of allReceipts) {\n if (r.section_id !== options.sectionId) continue;\n if (r.fetch_outcome !== 'ok') continue;\n const prev = okReceipts.get(r.source_id);\n if (!prev || prev.fetched_at < r.fetched_at) okReceipts.set(r.source_id, r);\n }\n const sectionSourceIds: string[] = [];\n const sourcesPath = join(packPath, 'sections', options.sectionId, 'sources.jsonl');\n if (existsSync(sourcesPath)) {\n const text = await readFile(sourcesPath, 'utf8');\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n const obj = JSON.parse(line) as { source_id?: string };\n if (obj.source_id) sectionSourceIds.push(obj.source_id);\n } catch {\n /* skip */\n }\n }\n }\n const cards = new Map<string, SourceCard>();\n for (const sid of sectionSourceIds) {\n const cardPath = join(packPath, 'evidence', 'source-cards', `${sid}.json`);\n if (!existsSync(cardPath)) continue;\n try {\n cards.set(sid, SourceCardSchema.parse(JSON.parse(await readFile(cardPath, 'utf8'))));\n } catch {\n /* skip */\n }\n }\n const publishers = Array.from(\n new Set(Array.from(cards.values()).map((c) => c.publisher).filter((p): p is string => !!p)),\n ).sort();\n\n // Total raw-text word count for this section.\n let totalWords = 0;\n for (const sid of sectionSourceIds) {\n const r = okReceipts.get(sid);\n if (!r?.raw_text_path) continue;\n const p = join(packPath, r.raw_text_path);\n if (!existsSync(p)) continue;\n totalWords += countWords(await readFile(p, 'utf8'));\n }\n\n // Claims.\n const claims = await readJsonl(\n join(packPath, 'sections', options.sectionId, 'claims.jsonl'),\n (raw) => ClaimSchema.parse(raw),\n );\n const claimsBySrc = new Map<string, Claim[]>();\n for (const c of claims) {\n for (const sid of c.source_ids) {\n const arr = claimsBySrc.get(sid) ?? [];\n arr.push(c);\n claimsBySrc.set(sid, arr);\n }\n }\n\n // Density audit (if it exists).\n const density = await readJson(\n join(packPath, 'audits', `${options.sectionId}-claim-density.json`),\n (raw) => raw as Record<string, unknown>,\n );\n\n // Extract receipt (if it exists).\n const extractReceipt = await readJson(\n join(packPath, 'audits', `${options.sectionId}-claim-extract.json`),\n (raw) => raw as Record<string, unknown>,\n );\n\n // Excerpt ledgers (so we can count pages even without an extract receipt).\n let excerptPagesProcessed: number | null = null;\n if (extractReceipt && typeof extractReceipt.excerpt_ledgers_built === 'number') {\n excerptPagesProcessed = extractReceipt.excerpt_ledgers_built as number;\n }\n let excerptIdFailures: number | null = null;\n if (extractReceipt && typeof extractReceipt.claims_rejected_excerpt_id_missing === 'number') {\n excerptIdFailures =\n (extractReceipt.claims_rejected_excerpt_id_missing as number) +\n ((extractReceipt.claims_rejected_excerpt_id_malformed as number) ?? 0);\n }\n let malformedOutputs: number | null = null;\n if (extractReceipt && Array.isArray(extractReceipt.failures)) {\n malformedOutputs = (extractReceipt.failures as Array<{ kind?: string }>).filter(\n (f) => f.kind === 'extractor_invalid_json',\n ).length;\n }\n\n // Contradictions.\n const contradictions = await readJsonl(\n join(packPath, 'sections', options.sectionId, 'contradictions.jsonl'),\n (raw) => ContradictionSchema.parse(raw),\n );\n let pairsCompared: number | null = null;\n if (claims.length > 1) pairsCompared = (claims.length * (claims.length - 1)) / 2;\n const overgeneralizationRisks = contradictions.filter(\n (c) => c.type === 'overgeneralization_risk',\n ).length;\n\n // Review.\n const reviews = await readJsonl(\n join(packPath, 'sections', options.sectionId, 'claim-reviews.jsonl'),\n (raw) => ClaimReviewSchema.parse(raw),\n );\n // For each claim, take the LATEST review (append-only ledger).\n const latestReviewByClaim = new Map<string, ClaimReview>();\n for (const r of reviews) {\n const prev = latestReviewByClaim.get(r.claim_id);\n if (!prev || prev.created_at < r.created_at) latestReviewByClaim.set(r.claim_id, r);\n }\n const findings = await readJsonl(\n join(packPath, 'audits', `${options.sectionId}-findings.jsonl`),\n (raw) => ReviewFindingSchema.parse(raw),\n );\n\n const decisionCounts = {\n accepted_for_synthesis: 0,\n needs_scope_repair: 0,\n needs_source_repair: 0,\n needs_contradiction_mapping: 0,\n rejected: 0,\n needs_human_review: 0,\n };\n for (const claim of claims) {\n const r = latestReviewByClaim.get(claim.claim_id);\n if (!r) continue;\n decisionCounts[r.decision] += 1;\n }\n // Tally finding categories that produced non-accept decisions.\n const categoryCounts = new Map<string, number>();\n for (const f of findings) {\n if (f.severity === 'info') continue;\n categoryCounts.set(f.category, (categoryCounts.get(f.category) ?? 0) + 1);\n }\n const rejectionByCategory = Array.from(categoryCounts.entries())\n .map(([category, count]) => ({ category, count }))\n .sort((a, b) => b.count - a.count);\n const topRejectionCategory = rejectionByCategory[0]?.category ?? null;\n const claimOverproductionFired = (categoryCounts.get('claim_overproduction') ?? 0) > 0;\n\n // Gate verdict.\n const gate = await readJson(\n join(packPath, 'audits', `${options.sectionId}-gate.json`),\n (raw) => raw as Record<string, unknown>,\n );\n\n const candidate = claims.length;\n const accepted = decisionCounts.accepted_for_synthesis;\n const acceptanceRatio = candidate > 0 ? accepted / candidate : 0;\n const acceptedPerSource = sectionSourceIds.length > 0 ? accepted / sectionSourceIds.length : 0;\n const acceptedPer1kWords = totalWords > 0 ? (accepted / totalWords) * 1000 : 0;\n const synthesisReady =\n typeof gate?.synthesis_eligible === 'boolean' ? gate.synthesis_eligible : false;\n\n const stamp = (options.now ?? (() => new Date()))();\n\n const report: SectionReport = SectionReportSchema.parse({\n report_id: `secrep_${stamp.getTime()}_${options.sectionId}`,\n section_id: options.sectionId,\n reported_at: stamp.toISOString(),\n research_os_version: RESEARCH_OS_VERSION,\n status: section?.status ?? 'unknown',\n sources: {\n fetched_ok: okReceipts.size,\n source_cards: cards.size,\n publishers,\n primary_source_waiver: {\n status: research.primary_source_waiver.status,\n reason: research.primary_source_waiver.reason ?? null,\n compensating_controls: research.primary_source_waiver.compensating_controls,\n },\n },\n extraction: {\n candidate_claims: candidate,\n claims_per_source: Array.from(claimsBySrc.entries())\n .map(([source_id, cs]) => ({ source_id, claims: cs.length }))\n .sort((a, b) => b.claims - a.claims),\n claims_per_1k_words: totalWords > 0 ? (candidate / totalWords) * 1000 : 0,\n excerpt_pages_processed: excerptPagesProcessed,\n excerpt_id_failures: excerptIdFailures,\n malformed_extractor_outputs: malformedOutputs,\n near_duplicate_clusters:\n density && Array.isArray((density as { near_duplicate_clusters?: unknown[] }).near_duplicate_clusters)\n ? ((density as { near_duplicate_clusters: unknown[] }).near_duplicate_clusters).length\n : 0,\n weak_scope_count:\n density && typeof (density as { weak_scope_count?: number }).weak_scope_count === 'number'\n ? ((density as { weak_scope_count: number }).weak_scope_count)\n : 0,\n generic_scope_count:\n density && typeof (density as { generic_scope_count?: number }).generic_scope_count === 'number'\n ? ((density as { generic_scope_count: number }).generic_scope_count)\n : 0,\n density_flags:\n density && Array.isArray((density as { flags?: unknown[] }).flags)\n ? ((density as { flags: unknown[] }).flags).length\n : 0,\n },\n contradictions: {\n pairs_compared: pairsCompared,\n contradiction_candidates: contradictions.length,\n overgeneralization_risks: overgeneralizationRisks,\n },\n review: {\n reviewed: latestReviewByClaim.size > 0,\n accepted_for_synthesis: decisionCounts.accepted_for_synthesis,\n needs_scope_repair: decisionCounts.needs_scope_repair,\n needs_source_repair: decisionCounts.needs_source_repair,\n needs_contradiction_mapping: decisionCounts.needs_contradiction_mapping,\n rejected: decisionCounts.rejected,\n needs_human_review: decisionCounts.needs_human_review,\n rejection_or_repair_by_category: rejectionByCategory,\n },\n acceptance: {\n candidate_claims: candidate,\n accepted_for_synthesis: accepted,\n acceptance_ratio: acceptanceRatio,\n accepted_per_source: acceptedPerSource,\n accepted_per_1k_words: acceptedPer1kWords,\n top_rejection_category: topRejectionCategory,\n claim_overproduction_fired: claimOverproductionFired,\n synthesis_ready: synthesisReady,\n },\n gate_verdict: typeof gate?.verdict === 'string' ? (gate.verdict as string) : null,\n gate_synthesis_eligible:\n typeof gate?.synthesis_eligible === 'boolean'\n ? (gate.synthesis_eligible as boolean)\n : null,\n });\n\n // Markdown render — exact shape from the user's spec.\n const md: string[] = [];\n md.push(`# Section ${report.section_id}`);\n md.push('');\n md.push(`- **Status:** ${report.status}`);\n md.push(`- **Reported at:** ${report.reported_at}`);\n md.push(`- **Report ID:** \\`${report.report_id}\\``);\n md.push('');\n md.push('## Sources');\n md.push('');\n md.push(`- fetched: ${report.sources.fetched_ok}`);\n md.push(`- source cards: ${report.sources.source_cards}`);\n md.push(`- publishers: ${report.sources.publishers.length === 0 ? '(none)' : report.sources.publishers.join(', ')}`);\n md.push(`- primary-source waiver: ${report.sources.primary_source_waiver.status}${report.sources.primary_source_waiver.reason ? ` — ${report.sources.primary_source_waiver.reason.slice(0, 200)}` : ''}`);\n md.push('');\n md.push('## Extraction');\n md.push('');\n md.push(`- candidate claims: ${report.extraction.candidate_claims}`);\n md.push(`- claims per source: ${report.extraction.claims_per_source.map((s) => `${s.source_id}=${s.claims}`).join(', ') || '(none)'}`);\n md.push(`- claims per 1k words: ${report.extraction.claims_per_1k_words.toFixed(2)}`);\n md.push(`- excerpt pages processed: ${report.extraction.excerpt_pages_processed ?? 'n/a'}`);\n md.push(`- excerpt-id failures: ${report.extraction.excerpt_id_failures ?? 'n/a'}`);\n md.push(`- malformed extractor outputs: ${report.extraction.malformed_extractor_outputs ?? 'n/a'}`);\n md.push(`- duplicate / near-duplicate clusters: ${report.extraction.near_duplicate_clusters}`);\n md.push(`- weak-scope claims: ${report.extraction.weak_scope_count}`);\n md.push(`- generic-scope claims: ${report.extraction.generic_scope_count}`);\n md.push(`- density flags: ${report.extraction.density_flags}`);\n md.push('');\n md.push('## Contradictions');\n md.push('');\n md.push(`- pairs compared: ${report.contradictions.pairs_compared ?? 'n/a'}`);\n md.push(`- contradiction candidates: ${report.contradictions.contradiction_candidates}`);\n md.push(`- overgeneralization risks: ${report.contradictions.overgeneralization_risks}`);\n md.push('');\n md.push('## Review');\n md.push('');\n if (!report.review.reviewed) {\n md.push('_Review has not run for this section yet._');\n } else {\n md.push(`- accepted_for_synthesis: ${report.review.accepted_for_synthesis}`);\n md.push(`- needs_scope_repair: ${report.review.needs_scope_repair}`);\n md.push(`- needs_source_repair: ${report.review.needs_source_repair}`);\n md.push(`- rejected: ${report.review.rejected}`);\n md.push(`- needs_human_review: ${report.review.needs_human_review}`);\n md.push(`- needs_contradiction_mapping: ${report.review.needs_contradiction_mapping}`);\n md.push('');\n md.push('### Rejection / repair by category');\n md.push('');\n if (report.review.rejection_or_repair_by_category.length === 0) {\n md.push('_No non-info findings recorded._');\n } else {\n md.push('| Category | Count |');\n md.push('|---|---:|');\n for (const r of report.review.rejection_or_repair_by_category) {\n md.push(`| \\`${r.category}\\` | ${r.count} |`);\n }\n }\n }\n md.push('');\n md.push('## Acceptance');\n md.push('');\n md.push(`- acceptance ratio: ${(report.acceptance.acceptance_ratio * 100).toFixed(1)}% (${report.acceptance.accepted_for_synthesis} / ${report.acceptance.candidate_claims})`);\n md.push(`- accepted per source: ${report.acceptance.accepted_per_source.toFixed(2)}`);\n md.push(`- accepted per 1k source words: ${report.acceptance.accepted_per_1k_words.toFixed(2)}`);\n md.push(`- top rejection category: ${report.acceptance.top_rejection_category ?? 'none'}`);\n md.push(`- claim_overproduction fired: ${report.acceptance.claim_overproduction_fired ? 'yes' : 'no'}`);\n md.push(`- synthesis ready: ${report.acceptance.synthesis_ready ? 'yes' : 'no'}`);\n md.push('');\n md.push('---');\n md.push('');\n md.push('_This report is read-only — it does not mutate any canonical artifact. Re-run after any pipeline step to refresh._');\n\n const auditsDir = join(packPath, 'audits');\n await mkdir(auditsDir, { recursive: true });\n const jsonPath = join(auditsDir, `${options.sectionId}-section-report.json`);\n const markdownPath = join(auditsDir, `${options.sectionId}-section-report.md`);\n await writeFile(jsonPath, JSON.stringify(report, null, 2), 'utf8');\n await writeFile(markdownPath, md.join('\\n'), 'utf8');\n return { report, jsonPath, markdownPath };\n}\n","export { reportSection, type SectionReportOptions, type SectionReportResult } from './run.js';\nexport {\n SectionReportSchema,\n SectionReportSourcesSchema,\n SectionReportExtractionSchema,\n SectionReportContradictionsSchema,\n SectionReportReviewSchema,\n SectionReportAcceptanceSchema,\n type SectionReport,\n} from './schema.js';\n","#!/usr/bin/env node\nimport { Command, Option } from 'commander';\nimport { init } from './intake/index.js';\nimport { add as sectionAdd } from './sections/index.js';\nimport { reportSection } from './section_report/index.js';\nimport { gather } from './sources/index.js';\nimport {\n discover as runDiscover,\n approve as discoverApprove,\n reject as discoverReject,\n exportUrls as discoverExport,\n} from './discover/index.js';\nimport { auditDensity, extract as claimExtract } from './claims/index.js';\nimport { triage as runTriage } from './triage/index.js';\nimport { map as contradictMap, resolve as contradictResolve } from './contradictions/index.js';\nimport { gate as runGate } from './gates/index.js';\nimport {\n DEFAULT_PROFILE,\n HeuristicReviewer,\n OllamaInternReviewer,\n promote as runPromote,\n review as runReview,\n} from './review/index.js';\nimport {\n build as indexBuild,\n query as indexQuery,\n exportRepoKnowledge,\n syncRepoKnowledge,\n} from './indexer/index.js';\nimport { handoff as coworkHandoff } from './cowork/index.js';\nimport { workspace as synthWorkspace } from './synth/index.js';\nimport { audit as runAudit } from './audit/index.js';\nimport { freeze as runFreeze } from './freeze/index.js';\nimport { invalidateExtraction, invalidateReview } from './invalidate/index.js';\nimport { publish as packPublish } from './pack/publish/index.js';\nimport { ResearchOSError } from './errors.js';\nimport { RESEARCH_OS_VERSION } from './index.js';\n\nfunction reportError(err: unknown): never {\n if (err instanceof ResearchOSError) {\n process.stderr.write(`research-os: ${err.code}: ${err.message}\\n`);\n if (err.hint) process.stderr.write(` hint: ${err.hint}\\n`);\n } else if (err instanceof Error) {\n process.stderr.write(`research-os: ${err.message}\\n`);\n } else {\n process.stderr.write(`research-os: unknown error\\n`);\n }\n process.exit(1);\n}\n\nconst program = new Command();\n\nprogram\n .name('research-os')\n .description('Local-first research control plane for gated source packs and long-running AI synthesis')\n .version(RESEARCH_OS_VERSION);\n\nprogram\n .command('init')\n .description('Create a new research-pack from a topic')\n .argument('<topic>', 'The research question or topic statement')\n .option('-n, --name <slug>', 'Pack directory name (defaults to a slug of the topic)')\n .option('-o, --out <dir>', 'Parent directory in which to create the pack', process.cwd())\n .option('-d, --decision <text>', 'What decision this research informs')\n .option('-a, --audience <text>', 'Who consumes the output', 'self')\n .option('--desired-output <text>', 'Shape of the final artifact')\n .option('--max-runtime-minutes <n>', 'Total runtime budget for the pack', (v) => parseInt(v, 10), 240)\n .option('--force', 'Overwrite an existing pack directory')\n .action(async (topic: string, opts) => {\n try {\n const result = await init({\n topic,\n name: opts.name,\n outDir: opts.out,\n decision: opts.decision,\n audience: opts.audience,\n desiredOutput: opts.desiredOutput,\n maxRuntimeMinutes: opts.maxRuntimeMinutes,\n force: opts.force,\n });\n process.stdout.write(`research-pack created\\n`);\n process.stdout.write(` name: ${result.packName}\\n`);\n process.stdout.write(` path: ${result.packPath}\\n`);\n process.stdout.write(` files: ${result.filesWritten.length}\\n`);\n } catch (err) {\n reportError(err);\n }\n });\n\nconst sectionCmd = program\n .command('section')\n .description('Manage sections inside a research-pack');\n\nsectionCmd\n .command('add')\n .description('Add a new section to the pack')\n .argument('<id>', 'Section id, e.g. \"01-landscape\"')\n .requiredOption('--purpose <text>', 'What this section investigates')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .option('--max-time <n>', 'Section time budget in minutes', (v) => parseInt(v, 10))\n .option('--min-sources <n>', 'Minimum sources required for this section', (v) => parseInt(v, 10))\n .option('--primary-required <n>', 'Primary sources required for this section', (v) => parseInt(v, 10))\n .action(async (id: string, opts) => {\n try {\n const result = await sectionAdd({\n id,\n purpose: opts.purpose,\n packPath: opts.pack,\n maxTimeMinutes: opts.maxTime,\n minSources: opts.minSources,\n primarySourcesRequired: opts.primaryRequired,\n });\n process.stdout.write(`section added\\n`);\n process.stdout.write(` id: ${result.sectionId}\\n`);\n process.stdout.write(` path: ${result.sectionPath}\\n`);\n process.stdout.write(` files: ${result.filesWritten.length}\\n`);\n } catch (err) {\n reportError(err);\n }\n });\n\nsectionCmd\n .command('report')\n .description(\n 'Read-only section roll-up: sources, extraction, contradictions, review, acceptance ratio',\n )\n .argument('<section>', 'Section id, e.g. \"03-source-and-claim-truth\"')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .action(async (section: string, opts) => {\n try {\n const { report, jsonPath, markdownPath } = await reportSection({\n sectionId: section,\n packPath: opts.pack,\n });\n process.stdout.write(`section report: ${report.section_id}\\n`);\n process.stdout.write(` status: ${report.status}\\n`);\n process.stdout.write(`Sources\\n`);\n process.stdout.write(` fetched: ${report.sources.fetched_ok}\\n`);\n process.stdout.write(` source cards: ${report.sources.source_cards}\\n`);\n process.stdout.write(` publishers: ${report.sources.publishers.length}\\n`);\n process.stdout.write(` primary-source waiver: ${report.sources.primary_source_waiver.status}\\n`);\n process.stdout.write(`Extraction\\n`);\n process.stdout.write(` candidate claims: ${report.extraction.candidate_claims}\\n`);\n process.stdout.write(` claims per 1k words: ${report.extraction.claims_per_1k_words.toFixed(2)}\\n`);\n process.stdout.write(` excerpt pages processed: ${report.extraction.excerpt_pages_processed ?? 'n/a'}\\n`);\n process.stdout.write(` excerpt-id failures: ${report.extraction.excerpt_id_failures ?? 'n/a'}\\n`);\n process.stdout.write(` malformed extractor: ${report.extraction.malformed_extractor_outputs ?? 'n/a'}\\n`);\n process.stdout.write(` near-duplicate clusters: ${report.extraction.near_duplicate_clusters}\\n`);\n process.stdout.write(`Contradictions\\n`);\n process.stdout.write(` pairs compared: ${report.contradictions.pairs_compared ?? 'n/a'}\\n`);\n process.stdout.write(` contradiction candidates: ${report.contradictions.contradiction_candidates}\\n`);\n process.stdout.write(` overgeneralization risks: ${report.contradictions.overgeneralization_risks}\\n`);\n process.stdout.write(`Review\\n`);\n if (!report.review.reviewed) {\n process.stdout.write(` (not reviewed yet)\\n`);\n } else {\n process.stdout.write(` accepted_for_synthesis: ${report.review.accepted_for_synthesis}\\n`);\n process.stdout.write(` needs_scope_repair: ${report.review.needs_scope_repair}\\n`);\n process.stdout.write(` needs_source_repair: ${report.review.needs_source_repair}\\n`);\n process.stdout.write(` rejected: ${report.review.rejected}\\n`);\n process.stdout.write(` needs_human_review: ${report.review.needs_human_review}\\n`);\n }\n process.stdout.write(`Acceptance\\n`);\n process.stdout.write(` ratio: ${(report.acceptance.acceptance_ratio * 100).toFixed(1)}% (${report.acceptance.accepted_for_synthesis} / ${report.acceptance.candidate_claims})\\n`);\n process.stdout.write(` accepted per source: ${report.acceptance.accepted_per_source.toFixed(2)}\\n`);\n process.stdout.write(` accepted per 1k words: ${report.acceptance.accepted_per_1k_words.toFixed(2)}\\n`);\n process.stdout.write(` top rejection category: ${report.acceptance.top_rejection_category ?? 'none'}\\n`);\n process.stdout.write(` claim_overproduction: ${report.acceptance.claim_overproduction_fired ? 'yes' : 'no'}\\n`);\n process.stdout.write(` synthesis ready: ${report.acceptance.synthesis_ready ? 'yes' : 'no'}\\n`);\n process.stdout.write(` json: ${jsonPath}\\n`);\n process.stdout.write(` markdown: ${markdownPath}\\n`);\n } catch (err) {\n reportError(err);\n }\n });\n\nprogram\n .command('gather')\n .description('Acquire known sources for a section: direct fetch + extraction')\n .argument('<section>', 'Section id, e.g. \"01-landscape\"')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .option('--url <url>', 'A URL to fetch (repeatable)', (value: string, prev: string[] = []) => {\n prev.push(value);\n return prev;\n })\n .option('--urls-file <path>', 'File of URLs, one per line; blank lines and # comments allowed')\n .option(\n '--approved',\n 'Read URLs from sections/<id>/urls.approved.txt (produced by `research-os discover approve` / `discover export-urls`)',\n false,\n )\n .action(async (section: string, opts) => {\n try {\n let urlsFile = opts.urlsFile as string | undefined;\n if (opts.approved) {\n const path = await import('node:path');\n const candidate = path.join(opts.pack as string, 'sections', section, 'urls.approved.txt');\n urlsFile = urlsFile ?? candidate;\n }\n const result = await gather({\n sectionId: section,\n packPath: opts.pack,\n urls: opts.url,\n urlsFile,\n });\n process.stdout.write(`gather complete\\n`);\n process.stdout.write(` section: ${result.sectionId}\\n`);\n process.stdout.write(` attempted: ${result.attempted}\\n`);\n process.stdout.write(` fetched ok: ${result.fetchedOk}\\n`);\n process.stdout.write(` fetched failed: ${result.fetchedFailed}\\n`);\n process.stdout.write(` extracted ok: ${result.extractedOk}\\n`);\n process.stdout.write(` extracted failed: ${result.extractedFailed}\\n`);\n process.stdout.write(` cards written: ${result.cardsWritten}\\n`);\n process.stdout.write(` receipts appended: ${result.receiptsAppended}\\n`);\n } catch (err) {\n reportError(err);\n }\n });\n\nconst discoverCmd = program\n .command('discover')\n .description(\n 'Propose source URL candidates for a section. Discovery results are LEADS, not evidence — only fetch + receipt + source card make a URL evidence.',\n );\n\ndiscoverCmd\n .command('run')\n .description('Run a discover query against a section, append candidates to the ledger, render report')\n .argument('<section>', 'Section id, e.g. \"04-gates-and-waivers\"')\n .requiredOption('--query <text>', 'Free-text query to ask the discover provider')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .option('--target <n>', 'Soft target candidate count', (v) => parseInt(v, 10), 12)\n .action(async (section: string, opts) => {\n try {\n const result = await runDiscover({\n sectionId: section,\n packPath: opts.pack,\n query: opts.query,\n targetCount: opts.target,\n });\n process.stdout.write(`discover complete\\n`);\n process.stdout.write(` section: ${section}\\n`);\n process.stdout.write(` candidates proposed: ${result.candidatesProposed}\\n`);\n process.stdout.write(` candidates added: ${result.candidatesAdded}\\n`);\n process.stdout.write(` invalid url rejected: ${result.candidatesRejectedInvalidUrl}\\n`);\n process.stdout.write(` candidates ledger: ${result.candidatesPath}\\n`);\n process.stdout.write(` report: ${result.reportPath}\\n`);\n process.stdout.write(` summary: ${result.summaryPath}\\n`);\n if (result.warnings.length > 0) {\n process.stdout.write(`\\nwarnings:\\n`);\n for (const w of result.warnings) process.stdout.write(` - ${w}\\n`);\n }\n } catch (err) {\n reportError(err);\n }\n });\n\ndiscoverCmd\n .command('approve')\n .description('Approve discovered candidates so gather --approved will fetch them')\n .argument('<section>', 'Section id')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .option(\n '--candidate <id>',\n 'Candidate id (repeatable)',\n (v: string, prev: string[] = []) => {\n prev.push(v);\n return prev;\n },\n )\n .option('--top <n>', 'Approve the top N candidates by rank', (v) => parseInt(v, 10))\n .option('--reason <text>', 'Optional reason recorded on the status update')\n .action(async (section: string, opts) => {\n try {\n const result = await discoverApprove({\n sectionId: section,\n packPath: opts.pack,\n candidateIds: opts.candidate,\n topN: opts.top,\n reason: opts.reason,\n });\n process.stdout.write(`discover approve\\n`);\n process.stdout.write(` approved: ${result.approved}\\n`);\n for (const id of result.approvedIds) process.stdout.write(` - ${id}\\n`);\n process.stdout.write(` exported: ${result.exportPath}\\n`);\n } catch (err) {\n reportError(err);\n }\n });\n\ndiscoverCmd\n .command('reject')\n .description('Reject discovered candidates with a recorded reason')\n .argument('<section>', 'Section id')\n .requiredOption(\n '--candidate <id>',\n 'Candidate id (repeatable)',\n (v: string, prev: string[] = []) => {\n prev.push(v);\n return prev;\n },\n )\n .requiredOption('--reason <text>', 'Reason recorded on the status update')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .action(async (section: string, opts) => {\n try {\n const result = await discoverReject({\n sectionId: section,\n packPath: opts.pack,\n candidateIds: opts.candidate,\n reason: opts.reason,\n });\n process.stdout.write(`discover reject\\n`);\n process.stdout.write(` rejected: ${result.rejected}\\n`);\n for (const id of result.rejectedIds) process.stdout.write(` - ${id}\\n`);\n } catch (err) {\n reportError(err);\n }\n });\n\ndiscoverCmd\n .command('export-urls')\n .description('Re-export sections/<id>/urls.approved.txt from the latest approved candidates')\n .argument('<section>', 'Section id')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .action(async (section: string, opts) => {\n try {\n const result = await discoverExport({\n sectionId: section,\n packPath: opts.pack,\n });\n process.stdout.write(`discover export-urls\\n`);\n process.stdout.write(` approved count: ${result.approvedCount}\\n`);\n process.stdout.write(` export path: ${result.exportPath}\\n`);\n } catch (err) {\n reportError(err);\n }\n });\n\nconst claimCmd = program\n .command('claim')\n .description('Manage claims extracted from gathered sources');\n\nclaimCmd\n .command('extract')\n .description('Extract candidate claims from a section\\'s gathered sources')\n .argument('<section>', 'Section id, e.g. \"01-landscape\"')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .action(async (section: string, opts) => {\n try {\n const result = await claimExtract({\n sectionId: section,\n packPath: opts.pack,\n });\n process.stdout.write(`claim extraction complete\\n`);\n process.stdout.write(` section: ${result.sectionId}\\n`);\n process.stdout.write(` extractor: ${result.extractor}\\n`);\n process.stdout.write(` method: ${result.extractionMethod}\\n`);\n process.stdout.write(` sources processed: ${result.sourcesProcessed}\\n`);\n process.stdout.write(` sources skipped: ${result.sourcesSkipped}\\n`);\n process.stdout.write(` sources failed: ${result.sourcesFailed}\\n`);\n process.stdout.write(` excerpt ledgers built: ${result.excerptLedgersBuilt}\\n`);\n process.stdout.write(` claims added: ${result.claimsAdded}\\n`);\n process.stdout.write(` claims deduped: ${result.claimsDeduped}\\n`);\n process.stdout.write(` claims rejected (total ungrounded): ${result.claimsRejectedUngrounded}\\n`);\n // Span-first taxonomy: precise rejection categories. Others\n // (unsupported_claim / scope_missing / scope_widening / cross_source_contam)\n // are reviewer concerns and surface in the review step, not here.\n process.stdout.write(` excerpt_id_missing: ${result.claimsRejectedExcerptIdMissing}\\n`);\n process.stdout.write(` excerpt_id_malformed: ${result.claimsRejectedExcerptIdMalformed}\\n`);\n if (result.failures.length > 0) {\n process.stdout.write(`\\nfailures:\\n`);\n for (const f of result.failures) {\n // Annotate JSON-parse failures so they're visibly distinct from\n // network/transport errors.\n const tag = /not valid JSON/i.test(f.reason) ? '[extractor_invalid_json] ' : '';\n process.stdout.write(` ${f.source_id}: ${tag}${f.reason}\\n`);\n }\n }\n } catch (err) {\n reportError(err);\n }\n });\n\nclaimCmd\n .command('triage')\n .description(\n 'Shape candidate claims before review: dedupe, cap per-source contribution, park weak-scope/low-value claims. Read-only on claims.jsonl.',\n )\n .argument('<section>', 'Section id, e.g. \"03-source-and-claim-truth\"')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .option('--per-source-cap <n>', 'Max claims per source forwarded to review', (v) => parseInt(v, 10), 10)\n .option('--min-assert-chars <n>', 'Asserts shorter than this become parked_low_value', (v) => parseInt(v, 10), 30)\n .action(async (section: string, opts) => {\n try {\n const result = await runTriage({\n sectionId: section,\n packPath: opts.pack,\n perSourceCap: opts.perSourceCap,\n minAssertChars: opts.minAssertChars,\n });\n process.stdout.write(`claim triage complete\\n`);\n process.stdout.write(` section: ${section}\\n`);\n process.stdout.write(` candidate claims: ${result.candidateClaims}\\n`);\n process.stdout.write(` selected_for_review: ${result.selectedCount}\\n`);\n process.stdout.write(` parked (total): ${result.parkedCount}\\n`);\n process.stdout.write(` needs_repair (total): ${result.needsRepairCount}\\n`);\n process.stdout.write(`\\ndecisions:\\n`);\n for (const [d, n] of Object.entries(result.decisions)) {\n process.stdout.write(` ${d}: ${n}\\n`);\n }\n process.stdout.write(`\\n triage jsonl: ${result.triageJsonlPath}\\n`);\n process.stdout.write(` triage markdown: ${result.triageMarkdownPath}\\n`);\n process.stdout.write(` summary json: ${result.summaryJsonPath}\\n`);\n } catch (err) {\n reportError(err);\n }\n });\n\nclaimCmd\n .command('audit-density')\n .description(\n 'Read-only diagnostic of a section claim ledger before review: claims/source, claims per 1k words, near-duplicate clusters, weak/generic scope',\n )\n .argument('<section>', 'Section id, e.g. \"03-source-and-claim-truth\"')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .action(async (section: string, opts) => {\n try {\n const result = await auditDensity({\n sectionId: section,\n packPath: opts.pack,\n });\n const a = result.audit;\n process.stdout.write(`claim density audit complete\\n`);\n process.stdout.write(` section: ${a.section_id}\\n`);\n process.stdout.write(` candidate claims: ${a.candidate_claim_count}\\n`);\n process.stdout.write(` sources: ${a.source_count}\\n`);\n process.stdout.write(` source word total: ${a.total_source_word_count.toLocaleString()}\\n`);\n process.stdout.write(` claims per 1k words: ${a.claims_per_1k_words.toFixed(2)}\\n`);\n process.stdout.write(` weak-scope claims: ${a.weak_scope_count}\\n`);\n process.stdout.write(` generic-scope claims: ${a.generic_scope_count}\\n`);\n process.stdout.write(` near-duplicate clusters:${a.near_duplicate_clusters.length}\\n`);\n process.stdout.write(` flags: ${a.flags.length}\\n`);\n for (const f of a.flags) {\n process.stdout.write(` [${f.severity}] ${f.type}: ${f.message}\\n`);\n }\n process.stdout.write(` json: ${result.jsonPath}\\n`);\n process.stdout.write(` markdown: ${result.markdownPath}\\n`);\n } catch (err) {\n reportError(err);\n }\n });\n\nconst contradictCmd = program\n .command('contradict')\n .description('Map tensions between candidate claims');\n\ncontradictCmd\n .command('map')\n .description('Detect contradiction candidates among a section\\'s candidate claims')\n .argument('<section>', 'Section id, e.g. \"01-landscape\"')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .option(\n '--triaged-only',\n 'Only consider claims that triage selected_for_review; reduces N² pair classification on dense sections',\n false,\n )\n .addOption(\n new Option(\n '--detector <mode>',\n 'Detector to use: auto (default, env-var-driven), heuristic (always fast, no LLM), ollama-intern (require LLM, fail visibly if unavailable)',\n )\n .choices(['auto', 'heuristic', 'ollama-intern'])\n .default('auto'),\n )\n .action(async (section: string, opts) => {\n try {\n const result = await contradictMap({\n sectionId: section,\n packPath: opts.pack,\n triagedOnly: opts.triagedOnly,\n detectorMode: opts.detector,\n });\n process.stdout.write(`${result.detectorAnnouncement}\\n`);\n process.stdout.write(`contradiction map complete\\n`);\n process.stdout.write(` section: ${result.sectionId}\\n`);\n process.stdout.write(` detector: ${result.detector}\\n`);\n process.stdout.write(` method: ${result.detectionMethod}\\n`);\n process.stdout.write(` candidate claims: ${result.candidateClaims}\\n`);\n process.stdout.write(` pairs compared: ${result.pairsCompared}\\n`);\n process.stdout.write(` contradictions added: ${result.contradictionsAdded}\\n`);\n process.stdout.write(` contradictions deduped: ${result.contradictionsDeduped}\\n`);\n if (result.detectorError) {\n process.stdout.write(`\\ndetector error: ${result.detectorError}\\n`);\n }\n } catch (err) {\n reportError(err);\n }\n });\n\ncontradictCmd\n .command('resolve')\n .description('Record resolution status for contradiction candidates in a section')\n .argument('<section>', 'Section id, e.g. \"08-acceptance-suite\"')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .option(\n '--id <id>',\n 'Contradiction ID to resolve (repeatable)',\n (v: string, prev: string[] = []) => { prev.push(v); return prev; },\n )\n .option('--all', 'Resolve all currently-unresolved contradictions in the section', false)\n .requiredOption('--status <status>', 'Resolution status: resolved, preserved, or rejected')\n .requiredOption('--reason <text>', 'Reason for this resolution (min 4 chars)')\n .option('--by <identifier>', 'Who resolved it (recorded in ledger)', 'operator')\n .action(async (section: string, opts) => {\n try {\n if (!opts.all && (!opts.id || opts.id.length === 0)) {\n process.stderr.write('research-os: must provide --id <id> (repeatable) or --all\\n');\n process.exit(1);\n }\n if (opts.status === 'unresolved') {\n process.stderr.write('research-os: --status unresolved is the default; use resolved, preserved, or rejected\\n');\n process.exit(1);\n }\n const result = await contradictResolve({\n sectionId: section,\n packPath: opts.pack,\n contradictionIds: opts.id,\n all: opts.all,\n status: opts.status,\n reason: opts.reason,\n resolvedBy: opts.by,\n });\n process.stdout.write(`contradict resolve complete\\n`);\n process.stdout.write(` section: ${result.sectionId}\\n`);\n process.stdout.write(` applied: ${result.applied}\\n`);\n process.stdout.write(` skipped: ${result.skipped}\\n`);\n process.stdout.write(` ledger: ${result.ledgerPath}\\n`);\n } catch (err) {\n reportError(err);\n }\n });\n\nprogram\n .command('gate')\n .description('Run the section gate engine and emit a structured verdict')\n .argument('<section>', 'Section id, e.g. \"01-landscape\"')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .action(async (section: string, opts) => {\n try {\n const result = await runGate({\n sectionId: section,\n packPath: opts.pack,\n });\n process.stdout.write(`gate verdict: ${result.verdict.toUpperCase()}\\n`);\n process.stdout.write(` section: ${result.section_id}\\n`);\n process.stdout.write(` synthesis eligible: ${result.synthesis_eligible}\\n`);\n process.stdout.write(` failures: ${result.failures.length}\\n`);\n process.stdout.write(` warnings: ${result.warnings.length}\\n`);\n process.stdout.write(` waivers applied: ${result.waivers_applied.length}\\n`);\n process.stdout.write(` blocking reasons: ${result.blocking_reasons.length}\\n`);\n if (result.blocking_reasons.length > 0) {\n process.stdout.write(`\\nblocking:\\n`);\n for (const r of result.blocking_reasons) {\n process.stdout.write(` - ${r}\\n`);\n }\n }\n if (result.next_actions.length > 0) {\n process.stdout.write(`\\nnext actions:\\n`);\n for (const a of result.next_actions) {\n process.stdout.write(` - ${a}\\n`);\n }\n }\n if (!result.synthesis_eligible) process.exitCode = 2;\n } catch (err) {\n reportError(err);\n }\n });\n\nprogram\n .command('review')\n .description('Run the adversarial reviewer pass; emits findings + claim review decisions')\n .argument('<section>', 'Section id, e.g. \"01-landscape\"')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .option(\n '--heuristic-only',\n 'Skip the LLM reviewer; run only the deterministic HeuristicReviewer',\n false,\n )\n .option(\n '--triaged-only',\n 'Only review claims that triage selected_for_review',\n false,\n )\n .option(\n '--llm-paged',\n 'Force the LLM reviewer (paged windows) — alias for the default ladder when ollama is up. Useful as documentation of intent.',\n false,\n )\n .option(\n '--review-window <n>',\n 'Claims per LLM review window (default 30). Smaller windows fit smaller models.',\n (v) => parseInt(v, 10),\n )\n .option(\n '--two-pass-llm',\n 'Two-pass LLM review: general + narrow_critic + heuristic. Findings merged.',\n false,\n )\n .option(\n '--model <name>',\n 'Override OLLAMA_INTERN_MODEL for this run (e.g. qwen3:14b). Applied to BOTH passes when --two-pass-llm.',\n )\n .option(\n '--general-model <name>',\n 'Model for the general LLM reviewer (overrides --model and OLLAMA_INTERN_MODEL).',\n )\n .option(\n '--critic-model <name>',\n 'Model for the narrow_critic LLM reviewer (overrides --model and OLLAMA_INTERN_MODEL).',\n )\n .option(\n '--profile <name>',\n `Review profile name. Non-default profiles are calibration evidence under sections/<id>/reviews/<profile>/ and do NOT update canonical state until promoted via 'review promote'.`,\n DEFAULT_PROFILE,\n )\n .option(\n '--preset <name>',\n 'Reviewer preset name from research.yaml/review_profiles. Fills --general-model, --critic-model, --review-window, --two-pass-llm from the preset; explicit flags still override.',\n )\n .action(async (section: string, opts) => {\n try {\n // Resolve preset (if any) from research.yaml/review_profiles. Explicit\n // CLI flags override preset values; preset only fills the gaps.\n let preset:\n | {\n general_model?: string | null;\n critic_model?: string | null;\n review_window?: number | null;\n mode?: 'general' | 'two_pass';\n }\n | undefined;\n if (opts.preset) {\n const fs = await import('node:fs/promises');\n const path = await import('node:path');\n const yaml = await import('yaml');\n const { ResearchYamlSchema } = await import('./intake/schema.js');\n const yamlPath = path.join(opts.pack as string, 'research.yaml');\n const research = ResearchYamlSchema.parse(\n yaml.parse(await fs.readFile(yamlPath, 'utf8')),\n );\n const found = research.review_profiles[opts.preset as string];\n if (!found) {\n throw new Error(\n `Preset \"${opts.preset}\" not in research.yaml/review_profiles. Known: ${Object.keys(research.review_profiles).join(', ') || '(none)'}`,\n );\n }\n preset = found;\n }\n\n const baseModel = (opts.model as string | undefined) ?? undefined;\n const generalModel =\n (opts.generalModel as string | undefined) ??\n baseModel ??\n preset?.general_model ??\n undefined;\n const criticModel =\n (opts.criticModel as string | undefined) ??\n baseModel ??\n preset?.critic_model ??\n undefined;\n const reviewWindow =\n (opts.reviewWindow as number | undefined) ?? preset?.review_window ?? undefined;\n const twoPass =\n Boolean(opts.twoPassLlm) || (preset?.mode === 'two_pass' ? true : false);\n\n const reviewers = opts.heuristicOnly\n ? [new HeuristicReviewer()]\n : twoPass\n ? [\n new OllamaInternReviewer({\n mode: 'general',\n model: generalModel ?? undefined,\n claimsPerWindow: reviewWindow,\n }),\n new OllamaInternReviewer({\n mode: 'narrow_critic',\n model: criticModel ?? undefined,\n claimsPerWindow: reviewWindow,\n }),\n new HeuristicReviewer(),\n ]\n : reviewWindow || opts.llmPaged || baseModel || generalModel\n ? [\n new OllamaInternReviewer({\n model: generalModel ?? undefined,\n claimsPerWindow: reviewWindow,\n }),\n new HeuristicReviewer(),\n ]\n : undefined;\n const result = await runReview({\n sectionId: section,\n packPath: opts.pack,\n reviewers,\n triagedOnly: opts.triagedOnly,\n multiPass: twoPass,\n profile: opts.profile as string | undefined,\n });\n process.stdout.write(`review complete\\n`);\n process.stdout.write(` section: ${result.sectionId}\\n`);\n process.stdout.write(` reviewer: ${result.reviewer}\\n`);\n process.stdout.write(` method: ${result.reviewMethod}\\n`);\n process.stdout.write(` candidate claims: ${result.candidateClaims}\\n`);\n process.stdout.write(` findings added: ${result.findingsAdded}\\n`);\n process.stdout.write(` findings deduped: ${result.findingsDeduped}\\n`);\n process.stdout.write(` llm findings rejected: ${result.llmFindingsRejected}\\n`);\n process.stdout.write(` blocking findings: ${result.blockingFindings}\\n`);\n process.stdout.write(` promoted to reviewed: ${result.promotedToReviewed}\\n`);\n process.stdout.write(`\\ndecisions:\\n`);\n for (const [d, n] of Object.entries(result.decisions)) {\n process.stdout.write(` ${d}: ${n}\\n`);\n }\n } catch (err) {\n reportError(err);\n }\n });\n\nconst indexCmd = program\n .command('index')\n .description('Build, query, and export the pack-local research-truth index');\n\nindexCmd\n .command('build')\n .description('Build the in-pack SQLite index from canonical artifacts')\n .argument('[section]', 'Optional section id; omit to index every section')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .option('--all', 'Index every section in the pack (default behavior)')\n .action(async (section: string | undefined, opts) => {\n try {\n const result = await indexBuild({\n sectionId: section,\n packPath: opts.pack,\n all: opts.all,\n });\n process.stdout.write(`index build complete\\n`);\n process.stdout.write(` db: ${result.dbPath}\\n`);\n process.stdout.write(` sections indexed: ${result.sectionsIndexed}\\n`);\n process.stdout.write(` sources: ${result.sources}\\n`);\n process.stdout.write(` claims: ${result.claims}\\n`);\n process.stdout.write(` contradictions: ${result.contradictions}\\n`);\n process.stdout.write(` review findings: ${result.reviewFindings}\\n`);\n process.stdout.write(` claim reviews: ${result.claimReviews}\\n`);\n process.stdout.write(` gate results: ${result.gateResults}\\n`);\n process.stdout.write(` fetch receipts: ${result.fetchReceipts}\\n`);\n process.stdout.write(` artifacts tracked: ${result.artifacts}\\n`);\n } catch (err) {\n reportError(err);\n }\n });\n\nindexCmd\n .command('export-repo-knowledge')\n .description('Write a repo-knowledge-compatible facts JSONL from the index')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .option('--out <path>', 'Output path; defaults to evidence/repo-knowledge/research-os-facts.jsonl')\n .action(async (opts) => {\n try {\n const result = await exportRepoKnowledge({\n packPath: opts.pack,\n outPath: opts.out,\n });\n process.stdout.write(`export complete\\n`);\n process.stdout.write(` out: ${result.outPath}\\n`);\n process.stdout.write(` facts: ${result.factCount}\\n`);\n for (const [t, n] of Object.entries(result.byType)) {\n process.stdout.write(` ${t}: ${n}\\n`);\n }\n } catch (err) {\n reportError(err);\n }\n });\n\nindexCmd\n .command('sync-repo-knowledge')\n .description('Sync the index into a locally-installed @mcptoolshop/repo-knowledge (optional, skips cleanly when absent)')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .action(async (opts) => {\n try {\n const result = await syncRepoKnowledge({ packPath: opts.pack });\n process.stdout.write(`sync attempted: ${result.attempted}\\n`);\n process.stdout.write(` ok: ${result.ok}\\n`);\n process.stdout.write(` facts synced: ${result.factsSynced}\\n`);\n process.stdout.write(` reason: ${result.reason}\\n`);\n if (result.attempted && !result.ok) process.exitCode = 2;\n } catch (err) {\n reportError(err);\n }\n });\n\nprogram\n .command('query')\n .description('Query the pack-local research-truth index')\n .argument('<term>', 'Search term (FTS5 syntax accepted)')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .option('--limit <n>', 'Max hits to return', (v) => parseInt(v, 10), 25)\n .option('--type <type>', 'Restrict to one record type (claim, source, contradiction, review_finding, gate_result, fetch_receipt, claim_review, section)')\n .action((term: string, opts) => {\n try {\n const result = indexQuery({\n term,\n packPath: opts.pack,\n limit: opts.limit,\n recordType: opts.type,\n });\n process.stdout.write(`query: ${JSON.stringify(result.term)}\\n`);\n process.stdout.write(`hits: ${result.totalHits}\\n\\n`);\n for (const [type, hits] of Object.entries(result.groupedByType)) {\n process.stdout.write(`== ${type} (${hits.length}) ==\\n`);\n for (const h of hits) {\n process.stdout.write(` [${h.section_id ?? '-'}] ${h.record_id}\\n`);\n process.stdout.write(` artifact: ${h.artifact_path}\\n`);\n process.stdout.write(` snippet: ${h.snippet.replace(/\\s+/g, ' ').slice(0, 240)}\\n`);\n }\n process.stdout.write('\\n');\n }\n } catch (err) {\n reportError(err);\n }\n });\n\nconst coworkCmd = program\n .command('cowork')\n .description('Cowork handoff: render the runtime contract from research truth');\n\ncoworkCmd\n .command('handoff')\n .description('Generate handoffs/cowork-handoff.json + handoffs/cowork-master.md from current pack state')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .action(async (opts) => {\n try {\n const result = await coworkHandoff({ packPath: opts.pack });\n process.stdout.write(`cowork handoff rendered\\n`);\n process.stdout.write(` pack id: ${result.packId}\\n`);\n process.stdout.write(` pack topic: ${result.packTopic}\\n`);\n process.stdout.write(` mode: ${result.mode}\\n`);\n process.stdout.write(` synthesis allowed: ${result.synthesisAllowed}\\n`);\n process.stdout.write(` accepted claims: ${result.acceptedCount}\\n`);\n process.stdout.write(` repair claims: ${result.repairCount}\\n`);\n process.stdout.write(` rejected claims: ${result.blockedCount}\\n`);\n process.stdout.write(` json: ${result.jsonPath}\\n`);\n process.stdout.write(` markdown: ${result.markdownPath}\\n`);\n if (result.warnings.length > 0) {\n process.stdout.write(`\\nwarnings:\\n`);\n for (const w of result.warnings) {\n process.stdout.write(` - ${w}\\n`);\n }\n }\n if (!result.synthesisAllowed) process.exitCode = 0; // not an error — informational\n } catch (err) {\n reportError(err);\n }\n });\n\nconst synthCmd = program\n .command('synth')\n .description('Synthesis workspace: organize accepted research truth for Cowork');\n\nsynthCmd\n .command('workspace')\n .description('Create the synthesis workspace; refuses unless cowork handoff mode is synthesis_ready')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .action(async (opts) => {\n try {\n const result = await synthWorkspace({ packPath: opts.pack });\n if (result.refused) {\n process.stdout.write(`synthesis workspace: REFUSED\\n`);\n process.stdout.write(` mode: ${result.mode}\\n`);\n process.stdout.write(` reason: ${result.refusalReason}\\n`);\n process.exitCode = 2;\n return;\n }\n process.stdout.write(`synthesis workspace ready\\n`);\n process.stdout.write(` mode: ${result.mode}\\n`);\n process.stdout.write(` accepted claims: ${result.acceptedClaims}\\n`);\n process.stdout.write(` claim clusters: ${result.claimClusters}\\n`);\n process.stdout.write(` scope overlaps: ${result.scopeOverlaps}\\n`);\n process.stdout.write(` cross-section contradictions: ${result.crossSectionContradictions}\\n`);\n for (const f of result.filesWritten) process.stdout.write(` wrote: ${f}\\n`);\n } catch (err) {\n reportError(err);\n }\n });\n\nprogram\n .command('audit')\n .description('Aggregate pack-level audit rollups across all sections')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .action(async (opts) => {\n try {\n const result = await runAudit({ packPath: opts.pack });\n process.stdout.write(`pack audit complete\\n`);\n process.stdout.write(` verdict: ${result.verdict}\\n`);\n process.stdout.write(` synthesis allowed: ${result.synthesisAllowed}\\n`);\n process.stdout.write(` orphan claims: ${result.orphans}\\n`);\n process.stdout.write(` stale sources: ${result.staleSources}\\n`);\n process.stdout.write(` weak sources: ${result.weakSources}\\n`);\n process.stdout.write(` unresolved contradictions:${result.unresolvedContradictions}\\n`);\n process.stdout.write(` scope-widening risks: ${result.scopeWideningRisks}\\n`);\n process.stdout.write(` source-diversity gaps: ${result.sourceDiversityGaps}\\n`);\n process.stdout.write(` files written: ${result.filesWritten.length}\\n`);\n if (result.blockingReasons.length > 0) {\n process.stdout.write(`\\nblocking reasons:\\n`);\n for (const b of result.blockingReasons) process.stdout.write(` - ${b}\\n`);\n }\n if (result.warnings.length > 0) {\n process.stdout.write(`\\nwarnings:\\n`);\n for (const w of result.warnings) process.stdout.write(` - ${w}\\n`);\n }\n if (!result.synthesisAllowed) process.exitCode = 2;\n } catch (err) {\n reportError(err);\n }\n });\n\nprogram\n .command('freeze')\n .description('Final integrity lock; refuses unless every condition is met')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .action(async (opts) => {\n try {\n const result = await runFreeze({ packPath: opts.pack });\n if (result.verdict === 'refused') {\n process.stdout.write(`freeze: REFUSED\\n`);\n process.stdout.write(` reasons: ${result.reasonsCount}\\n`);\n if (result.refusalPayload) {\n for (const r of result.refusalPayload.blocking_reasons) {\n process.stdout.write(` - ${r}\\n`);\n }\n if (result.refusalPayload.next_actions.length > 0) {\n process.stdout.write(`\\nnext actions:\\n`);\n for (const a of result.refusalPayload.next_actions) process.stdout.write(` - ${a}\\n`);\n }\n }\n process.stdout.write(` refusal json: ${result.jsonPath}\\n`);\n process.stdout.write(` refusal markdown: ${result.markdownPath}\\n`);\n process.exitCode = 2;\n return;\n }\n process.stdout.write(`freeze: FROZEN\\n`);\n if (result.receiptPayload) {\n process.stdout.write(` pack id: ${result.receiptPayload.pack_id}\\n`);\n process.stdout.write(` frozen at: ${result.receiptPayload.frozen_at}\\n`);\n process.stdout.write(` accepted claims: ${result.receiptPayload.accepted_claim_ids.length}\\n`);\n process.stdout.write(` cited claims: ${result.citedClaimCount}\\n`);\n process.stdout.write(` uncited accepted (info): ${result.uncitedAcceptedClaimCount}\\n`);\n process.stdout.write(` unresolved contradictions: ${result.receiptPayload.unresolved_contradictions.length}\\n`);\n process.stdout.write(` waivers disclosed: ${result.receiptPayload.waivers_disclosed.length}\\n`);\n process.stdout.write(` canonical artifacts hashed: ${result.receiptPayload.canonical_artifact_hashes.length}\\n`);\n process.stdout.write(` synthesis files hashed: ${result.receiptPayload.synthesis_hashes.length}\\n`);\n }\n process.stdout.write(` receipt json: ${result.jsonPath}\\n`);\n process.stdout.write(` receipt markdown: ${result.markdownPath}\\n`);\n } catch (err) {\n reportError(err);\n }\n });\n\nconst invalidate = program\n .command('invalidate')\n .description('Invalidate (archive with a receipt) artifacts produced under a superseded contract');\n\ninvalidate\n .command('extraction')\n .description(\n 'Archive claims/reviews/contradictions/audits/handoffs/synthesis written under the legacy authored-evidence-excerpt contract; replaced by span-first-extraction',\n )\n .requiredOption('--reason <text>', 'Plain-language reason recorded on the invalidation receipt')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .option('--label <slug>', 'Folder label under audits/legacy/', 'pre-span-extraction')\n .option('--new-contract <name>', 'Name recorded for the replacement contract', 'span-first-extraction')\n .option(\n '--superseded-contract <name>',\n 'Name recorded for the contract being retired',\n 'authored-evidence-excerpt',\n )\n .option('--notes <text>', 'Optional free-text notes to include on the receipt')\n .action(async (opts) => {\n try {\n const result = await invalidateExtraction({\n packPath: opts.pack,\n reason: opts.reason,\n label: opts.label,\n newContract: opts.newContract,\n supersededContract: opts.supersededContract,\n notes: opts.notes,\n });\n if (!result.performed) {\n process.stdout.write(`invalidate extraction: no-op\\n`);\n process.stdout.write(` ${result.message}\\n`);\n return;\n }\n process.stdout.write(`invalidate extraction: archived\\n`);\n process.stdout.write(` receipt id: ${result.receiptId}\\n`);\n process.stdout.write(` contract label: ${result.contractLabel}\\n`);\n process.stdout.write(` affected sections: ${result.affectedSections.length}\\n`);\n for (const s of result.affectedSections) process.stdout.write(` - ${s}\\n`);\n process.stdout.write(` archived count: ${result.archivedCount}\\n`);\n process.stdout.write(` archive dir: ${result.archiveDir}\\n`);\n } catch (err) {\n reportError(err);\n }\n });\n\ninvalidate\n .command('review')\n .description(\n 'Archive canonical review artifacts for a section into sections/<id>/legacy/<label>/<timestamp>/. Use to invalidate pre-profile review state before promoting a profile as new canonical truth.',\n )\n .argument('<section>', 'Section id, e.g. \"03-source-and-claim-truth\"')\n .requiredOption('--reason <text>', 'Plain-language reason recorded on the invalidation receipt')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .option('--label <slug>', 'Folder label under sections/<id>/legacy/', 'pre-review-profiles')\n .option('--notes <text>', 'Optional free-text notes recorded on the receipt')\n .action(async (section: string, opts) => {\n try {\n const result = await invalidateReview({\n packPath: opts.pack,\n sectionId: section,\n reason: opts.reason,\n label: opts.label,\n notes: opts.notes,\n });\n if (!result.performed) {\n process.stdout.write(`invalidate review: no-op\\n`);\n process.stdout.write(` ${result.message}\\n`);\n return;\n }\n process.stdout.write(`invalidate review: archived\\n`);\n process.stdout.write(` receipt id: ${result.receiptId}\\n`);\n process.stdout.write(` section: ${result.sectionId}\\n`);\n process.stdout.write(` contract label: ${result.contractLabel}\\n`);\n process.stdout.write(` archived count: ${result.archivedCount}\\n`);\n process.stdout.write(` archive dir: ${result.archiveDir}\\n`);\n } catch (err) {\n reportError(err);\n }\n });\n\nprogram\n .command('review-promote')\n .description(\n 'Promote a review profile to active state: copies the profile artifacts to canonical paths and writes review-active.json. Until promoted, profile runs are calibration evidence, not section truth.',\n )\n .argument('<section>', 'Section id, e.g. \"03-source-and-claim-truth\"')\n .requiredOption('--profile <name>', 'Profile name to promote')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .option(\n '--reason <text>',\n 'Free-text rationale recorded on review-active.json — why this profile is being trusted',\n )\n .option('--calibration-fixture <name>', 'Calibration fixture name')\n .option('--good-fp <text>', 'good-claim false-positive rate string (e.g. \"0/5 (0%)\")')\n .option('--any-flag-recall <text>', 'bad-claim any-flag recall string (e.g. \"9/13 (69%)\")')\n .option('--strict-cat-recall <text>', 'strict-category recall string')\n .option('--unsupported-recall <text>', 'unsupported_claim category recall string')\n .option('--calibration-notes <text>', 'free-text calibration notes')\n .option(\n '--bump-section-status',\n 'Also bump section.status from gated → reviewed if every promoted claim is accepted_for_synthesis',\n false,\n )\n .action(async (section: string, opts) => {\n try {\n const calibration =\n opts.calibrationFixture ||\n opts.goodFp ||\n opts.anyFlagRecall ||\n opts.strictCatRecall ||\n opts.unsupportedRecall ||\n opts.calibrationNotes\n ? {\n fixture: opts.calibrationFixture ?? null,\n good_false_positive_rate: opts.goodFp ?? null,\n bad_any_flag_recall: opts.anyFlagRecall ?? null,\n strict_category_recall: opts.strictCatRecall ?? null,\n unsupported_claim_recall: opts.unsupportedRecall ?? null,\n notes: opts.calibrationNotes ?? null,\n }\n : null;\n const result = await runPromote({\n sectionId: section,\n packPath: opts.pack,\n profile: opts.profile,\n promotionReason: opts.reason,\n calibrationSummary: calibration,\n promoteSectionStatus: opts.bumpSectionStatus,\n });\n process.stdout.write(`review profile promoted\\n`);\n process.stdout.write(` section: ${result.sectionId}\\n`);\n process.stdout.write(` profile: ${result.profile}\\n`);\n process.stdout.write(` promoted_at: ${result.promoted_at}\\n`);\n process.stdout.write(` promoted_method: ${result.promoted_method}\\n`);\n process.stdout.write(` promoted_reviewer: ${result.promoted_reviewer}\\n`);\n process.stdout.write(` status bumped: ${result.section_status_bumped}\\n`);\n process.stdout.write(` canonical files updated: ${result.canonical_files_updated.length}\\n`);\n } catch (err) {\n reportError(err);\n }\n });\n\nconst packCmd = program\n .command('pack')\n .description('Pack-level publication and archive operations');\n\npackCmd\n .command('publish')\n .description(\n 'Export a frozen pack into the research-packs archive format. ' +\n 'Copies the pack, derives pack.manifest.json, generates README.md, ' +\n 'provisions docs/how-to-read-this.md, and verifies the admission contract.',\n )\n .requiredOption('--to <path>', 'Target package directory, e.g. <research-packs>/packages/<name>')\n .option('--from <path>', 'Source frozen pack directory (defaults to cwd)', process.cwd())\n .option('--operator-notes <text>', 'Operator notes recorded in pack.manifest.json', '')\n .option('--force', 'Overwrite an existing non-empty target directory', false)\n .option('--dry-run', 'Print derived manifest and README plan; write nothing', false)\n .action(async (opts) => {\n try {\n const result = await packPublish({\n fromDir: opts.from as string,\n toDir: opts.to as string,\n operatorNotes: opts.operatorNotes as string,\n force: Boolean(opts.force),\n dryRun: Boolean(opts.dryRun),\n });\n if (result.dryRun) {\n process.stdout.write(`pack publish: DRY-RUN — no files written\\n`);\n process.stdout.write(` package name: ${result.packageName}\\n`);\n if (result.dryRunManifest) {\n const m = result.dryRunManifest;\n process.stdout.write(` topic: ${m.topic.slice(0, 80)}\\n`);\n process.stdout.write(` frozen_at: ${m.frozen_at}\\n`);\n process.stdout.write(` sections: ${m.totals.sections}\\n`);\n process.stdout.write(` accepted: ${m.totals.accepted_claims}\\n`);\n process.stdout.write(` receipt sha256:${m.freeze_receipt_sha256.slice(0, 16)}…\\n`);\n }\n return;\n }\n process.stdout.write(`pack publish: DONE\\n`);\n process.stdout.write(` package name: ${result.packageName}\\n`);\n process.stdout.write(` files written: ${result.filesWritten.length}\\n`);\n for (const f of result.filesWritten) process.stdout.write(` ${f}\\n`);\n process.stdout.write(` verify: ${result.verifyPassed ? 'PASS' : 'FAIL'}\\n`);\n if (result.warnings.length > 0) {\n process.stdout.write(`\\nwarnings:\\n`);\n for (const w of result.warnings) process.stdout.write(` - ${w}\\n`);\n }\n if (!result.verifyPassed) process.exitCode = 2;\n } catch (err) {\n reportError(err);\n }\n });\n\nprogram.parseAsync(process.argv);\n","import { existsSync, mkdirSync, writeFileSync, readFileSync, readdirSync } from 'node:fs';\nimport { join, basename, resolve } from 'node:path';\nimport { deriveManifest } from './manifest.js';\nimport { generateReadme } from './readme.js';\nimport { generateHowToReadScaffold } from './how-to-read.js';\nimport { copyDir } from './copy.js';\nimport { verifyPack } from './verify.js';\nimport type { PublishInput, PublishResult } from './types.js';\n\n// Source pack files that must exist before publish begins.\nconst REQUIRED_SOURCE_FILES = [\n 'research.yaml',\n 'audits/freeze-receipt.json',\n 'audits/pack-audit.json',\n 'synthesis/final-report.md',\n 'synthesis/decision-brief.md',\n];\n\nexport async function publish(input: PublishInput): Promise<PublishResult> {\n const fromDir = resolve(input.fromDir);\n const toDir = resolve(input.toDir);\n const packageName = basename(toDir);\n const warnings: string[] = [];\n\n // 1. Validate source pack has required files\n for (const rel of REQUIRED_SOURCE_FILES) {\n if (!existsSync(join(fromDir, rel))) {\n throw new Error(\n `Source pack missing required file: ${rel}\\n Hint: run research-os freeze before publish\\n Pack: ${fromDir}`,\n );\n }\n }\n\n // 2. Refuse if freeze-refusal artifacts exist (pack did not freeze cleanly)\n if (\n existsSync(join(fromDir, 'audits/freeze-refusal.json')) ||\n existsSync(join(fromDir, 'audits/freeze-refusal.md'))\n ) {\n throw new Error(\n `Source pack has freeze-refusal artifacts — pack did not freeze cleanly.\\n Resolve blocking reasons then re-run research-os freeze.\\n Pack: ${fromDir}`,\n );\n }\n\n // 3. Check target: refuse if non-empty without --force\n if (existsSync(toDir)) {\n const entries = readdirSync(toDir);\n if (entries.length > 0 && !input.force) {\n throw new Error(\n `Target directory already exists and is non-empty: ${toDir}\\n Use --force to overwrite.`,\n );\n }\n }\n\n // 4. Derive manifest early — fail fast on bad pack state before writing anything\n const manifest = deriveManifest(fromDir, packageName, input.operatorNotes ?? '');\n\n // 5. Dry-run: print plan without writing\n if (input.dryRun) {\n const finalReportPath = join(fromDir, 'synthesis/final-report.md');\n const finalReport = existsSync(finalReportPath)\n ? readFileSync(finalReportPath, 'utf8')\n : '';\n const readme = generateReadme(manifest, finalReport);\n return {\n packageName,\n filesWritten: [],\n warnings: ['dry-run: no files written'],\n verifyPassed: false,\n dryRun: true,\n dryRunManifest: manifest,\n dryRunReadme: readme,\n };\n }\n\n // 6. Create target directory\n mkdirSync(toDir, { recursive: true });\n\n const filesWritten: string[] = [];\n\n // 7. Copy entire frozen pack to <target>/pack/\n const packTarget = join(toDir, 'pack');\n const packFileCount = copyDir(fromDir, packTarget);\n filesWritten.push(`pack/ (${packFileCount} files)`);\n\n // 8. Copy synthesis/ to <target>/synthesis/ (Lane 1 accessibility)\n const synthSrc = join(fromDir, 'synthesis');\n if (existsSync(synthSrc)) {\n const synthTarget = join(toDir, 'synthesis');\n const synthFileCount = copyDir(synthSrc, synthTarget);\n filesWritten.push(`synthesis/ (${synthFileCount} files)`);\n } else {\n warnings.push(\n 'No synthesis/ directory in source pack — Lane 1 synthesis files not written',\n );\n }\n\n // 9. Write pack.manifest.json\n writeFileSync(\n join(toDir, 'pack.manifest.json'),\n JSON.stringify(manifest, null, 2) + '\\n',\n 'utf8',\n );\n filesWritten.push('pack.manifest.json');\n\n // 10. Generate README.md from final-report.md + manifest\n const finalReportPath = join(fromDir, 'synthesis/final-report.md');\n const finalReport = existsSync(finalReportPath) ? readFileSync(finalReportPath, 'utf8') : '';\n const readme = generateReadme(manifest, finalReport);\n writeFileSync(join(toDir, 'README.md'), readme, 'utf8');\n filesWritten.push('README.md');\n\n // 11. Provision docs/how-to-read-this.md scaffold (preserve if already exists)\n const docsDir = join(toDir, 'docs');\n mkdirSync(docsDir, { recursive: true });\n const howToReadPath = join(docsDir, 'how-to-read-this.md');\n if (existsSync(howToReadPath)) {\n warnings.push(\n 'docs/how-to-read-this.md already exists — not overwritten (operator-authored content preserved)',\n );\n } else {\n const scaffold = generateHowToReadScaffold(manifest);\n writeFileSync(howToReadPath, scaffold, 'utf8');\n filesWritten.push('docs/how-to-read-this.md');\n }\n\n // 12. Run inline admission-contract verification\n const verifyResult = verifyPack(toDir);\n for (const w of verifyResult.softWarnings ?? []) warnings.push(w);\n\n if (!verifyResult.pass) {\n throw new Error(\n `Pack verification FAILED after publish — the published package does not meet the admission contract.\\n` +\n ` ${verifyResult.reason}\\n` +\n ` Target: ${toDir}`,\n );\n }\n\n return {\n packageName,\n filesWritten,\n warnings,\n verifyPassed: true,\n dryRun: false,\n };\n}\n\nexport { verifyPack } from './verify.js';\nexport { deriveManifest } from './manifest.js';\nexport { generateReadme } from './readme.js';\nexport { generateHowToReadScaffold } from './how-to-read.js';\nexport type { PublishInput, PublishResult } from './types.js';\nexport type { PackManifest } from './schema.js';\n","import { createHash } from 'node:crypto';\nimport { readFileSync, existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { parse as parseYaml } from 'yaml';\nimport { z } from 'zod';\nimport { ResearchYamlSchema } from '../../intake/schema.js';\nimport { PackManifestSchema } from './schema.js';\nimport type { PackManifest } from './schema.js';\n\n// Minimal schema for gate-result.json — only the fields manifest derivation needs.\nconst GateResultMinimalSchema = z.object({\n verdict: z.enum(['pass', 'warn', 'fail', 'blocked']),\n synthesis_eligible: z.boolean(),\n});\n\ninterface ClaimReviewLine {\n claim_id: string;\n decision: string;\n created_at: string;\n}\n\ninterface ResolutionLine {\n contradiction_id: string;\n status: string;\n resolved_at: string;\n}\n\ninterface DispositionLine {\n claim_id: string;\n created_at: string;\n}\n\ninterface AuditSectionSummary {\n section_id: string;\n accepted_claims: number;\n}\n\nfunction sha256Bytes(buf: Buffer): string {\n return createHash('sha256').update(buf).digest('hex');\n}\n\nfunction parseJsonl<T>(content: string): T[] {\n return content\n .split('\\n')\n .filter((l) => l.trim().length > 0)\n .map((l) => JSON.parse(l) as T);\n}\n\nfunction readJsonlSafe<T>(filePath: string): T[] {\n if (!existsSync(filePath)) return [];\n return parseJsonl<T>(readFileSync(filePath, 'utf8'));\n}\n\nfunction latestClaimDecisions(reviews: ClaimReviewLine[]): Map<string, string> {\n const m = new Map<string, string>();\n const sorted = [...reviews].sort((a, b) => a.created_at.localeCompare(b.created_at));\n for (const r of sorted) m.set(r.claim_id, r.decision);\n return m;\n}\n\nfunction latestContradictionStatuses(resolutions: ResolutionLine[]): Map<string, string> {\n const m = new Map<string, string>();\n const sorted = [...resolutions].sort((a, b) => a.resolved_at.localeCompare(b.resolved_at));\n for (const r of sorted) m.set(r.contradiction_id, r.status);\n return m;\n}\n\nfunction latestDispositionStatuses(dispositions: DispositionLine[]): Map<string, string> {\n const m = new Map<string, string>();\n const sorted = [...dispositions].sort((a, b) => a.created_at.localeCompare(b.created_at));\n for (const d of sorted) m.set(d.claim_id, 'dispositioned');\n return m;\n}\n\nexport interface ManifestRefusal {\n reason: string;\n}\n\nexport function deriveManifest(\n packDir: string,\n packageName: string,\n operatorNotes = '',\n): PackManifest {\n // research.yaml\n const yamlPath = join(packDir, 'research.yaml');\n if (!existsSync(yamlPath)) throw new Error(`research.yaml not found in ${packDir}`);\n const research = ResearchYamlSchema.parse(parseYaml(readFileSync(yamlPath, 'utf8')));\n if (!research.frozen_at) {\n throw new Error(`Pack is not frozen: research.yaml.frozen_at is null — run research-os freeze first`);\n }\n\n // freeze-receipt.json → sha256 of file bytes → freeze_receipt_sha256; parse for frozen_at\n const receiptPath = join(packDir, 'audits/freeze-receipt.json');\n if (!existsSync(receiptPath)) {\n throw new Error(`audits/freeze-receipt.json not found — pack is not frozen`);\n }\n const receiptBytes = readFileSync(receiptPath);\n const freeze_receipt_sha256 = sha256Bytes(receiptBytes);\n const receipt = JSON.parse(receiptBytes.toString('utf8')) as { frozen_at?: string };\n const frozen_at = receipt.frozen_at ?? research.frozen_at;\n\n // pack-audit.json → per-section accepted_claims for cross-check\n const packAuditPath = join(packDir, 'audits/pack-audit.json');\n if (!existsSync(packAuditPath)) throw new Error(`audits/pack-audit.json not found`);\n const packAudit = JSON.parse(readFileSync(packAuditPath, 'utf8')) as {\n section_summaries?: AuditSectionSummary[];\n };\n const auditSectionMap = new Map<string, number>(\n (packAudit.section_summaries ?? []).map((s) => [s.section_id, s.accepted_claims]),\n );\n\n // Per-section derivation\n const sectionIds = research.sections.map((s) => s.id);\n const sections: PackManifest['sections'] = [];\n let totalAccepted = 0;\n let totalDispositioned = 0;\n let totalPreserved = 0;\n\n for (const sectionId of sectionIds) {\n const sectionDir = join(packDir, 'sections', sectionId);\n\n // claim-reviews.jsonl → latest-decision-wins → count accepted_for_synthesis\n const reviews = readJsonlSafe<ClaimReviewLine>(join(sectionDir, 'claim-reviews.jsonl'));\n const decisionMap = latestClaimDecisions(reviews);\n const acceptedCount = [...decisionMap.values()].filter(\n (d) => d === 'accepted_for_synthesis',\n ).length;\n\n // Cross-check against pack-audit.json section summaries (Pattern 2 — same predicate)\n const auditAccepted = auditSectionMap.get(sectionId);\n if (auditAccepted !== undefined && auditAccepted !== acceptedCount) {\n throw new Error(\n `Section ${sectionId}: accepted_claims mismatch between claim-reviews.jsonl (${acceptedCount})` +\n ` and pack-audit.json (${auditAccepted}). Closure-ledger seam disagreement — investigate before publishing.`,\n );\n }\n\n // audits/<section-id>-gate.json → verdict + synthesis_eligible\n const gateResultPath = join(packDir, 'audits', `${sectionId}-gate.json`);\n if (!existsSync(gateResultPath)) {\n throw new Error(`audits/${sectionId}-gate.json not found — section not gated`);\n }\n const gateResult = GateResultMinimalSchema.parse(\n JSON.parse(readFileSync(gateResultPath, 'utf8')),\n );\n\n // claim-synthesis-dispositions.jsonl → latest-status-wins count\n const dispositions = readJsonlSafe<DispositionLine>(\n join(sectionDir, 'claim-synthesis-dispositions.jsonl'),\n );\n const dispositionMap = latestDispositionStatuses(dispositions);\n totalDispositioned += dispositionMap.size;\n\n // contradiction-resolutions.jsonl → latest-status-wins; assert none unresolved\n const resolutions = readJsonlSafe<ResolutionLine>(\n join(sectionDir, 'contradiction-resolutions.jsonl'),\n );\n const resolutionMap = latestContradictionStatuses(resolutions);\n const stillUnresolved = [...resolutionMap.values()].filter((s) => s === 'unresolved').length;\n if (stillUnresolved > 0) {\n throw new Error(\n `Section ${sectionId} has ${stillUnresolved} unresolved contradictions.` +\n ` Freeze should have blocked this — investigate before publishing.`,\n );\n }\n totalPreserved += [...resolutionMap.values()].filter((s) => s !== 'unresolved').length;\n\n totalAccepted += acceptedCount;\n sections.push({\n id: sectionId,\n accepted_claims: acceptedCount,\n gate: gateResult.verdict,\n synthesis_eligible: gateResult.synthesis_eligible,\n });\n }\n\n const totalsBase = {\n sections: sections.length,\n accepted_claims: totalAccepted,\n dispositioned: totalDispositioned,\n unresolved_contradictions: 0,\n };\n\n return PackManifestSchema.parse({\n name: packageName,\n topic: research.topic,\n frozen_at,\n research_os_version: research.research_os_version,\n sections,\n totals: totalPreserved > 0\n ? { ...totalsBase, preserved_contradiction_records: totalPreserved }\n : totalsBase,\n freeze_receipt_sha256,\n operator_notes: operatorNotes,\n });\n}\n","import { z } from 'zod';\n\n// Mirror of research-packs/scripts/manifest-schema.mjs in TypeScript.\n// Manifests produced by pack publish must validate against both this schema\n// and the MJS schema (verified by the dogfood test via verify-pack.mjs).\n\nexport const SectionSummarySchema = z.object({\n id: z.string().min(1),\n accepted_claims: z.number().int().min(0),\n gate: z.enum(['pass', 'warn', 'fail', 'blocked', 'pass_with_waiver']),\n synthesis_eligible: z.boolean(),\n});\n\nexport const TotalsSchema = z.object({\n sections: z.number().int().min(1),\n accepted_claims: z.number().int().min(0),\n dispositioned: z.number().int().min(0),\n unresolved_contradictions: z.number().int().min(0),\n preserved_contradiction_records: z.number().int().min(0).optional(),\n});\n\nexport const PackManifestSchema = z.object({\n name: z.string().min(1),\n topic: z.string().min(1),\n frozen_at: z.string().datetime(),\n research_os_version: z.string().min(1),\n sections: z.array(SectionSummarySchema).min(1),\n totals: TotalsSchema,\n freeze_receipt_sha256: z.string().regex(/^[a-f0-9]{64}$/, 'Must be a 64-char hex sha256'),\n operator_notes: z.string().default(''),\n});\n\nexport type PackManifest = z.infer<typeof PackManifestSchema>;\nexport type SectionSummary = z.infer<typeof SectionSummarySchema>;\nexport type Totals = z.infer<typeof TotalsSchema>;\n","import type { PackManifest } from './schema.js';\n\n// Port of research-packs/scripts/summarize-pack.mjs generateReadme() to TypeScript.\n// Must produce identical output — verified by the dogfood test.\n\nfunction extractSummary(markdown: string): string {\n const lines = markdown.split('\\n');\n let inSummary = false;\n const summaryLines: string[] = [];\n for (const line of lines) {\n if (/^## Summary\\s*$/.test(line)) { inSummary = true; continue; }\n if (inSummary && /^## /.test(line)) break;\n if (inSummary) summaryLines.push(line);\n }\n return summaryLines.join('\\n').trim();\n}\n\nexport function generateReadme(manifest: PackManifest, finalReport: string): string {\n const m = manifest;\n const frozenDate = m.frozen_at.slice(0, 10);\n const summary = extractSummary(finalReport);\n\n const sectionTable = m.sections\n .map((s) => `| ${s.id} | ${s.accepted_claims} | ${s.gate} | ${s.synthesis_eligible ? 'yes' : 'no'} |`)\n .join('\\n');\n\n const totalsLine =\n m.totals.preserved_contradiction_records != null\n ? `Preserved contradiction records: ${m.totals.preserved_contradiction_records}`\n : `${m.totals.unresolved_contradictions} unresolved contradictions`;\n\n const operatorSection = m.operator_notes\n ? `\\n---\\n\\n## Operator notes\\n\\n${m.operator_notes}\\n`\n : '';\n\n return `# ${m.name}\n\n**Topic:** ${m.topic}\n\n**Frozen:** ${frozenDate} | **research-os version:** ${m.research_os_version} | **Accepted claims:** ${m.totals.accepted_claims} across ${m.totals.sections} sections\n\n---\n\n## Executive summary\n\n${summary}\n\n---\n\n## Sections\n\n| Section | Accepted claims | Gate | Synthesis eligible |\n|---------|-----------------|------|-------------------|\n${sectionTable}\n\n**Totals:** ${m.totals.accepted_claims} accepted, ${m.totals.dispositioned} dispositioned, ${totalsLine}\n\n---\n\n## How to read this pack\n\nThis package is part of the [\\`research-packs\\`](../../README.md) archive.\n\n- **Lane 1 (synthesis):** You are here. See [\\`synthesis/final-report.md\\`](synthesis/final-report.md) for the full citation-clean prose.\n- **Lane 2 (evidence):** [\\`pack/\\`](pack/) — full frozen ledgers, source cards, excerpts, claim reviews, gate results, and \\`audits/freeze-receipt.json\\`.\n- **Lane 3 (method):** [\\`../../docs/\\`](../../docs/) — artifact contract, how-to-read, source quality notes.\n\nTo verify this pack's integrity: \\`node ../../scripts/verify-pack.mjs .\\` from this directory.\n\nSee [\\`docs/how-to-read-this.md\\`](docs/how-to-read-this.md) for pack-specific reading notes.${operatorSection}`;\n}\n","import type { PackManifest } from './schema.js';\n\nexport function generateHowToReadScaffold(manifest: PackManifest): string {\n const frozenDate = manifest.frozen_at.slice(0, 10);\n const contradictionNote =\n manifest.totals.preserved_contradiction_records != null\n ? `This pack has ${manifest.totals.preserved_contradiction_records} preserved contradiction records. ` +\n `These are not active blockers — freeze validated zero unresolved contradictions across all sections. ` +\n `The records are preserved for provenance in \\`pack/sections/<id>/contradiction-resolutions.jsonl\\`.`\n : 'This pack has no preserved contradiction records.';\n\n return `# How to read: ${manifest.name}\n\n<!-- SCAFFOLD: Pre-filled with pack-specific metadata by \\`research-os pack publish\\`.\n Final prose is human-authored. Edit freely — this file is NOT covered by the freeze receipt. -->\n\n**Pack:** \\`${manifest.name}\\`\n**Topic:** ${manifest.topic}\n**Frozen:** ${frozenDate}\n**Accepted claims:** ${manifest.totals.accepted_claims} accepted claims across ${manifest.totals.sections} section${manifest.totals.sections !== 1 ? 's' : ''}\n\n---\n\n## What this pack answers\n\n<!-- human-authored: describe what the synthesis delivers -->\n\n## How the evidence is structured\n\n<!-- human-authored: explain section breakdown, what each section investigated -->\n\n## Interpreting claim IDs\n\nClaims are referenced as \\`[claim:clm_<hex>]\\` in the synthesis prose. To look up a claim:\n\n1. Open \\`pack/sections/<section-id>/claims.jsonl\\`\n2. Find the entry with matching \\`claim_id\\`\n3. The \\`asserts\\` field is the claim; \\`evidence_excerpt\\` is the literal source span\n\nAccepted vs rejected: \\`pack/sections/<section-id>/claim-reviews.jsonl\\` — latest entry per \\`claim_id\\` wins.\n\n## Preserved contradiction records\n\n${contradictionNote}\n\n## Verifying integrity\n\nFrom this directory:\n\n\\`\\`\\`bash\nnode ../../scripts/verify-pack.mjs .\n\\`\\`\\`\n\nExpected output: PASS with artifact count and receipt sha256.\n\nSee [\\`../../docs/how-to-read-a-pack.md\\`](../../docs/how-to-read-a-pack.md) for the general guide.\n`;\n}\n","import { mkdirSync, copyFileSync, readdirSync } from 'node:fs';\nimport { join } from 'node:path';\n\nexport function copyDir(src: string, dst: string): number {\n mkdirSync(dst, { recursive: true });\n let count = 0;\n const entries = readdirSync(src, { withFileTypes: true });\n for (const entry of entries) {\n const srcPath = join(src, entry.name);\n const dstPath = join(dst, entry.name);\n if (entry.isDirectory()) {\n count += copyDir(srcPath, dstPath);\n } else if (entry.isFile()) {\n copyFileSync(srcPath, dstPath);\n count++;\n }\n }\n return count;\n}\n","import { createHash } from 'node:crypto';\nimport { readFileSync, existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { PackManifestSchema } from './schema.js';\n\n// Inline equivalent of research-packs/scripts/verify-pack.mjs.\n// Checks the same admission-contract conditions. The dogfood test uses the\n// MJS script directly; this inline version is used when the research-packs\n// checkout is unavailable or for testing.\n\nconst REQUIRED_FILES = [\n 'pack/audits/freeze-receipt.json',\n 'synthesis/final-report.md',\n 'synthesis/decision-brief.md',\n 'pack.manifest.json',\n 'README.md',\n];\n\nexport interface VerifyResult {\n pass: boolean;\n reason?: string;\n name?: string;\n artifactsVerified?: number;\n softWarnings?: string[];\n}\n\nfunction sha256File(filePath: string): string {\n return createHash('sha256').update(readFileSync(filePath)).digest('hex');\n}\n\nexport function verifyPack(packageDir: string): VerifyResult {\n // Step 1: Check admission-contract files\n for (const rel of REQUIRED_FILES) {\n const full = join(packageDir, rel);\n if (!existsSync(full)) {\n return { pass: false, reason: `MISSING required file: ${rel}` };\n }\n }\n\n // Step 2: Parse and validate pack.manifest.json\n let rawManifest: unknown;\n try {\n rawManifest = JSON.parse(readFileSync(join(packageDir, 'pack.manifest.json'), 'utf8'));\n } catch (e) {\n return { pass: false, reason: `pack.manifest.json parse error: ${(e as Error).message}` };\n }\n const parsed = PackManifestSchema.safeParse(rawManifest);\n if (!parsed.success) {\n const issues = parsed.error.issues\n .map((i) => `${i.path.join('.')}: ${i.message}`)\n .join(', ');\n return { pass: false, reason: `pack.manifest.json schema violation: ${issues}` };\n }\n const m = parsed.data;\n\n // Step 3: Verify freeze_receipt_sha256 matches actual file\n const receiptPath = join(packageDir, 'pack/audits/freeze-receipt.json');\n const actualReceiptHash = sha256File(receiptPath);\n if (actualReceiptHash !== m.freeze_receipt_sha256) {\n return {\n pass: false,\n reason:\n `freeze-receipt.json hash mismatch.\\n manifest: ${m.freeze_receipt_sha256}\\n actual: ${actualReceiptHash}`,\n name: m.name,\n };\n }\n\n // Step 4: Parse freeze receipt and re-verify all fingerprinted artifacts\n let receipt: {\n canonical_artifact_hashes?: Array<{ path: string; sha256: string }>;\n synthesis_hashes?: Array<{ path: string; sha256: string }>;\n };\n try {\n receipt = JSON.parse(readFileSync(receiptPath, 'utf8'));\n } catch (e) {\n return {\n pass: false,\n reason: `freeze-receipt.json parse error: ${(e as Error).message}`,\n name: m.name,\n };\n }\n\n const allFingerprints = [\n ...(receipt.canonical_artifact_hashes ?? []),\n ...(receipt.synthesis_hashes ?? []),\n ];\n\n let verified = 0;\n const softWarnings: string[] = [];\n for (const entry of allFingerprints) {\n const artifactPath = join(packageDir, 'pack', entry.path);\n if (!existsSync(artifactPath)) {\n return {\n pass: false,\n reason: `Fingerprinted artifact missing: pack/${entry.path}`,\n name: m.name,\n };\n }\n const actualHash = sha256File(artifactPath);\n if (actualHash !== entry.sha256) {\n // research.yaml is always modified by freeze AFTER the receipt is written.\n // Its receipt hash reflects the pre-freeze state by design — soft-warn, do not fail.\n if (entry.path === 'research.yaml') {\n softWarnings.push(\n `WARN pack/research.yaml hash reflects pre-freeze state (known: freeze writes frozen_at + status after fingerprinting)`,\n );\n verified++;\n continue;\n }\n return {\n pass: false,\n reason: `Hash mismatch for pack/${entry.path}.\\n receipt: ${entry.sha256}\\n actual: ${actualHash}`,\n name: m.name,\n };\n }\n verified++;\n }\n\n return { pass: true, name: m.name, artifactsVerified: verified, softWarnings };\n}\n"],"mappings":";;;;;;;;;;;;AAAA,IAAa,iBAoBA,iBAOA,uBAOA,mBAOA,oBAOA,uBAOA,sBAOA,qBAUA,wBAUA;AAlFb;AAAA;AAAA;AAAO,IAAM,kBAAN,cAA8B,MAAM;AAAA,MACzC,YACE,SACgB,MACA,MAChB,OACgB,WAChB;AACA,cAAM,SAAS,QAAQ,EAAE,MAAM,IAAI,MAAS;AAL5B;AACA;AAEA;AAGhB,aAAK,OAAO;AAAA,MACd;AAAA,MAPkB;AAAA,MACA;AAAA,MAEA;AAAA,IAKpB;AASO,IAAM,kBAAN,cAA8B,gBAAgB;AAAA,MACnD,YAAY,MAAc;AACxB,cAAM,kCAA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AAO,gBAAgB;AACzB,cAAM,IAAI,OAAO;AACjB,gBAAQ,OAAO,MAAM,oBAAoB,EAAE,MAAM,MAAM,GAAG,EAAE,CAAC;AAAA,CAAI;AACjE,gBAAQ,OAAO,MAAM,oBAAoB,EAAE,SAAS;AAAA,CAAI;AACxD,gBAAQ,OAAO,MAAM,oBAAoB,EAAE,OAAO,QAAQ;AAAA,CAAI;AAC9D,gBAAQ,OAAO,MAAM,oBAAoB,EAAE,OAAO,eAAe;AAAA,CAAI;AACrE,gBAAQ,OAAO,MAAM,oBAAoB,EAAE,sBAAsB,MAAM,GAAG,EAAE,CAAC;AAAA,CAAK;AAAA,MACpF;AACA;AAAA,IACF;AACA,YAAQ,OAAO,MAAM;AAAA,CAAsB;AAC3C,YAAQ,OAAO,MAAM,oBAAoB,OAAO,WAAW;AAAA,CAAI;AAC/D,YAAQ,OAAO,MAAM,oBAAoB,OAAO,aAAa,MAAM;AAAA,CAAI;AACvE,eAAW,KAAK,OAAO,aAAc,SAAQ,OAAO,MAAM,OAAO,CAAC;AAAA,CAAI;AACtE,YAAQ,OAAO,MAAM,oBAAoB,OAAO,eAAe,SAAS,MAAM;AAAA,CAAI;AAClF,QAAI,OAAO,SAAS,SAAS,GAAG;AAC9B,cAAQ,OAAO,MAAM;AAAA;AAAA,CAAe;AACpC,iBAAW,KAAK,OAAO,SAAU,SAAQ,OAAO,MAAM,OAAO,CAAC;AAAA,CAAI;AAAA,IACpE;AACA,QAAI,CAAC,OAAO,aAAc,SAAQ,WAAW;AAAA,EAC/C,SAAS,KAAK;AACZ,gBAAY,GAAG;AAAA,EACjB;AACF,CAAC;AAEH,QAAQ,WAAW,QAAQ,IAAI;","names":["z","init_schema","mkdir","readFile","writeFile","existsSync","join","resolve","yamlStringify","init_scaffold","init_schema","init_scaffold","init_schema","mkdir","writeFile","join","URL","receipt","readFile","URL","title","asserts","keyPoints","z","init_schema","mkdir","readFile","writeFile","existsSync","join","init_schema","existsSync","join","resolve","z","init_schema","existsSync","mkdir","readFile","writeFile","dirname","join","excerpts","origin","init_schema","init_schema","init_schema","init_heuristic","DEFAULT_HOST","DEFAULT_MODEL","SYSTEM_PROMPT","init_ollama_intern","init_extractors","init_heuristic","init_ollama_intern","z","init_schema","existsSync","appendFile","mkdir","readFile","writeFile","join","resolve","receipt","init_schema","init_extractors","z","init_schema","existsSync","mkdir","readFile","writeFile","join","resolve","normalize","audit","init_schema","init_schema","init_extractors","init_schema","z","init_schema","init_heuristic","DEFAULT_HOST","DEFAULT_MODEL","DEFAULT_TIMEOUT_MS","SYSTEM_PROMPT","init_ollama_intern","init_heuristic","init_ollama_intern","z","init_schema","existsSync","createHash","mkdir","readFile","writeFile","join","resolve","readClaims","buildMarkdown","init_run","init_schema","createHash","existsSync","appendFile","readFile","writeFile","join","resolve","readTriagedClaimIds","md","init_schema","init_heuristic","init_ollama_intern","z","appendFile","readFile","existsSync","join","map","resolve","candidatesPath","init_schema","z","init_schema","map","buildEffectiveStatuses","map","init_markdown","z","init_schema","existsSync","mkdir","readFile","writeFile","join","resolve","yamlParse","yamlStringify","readSourceCards","readdir","buildEffectiveStatuses","map","loadResearchYaml","init_run","init_schema","init_markdown","init_run","init_markdown","init_schema","existsSync","mkdir","readFile","writeFile","join","z","normalize","EVIDENCE_EXCERPT_JOIN","init_heuristic","asEnum","DEFAULT_HOST","DEFAULT_MODEL","DEFAULT_TIMEOUT_MS","VALID_SEVERITIES","VALID_CONFIDENCES","init_ollama_intern","init_heuristic","init_ollama_intern","init_markdown","createHash","existsSync","appendFile","mkdir","readFile","writeFile","join","resolve","yamlParse","yamlStringify","readJsonl","readSourceCards","readdir","map","loadResearchYaml","readTriagedClaimIds","init_run","init_schema","init_markdown","existsSync","mkdir","readFile","writeFile","appendFile","join","resolve","yamlParse","yamlStringify","init_schema","init_markdown","init_run","init_markdown","init_schema","init_schema","existsSync","dirname","join","init_schema","existsSync","readFile","join","resolve","relative","createHash","yamlParse","readSourceCards","readdir","readGateResult","gate","init_schema","existsSync","resolve","existsSync","mkdir","writeFile","dirname","join","resolve","resolve","readFile","init_schema","z","init_schema","createHash","map","buildEffectiveStatuses","review","gate","z","init_schema","init_markdown","existsSync","mkdir","readFile","writeFile","join","resolve","yamlParse","loadResearchYaml","readJsonl","gate","init_run","init_schema","init_markdown","init_run","init_markdown","init_schema","createHash","latestDecisionByClaim","map","handoff","init_derive","z","init_schema","map","s","init_markdown","existsSync","mkdir","readFile","writeFile","join","resolve","yamlParse","readJsonl","readSourceCards","readdir","handoff","map","relPath","init_run","init_schema","init_derive","init_markdown","init_run","init_derive","init_markdown","init_schema","packId","latestDecisionByClaim","buildEffectiveStatuses","map","buildEffectiveDispositions","review","handoff","buildNextActions","z","HandoffModeSchema","init_schema","init_markdown","existsSync","mkdir","readFile","writeFile","join","resolve","yamlParse","readJsonl","readSourceCards","readdir","readGate","gate","handoff","init_run","init_schema","init_markdown","init_run","init_markdown","init_schema","existsSync","readFile","stat","createHash","join","fileSha256","init_checks","init_markdown","z","init_schema","existsSync","mkdir","readFile","readdir","writeFile","createHash","join","resolve","yamlParse","yamlStringify","packId","handoff","init_run","init_schema","init_checks","init_markdown","init_run","init_markdown","init_schema","z","init_schema","existsSync","mkdir","readFile","readdir","writeFile","dirname","join","relative","resolve","yamlParse","yamlStringify","init_run","init_schema","existsSync","mkdir","rename","writeFile","dirname","join","posix","relative","resolve","sep","z","posixify","moveIfExists","buildReceiptMarkdown","init_review","init_schema","init_run","init_review","init_schema","init_run","init_schema","z","init_schema","asString","asStringOrNull","DEFAULT_HOST","DEFAULT_MODEL","DEFAULT_TIMEOUT_MS","SYSTEM_PROMPT","existsSync","createHash","mkdir","readFile","writeFile","appendFile","join","resolve","yamlParse","query","init_run","init_schema","init_run","init_schema","z","init_schema","existsSync","mkdir","readFile","writeFile","join","resolve","yamlParse","readJsonl","countWords","gate","init_run","init_schema","init_run","init_schema","existsSync","mkdirSync","writeFileSync","readFileSync","readdirSync","join","resolve","createHash","existsSync","join","z","z","z","createHash","existsSync","join","mkdirSync","join","createHash","readFileSync","existsSync","join","createHash","readFileSync","join","existsSync","resolve","existsSync","join","readdirSync","finalReportPath","finalReport","readFileSync","readme","mkdirSync","writeFileSync","resolve","ResearchYamlSchema"]}
1
+ {"version":3,"sources":["../src/errors.ts","../src/intake/schema.ts","../src/intake/scaffold.ts","../src/intake/index.ts","../src/sections/schema.ts","../src/sections/scaffold.ts","../src/sections/index.ts","../src/sources/fetch.ts","../src/sources/url-input.ts","../src/sources/extractors/heuristic.ts","../src/sources/extractors/ollama-intern.ts","../src/sources/extractors/index.ts","../src/sources/schema.ts","../src/sources/cards.ts","../src/sources/gather.ts","../src/sources/excerpts/schema.ts","../src/sources/excerpts/chunk.ts","../src/sources/excerpts/ledger.ts","../src/sources/excerpts/index.ts","../src/sources/index.ts","../src/claims/extractors/heuristic.ts","../src/claims/extractors/ollama-intern.ts","../src/claims/extractors/index.ts","../src/claims/schema.ts","../src/claims/extract.ts","../src/claims/density/schema.ts","../src/claims/density/run.ts","../src/claims/density/index.ts","../src/claims/index.ts","../src/contradictions/schema.ts","../src/contradictions/scope.ts","../src/contradictions/detectors/heuristic.ts","../src/contradictions/detectors/ollama-intern.ts","../src/contradictions/detectors/index.ts","../src/contradictions/markdown.ts","../src/triage/schema.ts","../src/triage/run.ts","../src/contradictions/map.ts","../src/contradictions/resolution-schema.ts","../src/contradictions/resolve.ts","../src/contradictions/index.ts","../src/review/schema.ts","../src/gates/checks/source-floor.ts","../src/gates/checks/claim-integrity.ts","../src/gates/checks/scope-integrity.ts","../src/gates/checks/freshness.ts","../src/gates/checks/contradiction.ts","../src/gates/checks/section-budget.ts","../src/gates/checks/waivers.ts","../src/gates/checks/accepted-claim-floor.ts","../src/gates/checks/index.ts","../src/gates/markdown.ts","../src/gates/schema.ts","../src/gates/run.ts","../src/gates/index.ts","../src/review/profiles.ts","../src/review/reviewers/heuristic.ts","../src/review/reviewers/ollama-intern.ts","../src/review/reviewers/index.ts","../src/review/decision.ts","../src/review/markdown.ts","../src/review/run.ts","../src/review/promote.ts","../src/review/index.ts","../src/indexer/schema.ts","../src/indexer/db.ts","../src/indexer/build.ts","../src/indexer/query.ts","../src/indexer/export.ts","../src/indexer/sync.ts","../src/indexer/index.ts","../src/dispositions/schema.ts","../src/cowork/derive.ts","../src/cowork/schema.ts","../src/cowork/markdown.ts","../src/cowork/run.ts","../src/cowork/index.ts","../src/synth/derive.ts","../src/synth/schema.ts","../src/synth/markdown.ts","../src/synth/run.ts","../src/synth/index.ts","../src/audit/aggregate.ts","../src/audit/schema.ts","../src/audit/markdown.ts","../src/audit/run.ts","../src/audit/index.ts","../src/freeze/checks.ts","../src/freeze/citations.ts","../src/freeze/markdown.ts","../src/freeze/schema.ts","../src/freeze/run.ts","../src/freeze/index.ts","../src/invalidate/schema.ts","../src/invalidate/run.ts","../src/invalidate/review.ts","../src/invalidate/index.ts","../src/triage/index.ts","../src/discover/schema.ts","../src/discover/providers/llm-heuristic.ts","../src/discover/run.ts","../src/discover/index.ts","../src/index.ts","../src/section_report/schema.ts","../src/section_report/run.ts","../src/section_report/index.ts","../src/cli.ts","../src/pack/publish/index.ts","../src/pack/publish/manifest.ts","../src/pack/publish/schema.ts","../src/pack/publish/readme.ts","../src/pack/publish/how-to-read.ts","../src/pack/publish/copy.ts","../src/pack/publish/verify.ts"],"sourcesContent":["export class ResearchOSError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n public readonly hint?: string,\n cause?: Error,\n public readonly retryable?: boolean,\n ) {\n super(message, cause ? { cause } : undefined);\n this.name = 'ResearchOSError';\n }\n}\n\nexport class IntakeValidationError extends ResearchOSError {\n constructor(message: string, public readonly issues: unknown) {\n super(message, 'INTAKE_VALIDATION');\n this.name = 'IntakeValidationError';\n }\n}\n\nexport class PackExistsError extends ResearchOSError {\n constructor(path: string) {\n super(`Pack directory already exists: ${path}`, 'PACK_EXISTS');\n this.name = 'PackExistsError';\n }\n}\n\nexport class TemplateNotFoundError extends ResearchOSError {\n constructor(path: string) {\n super(`Pack template not found at ${path}`, 'TEMPLATE_NOT_FOUND');\n this.name = 'TemplateNotFoundError';\n }\n}\n\nexport class PackNotFoundError extends ResearchOSError {\n constructor(path: string) {\n super(`No research.yaml found at ${path}. Run 'research-os init' first.`, 'PACK_NOT_FOUND');\n this.name = 'PackNotFoundError';\n }\n}\n\nexport class SectionExistsError extends ResearchOSError {\n constructor(id: string) {\n super(`Section already exists: ${id}`, 'SECTION_EXISTS');\n this.name = 'SectionExistsError';\n }\n}\n\nexport class InvalidSectionIdError extends ResearchOSError {\n constructor(id: string) {\n super(`Invalid section id: \"${id}\". Must match pattern NN-slug (e.g. \"01-landscape\").`, 'INVALID_SECTION_ID');\n this.name = 'InvalidSectionIdError';\n }\n}\n\nexport class SectionNotFoundError extends ResearchOSError {\n constructor(id: string) {\n super(`Section not found: ${id}. Run 'research-os section add' first.`, 'SECTION_NOT_FOUND');\n this.name = 'SectionNotFoundError';\n }\n}\n\nexport class NoUrlsProvidedError extends ResearchOSError {\n constructor() {\n super(\n `No URLs provided. Pass --url <url> (repeatable) or --urls-file <path>. 'gather' acquires known sources; discovery/search is a separate step.`,\n 'NO_URLS_PROVIDED',\n );\n this.name = 'NoUrlsProvidedError';\n }\n}\n\nexport class NoSourcesGatheredError extends ResearchOSError {\n constructor(sectionId: string) {\n super(\n `Section \"${sectionId}\" has no gathered sources. Run 'research-os gather ${sectionId} --url ...' first. Claim extraction requires source truth.`,\n 'NO_SOURCES_GATHERED',\n );\n this.name = 'NoSourcesGatheredError';\n }\n}\n\nexport class HandoffNotFoundError extends ResearchOSError {\n constructor() {\n super(\n `No handoff on file at handoffs/cowork-handoff.json. Run 'research-os cowork handoff' first.`,\n 'HANDOFF_NOT_FOUND',\n );\n this.name = 'HandoffNotFoundError';\n }\n}\n\nexport class SynthesisNotReadyError extends ResearchOSError {\n constructor(public readonly mode: string) {\n super(\n `Synthesis workspace refused: pack is in ${mode} mode. Run 'research-os cowork handoff' for repair instructions.`,\n 'SYNTHESIS_NOT_READY',\n );\n this.name = 'SynthesisNotReadyError';\n }\n}\n","import { z } from 'zod';\n\nexport const SectionStatusSchema = z.enum([\n 'draft',\n 'gathering',\n 'gated',\n 'reviewed',\n 'frozen',\n]);\n\nexport const SectionSchema = z.object({\n id: z\n .string()\n .regex(/^[0-9]{2}-[a-z0-9-]+$/, 'Section id must look like \"01-landscape\"'),\n purpose: z.string().min(1),\n max_time_minutes: z.number().int().positive().default(45),\n min_sources: z.number().int().nonnegative().default(8),\n primary_sources_required: z.number().int().nonnegative().default(2),\n contradictions_required: z.boolean().default(true),\n status: SectionStatusSchema.default('draft'),\n});\n\nexport const SourceFloorGateSchema = z.object({\n min_sources: z.number().int().nonnegative().default(8),\n min_independent_publishers: z.number().int().nonnegative().default(4),\n primary_sources_required: z.number().int().nonnegative().default(2),\n primary_source_waiver_allowed: z.boolean().default(true),\n});\n\nexport const ClaimIntegrityGateSchema = z.object({\n every_claim_needs_source: z.boolean().default(true),\n no_orphan_claims: z.boolean().default(true),\n no_source_cluster_monopoly: z.boolean().default(true),\n});\n\nexport const FreshnessGateSchema = z.object({\n required_for_current_topics: z.boolean().default(true),\n stale_source_policy: z.enum(['warn', 'fail']).default('warn'),\n});\n\nexport const ContradictionGateSchema = z.object({\n required: z.boolean().default(true),\n unresolved_contradictions_block_synthesis: z.boolean().default(true),\n});\n\nexport const SectionBudgetGateSchema = z.object({\n max_time_minutes: z.number().int().positive().default(45),\n extension_requires_evidence: z.boolean().default(true),\n});\n\nexport const GateConfigSchema = z.object({\n source_floor: SourceFloorGateSchema.default({}),\n claim_integrity: ClaimIntegrityGateSchema.default({}),\n freshness: FreshnessGateSchema.default({}),\n contradiction: ContradictionGateSchema.default({}),\n section_budget: SectionBudgetGateSchema.default({}),\n});\n\n// Section-scoped source-floor waiver. Each entry stands alone with its own\n// reason + compensating_controls audit trail. Earned by Experiment 3 XRPL\n// Pack Session 2 — canonical-protocol sections (XRPL Foundation docs, XLS\n// standards, rippled implementation) are structurally single-publisher and\n// the global publisher-diversity floor inappropriately fails them. The\n// waiver is per-(section_id, scope), so a section can have separate\n// waivers for different floor checks without weakening the pack default.\nexport const SectionScopedWaiverSchema = z.object({\n section_id: z.string().regex(/^[0-9]{2}-[a-z0-9-]+$/, 'Section id must look like \"01-landscape\"'),\n scope: z.enum(['min_independent_publishers', 'primary_sources_required']),\n reason: z.string().min(1),\n compensating_controls: z.array(z.string()).min(1),\n});\n\nexport const PrimarySourceWaiverSchema = z.object({\n status: z.enum(['none', 'requested', 'granted']).default('none'),\n reason: z.string().optional(),\n compensating_controls: z.array(z.string()).default([]),\n // Section-scoped waivers; each entry is its own waiver record. Independent\n // of the pack-level status/reason/compensating_controls fields above.\n // Defaults to [] for backward compatibility — existing packs unaffected.\n section_waivers: z.array(SectionScopedWaiverSchema).default([]),\n});\n\nexport const FreshnessRequirementsSchema = z.object({\n required: z.boolean().default(true),\n max_source_age_months: z.number().int().positive().nullable().default(null),\n});\n\n// A documented reviewer-profile preset. Bundles the model/window/mode that\n// were known-good (or known-bad) on a given rig so future runs don't have\n// to rediscover timeout/context/false-positive issues. Status:\n// - calibrated_baseline: passed seeded calibration; safe default\n// - experimental: not yet calibrated; results untrusted\n// - deprecated: shipped, then disqualified by calibration\nexport const ReviewProfilePresetSchema = z.object({\n general_model: z.string().nullable().default(null),\n critic_model: z.string().nullable().default(null),\n review_window: z.number().int().positive().nullable().default(null),\n mode: z.enum(['general', 'two_pass']).default('two_pass'),\n status: z\n .enum(['calibrated_baseline', 'experimental', 'deprecated'])\n .default('experimental'),\n notes: z.string().nullable().default(null),\n});\n\nexport const DEFAULT_REVIEW_PROFILES: Record<string, z.input<typeof ReviewProfilePresetSchema>> = {\n // The dogfood-validated baseline. Section 03 of research-os-spec is the\n // calibration fixture: long sources, waiver pressure, 715 candidates,\n // hermes3:8b-only two-pass with window 10 hits 0% false-flag on the\n // seeded fixture and the narrow_critic actually fires.\n 'hermes-two-pass': {\n general_model: 'hermes3:8b',\n critic_model: 'hermes3:8b',\n review_window: 10,\n mode: 'two_pass',\n status: 'calibrated_baseline',\n notes:\n 'Calibrated baseline as of v0.1. 0% good-claim FPR on the seeded fixture; bad-claim any-flag recall 9/13 (69%). Smaller window required because hermes3:8b at 4-bit on a 5080 cannot complete 25-claim windows within a 3-minute budget.',\n },\n};\n\nexport const ResearchYamlSchema = z.object({\n research_os_version: z.string(),\n created_at: z.string(),\n topic: z.string().min(10, 'Topic must be at least 10 characters'),\n decision: z.string().default(''),\n audience: z.string().default('self'),\n desired_output: z.string().default(''),\n max_runtime_minutes: z.number().int().positive().default(240),\n freshness: FreshnessRequirementsSchema.default({}),\n excluded_sources: z.array(z.string()).default([]),\n primary_source_waiver: PrimarySourceWaiverSchema.default({}),\n sections: z.array(SectionSchema).default([]),\n gates: GateConfigSchema.default({}),\n // Reviewer-profile presets baked into the pack so future review runs\n // (across any section in this pack) inherit the calibrated configuration\n // without rediscovering rig-specific timeouts and context issues. Override\n // with `--preset <name>` on `research-os review`.\n review_profiles: z\n .record(z.string(), ReviewProfilePresetSchema)\n .default(() => ({ ...DEFAULT_REVIEW_PROFILES })),\n frozen_at: z.string().nullable().default(null),\n});\n\nexport type Section = z.infer<typeof SectionSchema>;\nexport type GateConfig = z.infer<typeof GateConfigSchema>;\nexport type PrimarySourceWaiver = z.infer<typeof PrimarySourceWaiverSchema>;\nexport type SectionScopedWaiver = z.infer<typeof SectionScopedWaiverSchema>;\nexport type ReviewProfilePreset = z.infer<typeof ReviewProfilePresetSchema>;\nexport type ResearchYaml = z.infer<typeof ResearchYamlSchema>;\n","import { mkdir, writeFile, readFile, readdir, stat } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { stringify as yamlStringify } from 'yaml';\n\nimport { PackExistsError, TemplateNotFoundError } from '../errors.js';\nimport { ResearchYamlSchema, type ResearchYaml } from './schema.js';\nimport type { InitOptions, InitResult } from './types.js';\n\nconst PACKAGE_VERSION = '0.1.0';\n\nexport function slugify(input: string): string {\n const normalized = input\n .toLowerCase()\n .normalize('NFKD')\n .replace(/[̀-ͯ]/g, '')\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 60)\n .replace(/-+$/g, '');\n return normalized || 'research-pack';\n}\n\nfunction findTemplatesDir(): string {\n const here = dirname(fileURLToPath(import.meta.url));\n const candidates = [\n resolve(here, '../templates/pack'),\n resolve(here, '../../templates/pack'),\n resolve(here, '../../../templates/pack'),\n ];\n for (const candidate of candidates) {\n if (existsSync(candidate)) return candidate;\n }\n throw new TemplateNotFoundError(candidates.join(' | '));\n}\n\nasync function copyTreeRelative(srcDir: string, destDir: string, written: string[]): Promise<void> {\n const entries = await readdir(srcDir, { withFileTypes: true });\n for (const entry of entries) {\n const srcPath = join(srcDir, entry.name);\n const destPath = join(destDir, entry.name);\n if (entry.isDirectory()) {\n await mkdir(destPath, { recursive: true });\n await copyTreeRelative(srcPath, destPath, written);\n } else if (entry.isFile()) {\n const data = await readFile(srcPath);\n await writeFile(destPath, data);\n written.push(destPath);\n }\n }\n}\n\nexport function buildResearchYaml(options: InitOptions): ResearchYaml {\n const draft = {\n research_os_version: PACKAGE_VERSION,\n created_at: new Date().toISOString(),\n topic: options.topic,\n decision: options.decision ?? '',\n audience: options.audience ?? 'self',\n desired_output: options.desiredOutput ?? '',\n max_runtime_minutes: options.maxRuntimeMinutes ?? 240,\n freshness: { required: true, max_source_age_months: null },\n excluded_sources: [],\n primary_source_waiver: { status: 'none', compensating_controls: [] },\n sections: [],\n frozen_at: null,\n gates: {\n source_floor: {\n min_sources: 8,\n min_independent_publishers: 4,\n primary_sources_required: 2,\n primary_source_waiver_allowed: true,\n },\n claim_integrity: {\n every_claim_needs_source: true,\n no_orphan_claims: true,\n no_source_cluster_monopoly: true,\n },\n freshness: {\n required_for_current_topics: true,\n stale_source_policy: 'warn',\n },\n contradiction: {\n required: true,\n unresolved_contradictions_block_synthesis: true,\n },\n section_budget: {\n max_time_minutes: 45,\n extension_requires_evidence: true,\n },\n },\n };\n return ResearchYamlSchema.parse(draft);\n}\n\nexport async function init(options: InitOptions): Promise<InitResult> {\n const packName = options.name?.trim() || slugify(options.topic);\n const baseDir = options.outDir ? resolve(options.outDir) : process.cwd();\n const packPath = resolve(baseDir, packName);\n\n if (existsSync(packPath) && !options.force) {\n const s = await stat(packPath);\n if (s.isDirectory()) {\n const entries = await readdir(packPath);\n if (entries.length > 0) throw new PackExistsError(packPath);\n } else {\n throw new PackExistsError(packPath);\n }\n }\n\n const written: string[] = [];\n\n await mkdir(packPath, { recursive: true });\n for (const dir of [\n 'sections',\n 'evidence/source-cards',\n 'synthesis',\n 'audits',\n 'prompts',\n ]) {\n await mkdir(join(packPath, dir), { recursive: true });\n }\n\n const templatesDir = findTemplatesDir();\n await copyTreeRelative(templatesDir, packPath, written);\n\n const research = buildResearchYaml(options);\n const yamlPath = join(packPath, 'research.yaml');\n await writeFile(yamlPath, yamlStringify(research, { lineWidth: 0 }), 'utf8');\n written.push(yamlPath);\n\n const fetchLogPath = join(packPath, 'evidence', 'fetch-log.jsonl');\n const citationLedgerPath = join(packPath, 'evidence', 'citation-ledger.jsonl');\n for (const ledger of [fetchLogPath, citationLedgerPath]) {\n if (!existsSync(ledger)) {\n await writeFile(ledger, '', 'utf8');\n written.push(ledger);\n }\n }\n\n return { packPath, packName, filesWritten: written };\n}\n","export { init, buildResearchYaml, slugify } from './scaffold.js';\nexport type { InitOptions, InitResult } from './types.js';\nexport {\n ResearchYamlSchema,\n SectionSchema,\n GateConfigSchema,\n PrimarySourceWaiverSchema,\n type ResearchYaml,\n type Section,\n type GateConfig,\n type PrimarySourceWaiver,\n} from './schema.js';\n","import { z } from 'zod';\nimport { SectionStatusSchema } from '../intake/schema.js';\n\nexport const SectionGatesYamlSchema = z.object({\n section_id: z\n .string()\n .regex(/^[0-9]{2}-[a-z0-9-]+$/, 'Section id must look like \"01-landscape\"'),\n purpose: z.string().min(1),\n status: SectionStatusSchema,\n created_at: z.string(),\n max_time_minutes: z.number().int().positive(),\n min_sources: z.number().int().nonnegative(),\n primary_sources_required: z.number().int().nonnegative(),\n contradictions_required: z.boolean(),\n});\n\nexport type SectionGatesYaml = z.infer<typeof SectionGatesYamlSchema>;\n","import { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { parse as yamlParse, stringify as yamlStringify } from 'yaml';\n\nimport {\n PackNotFoundError,\n SectionExistsError,\n InvalidSectionIdError,\n} from '../errors.js';\nimport {\n ResearchYamlSchema,\n SectionSchema,\n type Section,\n type ResearchYaml,\n} from '../intake/schema.js';\nimport { SectionGatesYamlSchema, type SectionGatesYaml } from './schema.js';\nimport type { SectionAddOptions, SectionAddResult } from './types.js';\n\nconst SECTION_ID_PATTERN = /^[0-9]{2}-[a-z0-9-]+$/;\n\nfunction briefStub(opts: SectionAddOptions): string {\n return `# Section: ${opts.id}\n\n**Status:** draft\n**Purpose:** ${opts.purpose}\n\n## Findings\n\n_This section has not been gathered yet. Sources, claims, and contradictions will be populated by the section-worker pass._\n\n## What the evidence supports\n\n_To be populated after gathering and gate pass._\n\n## What the evidence does not support\n\n_To be populated._\n\n## Unresolved\n\n_To be populated._\n`;\n}\n\nfunction contradictionsStub(id: string): string {\n return `# Contradictions: ${id}\n\n_No contradictions recorded yet. Each contradiction must include both sides with source IDs from the source ledger._\n\n## Format\n\n\\`\\`\\`\n## Contradiction C-<n>: <short label>\n\n**Side A:** <claim> (source: <source_id>)\n**Side B:** <claim> (source: <source_id>)\n**Status:** unresolved | reconciled-by-<source_id> | preserved-deliberately\n**Notes:** <reason>\n\\`\\`\\`\n`;\n}\n\nfunction openQuestionsStub(id: string): string {\n return `# Open questions: ${id}\n\n_Questions raised by this section that are not resolved within section scope. Cross-section synthesis or additional gathering may resolve them._\n\n## Format\n\n\\`\\`\\`\n- **Q-<n>:** <question> — needs: <evidence-shape>\n\\`\\`\\`\n`;\n}\n\nasync function loadResearchYaml(packPath: string): Promise<{ yaml: ResearchYaml; path: string }> {\n const yamlPath = join(packPath, 'research.yaml');\n if (!existsSync(yamlPath)) throw new PackNotFoundError(packPath);\n const text = await readFile(yamlPath, 'utf8');\n const parsed = ResearchYamlSchema.parse(yamlParse(text));\n return { yaml: parsed, path: yamlPath };\n}\n\nexport async function add(options: SectionAddOptions): Promise<SectionAddResult> {\n if (!SECTION_ID_PATTERN.test(options.id)) {\n throw new InvalidSectionIdError(options.id);\n }\n if (!options.purpose || options.purpose.trim().length === 0) {\n throw new Error('Section purpose is required');\n }\n\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n const { yaml, path: yamlPath } = await loadResearchYaml(packPath);\n\n if (yaml.sections.some((s) => s.id === options.id)) {\n throw new SectionExistsError(options.id);\n }\n\n const newSection: Section = SectionSchema.parse({\n id: options.id,\n purpose: options.purpose,\n max_time_minutes: options.maxTimeMinutes ?? yaml.gates.section_budget.max_time_minutes,\n min_sources: options.minSources ?? yaml.gates.source_floor.min_sources,\n primary_sources_required:\n options.primarySourcesRequired ?? yaml.gates.source_floor.primary_sources_required,\n contradictions_required:\n options.contradictionsRequired ?? yaml.gates.contradiction.required,\n status: 'draft',\n });\n\n const updated: ResearchYaml = ResearchYamlSchema.parse({\n ...yaml,\n sections: [...yaml.sections, newSection],\n });\n\n const sectionPath = join(packPath, 'sections', options.id);\n await mkdir(sectionPath, { recursive: true });\n\n const written: string[] = [];\n\n const writes: Array<[string, string]> = [\n [join(sectionPath, 'brief.md'), briefStub(options)],\n [join(sectionPath, 'sources.jsonl'), ''],\n [join(sectionPath, 'claims.jsonl'), ''],\n [join(sectionPath, 'contradictions.md'), contradictionsStub(options.id)],\n [join(sectionPath, 'open_questions.md'), openQuestionsStub(options.id)],\n ];\n for (const [path, content] of writes) {\n await writeFile(path, content, 'utf8');\n written.push(path);\n }\n\n const gatesYaml: SectionGatesYaml = SectionGatesYamlSchema.parse({\n section_id: newSection.id,\n purpose: newSection.purpose,\n status: newSection.status,\n created_at: new Date().toISOString(),\n max_time_minutes: newSection.max_time_minutes,\n min_sources: newSection.min_sources,\n primary_sources_required: newSection.primary_sources_required,\n contradictions_required: newSection.contradictions_required,\n });\n const gatesPath = join(sectionPath, 'gates.yaml');\n await writeFile(gatesPath, yamlStringify(gatesYaml, { lineWidth: 0 }), 'utf8');\n written.push(gatesPath);\n\n await writeFile(yamlPath, yamlStringify(updated, { lineWidth: 0 }), 'utf8');\n written.push(yamlPath);\n\n return {\n sectionId: newSection.id,\n sectionPath,\n filesWritten: written,\n };\n}\n","export { add } from './scaffold.js';\nexport { SectionGatesYamlSchema, type SectionGatesYaml } from './schema.js';\nexport type { SectionAddOptions, SectionAddResult } from './types.js';\n","import { createHash } from 'node:crypto';\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport { extname, join, relative } from 'node:path';\nimport { URL } from 'node:url';\n\nimport type { FetchReceipt } from './schema.js';\n\nexport interface FetchAttemptResult {\n receipt: FetchReceipt;\n rawText: string | null;\n rawTextAbsPath: string | null;\n}\n\nfunction urlHash(url: string): string {\n return createHash('sha256').update(url).digest('hex').slice(0, 12);\n}\n\nexport function makeSourceId(url: string): string {\n return `src_${urlHash(url)}`;\n}\n\nexport function makeReceiptId(sourceId: string, when: Date): string {\n const ts = when.getTime();\n return `rcpt_${sourceId.replace(/^src_/, '')}_${ts}`;\n}\n\nfunction pickExtension(contentType: string | null, finalUrl: string | null): string {\n if (contentType?.includes('text/html')) return '.html';\n if (contentType?.includes('text/plain')) return '.txt';\n if (contentType?.includes('application/json')) return '.json';\n if (contentType?.includes('text/markdown')) return '.md';\n if (finalUrl) {\n try {\n const ext = extname(new URL(finalUrl).pathname);\n if (ext) return ext;\n } catch {\n /* fall through */\n }\n }\n return '.txt';\n}\n\nfunction isTextLike(contentType: string | null): boolean {\n if (!contentType) return true;\n return (\n contentType.startsWith('text/') ||\n contentType.includes('json') ||\n contentType.includes('xml') ||\n contentType.includes('javascript')\n );\n}\n\nexport interface FetchOptions {\n sectionId: string;\n packPath: string;\n fetchImpl?: typeof fetch;\n}\n\nexport async function fetchOnce(\n url: string,\n options: FetchOptions,\n): Promise<FetchAttemptResult> {\n const fetchImpl = options.fetchImpl ?? globalThis.fetch;\n const sourceId = makeSourceId(url);\n const fetchedAt = new Date();\n const receiptId = makeReceiptId(sourceId, fetchedAt);\n\n const receiptBase = {\n receipt_id: receiptId,\n source_id: sourceId,\n section_id: options.sectionId,\n requested_url: url,\n fetched_at: fetchedAt.toISOString(),\n extraction_outcome: 'skipped' as const,\n extraction_extractor: null,\n extraction_error: null,\n };\n\n let response: Response;\n try {\n response = await fetchImpl(url, {\n redirect: 'follow',\n headers: { 'User-Agent': 'research-os/0.1.0' },\n });\n } catch (err) {\n const receipt: FetchReceipt = {\n ...receiptBase,\n final_url: null,\n status: null,\n status_text: null,\n content_type: null,\n byte_count: null,\n sha256: null,\n title: null,\n raw_text_path: null,\n fetch_outcome: 'network_error',\n fetch_error: err instanceof Error ? err.message : String(err),\n };\n return { receipt, rawText: null, rawTextAbsPath: null };\n }\n\n const finalUrl = response.url || url;\n const contentType = response.headers.get('content-type');\n\n if (!response.ok) {\n const receipt: FetchReceipt = {\n ...receiptBase,\n final_url: finalUrl,\n status: response.status,\n status_text: response.statusText || null,\n content_type: contentType,\n byte_count: null,\n sha256: null,\n title: null,\n raw_text_path: null,\n fetch_outcome: 'http_error',\n fetch_error: `${response.status} ${response.statusText || ''}`.trim(),\n };\n return { receipt, rawText: null, rawTextAbsPath: null };\n }\n\n const buffer = Buffer.from(await response.arrayBuffer());\n const sha256 = createHash('sha256').update(buffer).digest('hex');\n const byteCount = buffer.byteLength;\n\n let rawText: string | null = null;\n let rawTextRelPath: string | null = null;\n let rawTextAbsPath: string | null = null;\n\n if (isTextLike(contentType)) {\n rawText = buffer.toString('utf8');\n const ext = pickExtension(contentType, finalUrl);\n const dir = join(options.packPath, 'evidence', 'raw');\n await mkdir(dir, { recursive: true });\n const abs = join(dir, `${sourceId}${ext}`);\n await writeFile(abs, rawText, 'utf8');\n rawTextRelPath = relative(options.packPath, abs).split('\\\\').join('/');\n rawTextAbsPath = abs;\n }\n\n let title: string | null = null;\n if (rawText && contentType?.includes('text/html')) {\n const m = /<title[^>]*>([\\s\\S]*?)<\\/title>/i.exec(rawText);\n if (m && m[1]) title = m[1].trim() || null;\n }\n\n const receipt: FetchReceipt = {\n ...receiptBase,\n final_url: finalUrl,\n status: response.status,\n status_text: response.statusText || null,\n content_type: contentType,\n byte_count: byteCount,\n sha256,\n title,\n raw_text_path: rawTextRelPath,\n fetch_outcome: 'ok',\n fetch_error: null,\n };\n\n return { receipt, rawText, rawTextAbsPath };\n}\n","import { readFile } from 'node:fs/promises';\n\nexport function parseUrlsFileText(text: string): string[] {\n return text\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter((line) => line.length > 0 && !line.startsWith('#'));\n}\n\nexport async function readUrlsFile(path: string): Promise<string[]> {\n const text = await readFile(path, 'utf8');\n return parseUrlsFileText(text);\n}\n\nfunction isValidHttpUrl(candidate: string): boolean {\n try {\n const u = new URL(candidate);\n return u.protocol === 'http:' || u.protocol === 'https:';\n } catch {\n return false;\n }\n}\n\nexport function dedupeAndValidate(urls: string[]): { valid: string[]; invalid: string[] } {\n const seen = new Set<string>();\n const valid: string[] = [];\n const invalid: string[] = [];\n for (const u of urls) {\n if (!isValidHttpUrl(u)) {\n invalid.push(u);\n continue;\n }\n const norm = u;\n if (seen.has(norm)) continue;\n seen.add(norm);\n valid.push(norm);\n }\n return { valid, invalid };\n}\n\nexport async function collectUrls(input: {\n urls?: string[];\n urlsFile?: string;\n}): Promise<{ urls: string[]; invalid: string[] }> {\n const collected: string[] = [];\n if (input.urls) collected.push(...input.urls);\n if (input.urlsFile) collected.push(...(await readUrlsFile(input.urlsFile)));\n const { valid, invalid } = dedupeAndValidate(collected);\n return { urls: valid, invalid };\n}\n","import * as cheerio from 'cheerio';\nimport { URL } from 'node:url';\n\nimport type {\n Extractor,\n ExtractionInput,\n ExtractionResult,\n Relevance,\n SourceType,\n} from '../types.js';\n\nfunction deriveSourceType(rawUrl: string, finalUrl: string | null): SourceType {\n const u = finalUrl ?? rawUrl;\n let host: string;\n try {\n host = new URL(u).hostname.toLowerCase();\n } catch {\n return 'unknown';\n }\n if (host.startsWith('docs.') || host.endsWith('.readthedocs.io')) return 'docs';\n if (host === 'github.com' && /\\/(issues|pull|discussions)\\//.test(u)) return 'forum';\n if (host === 'news.ycombinator.com' || host.endsWith('reddit.com') || host.endsWith('stackoverflow.com'))\n return 'forum';\n if (host.endsWith('arxiv.org') || host.endsWith('semanticscholar.org')) return 'primary';\n if (host.endsWith('paperswithcode.com')) return 'benchmark';\n if (host.endsWith('anthropic.com') || host.endsWith('openai.com') || host.endsWith('claude.com'))\n return 'primary';\n return 'secondary';\n}\n\nfunction clean(text: string | undefined | null): string {\n return (text ?? '').replace(/\\s+/g, ' ').trim();\n}\n\nexport class HeuristicExtractor implements Extractor {\n readonly name = 'heuristic' as const;\n\n async available(): Promise<boolean> {\n return true;\n }\n\n async extract(input: ExtractionInput): Promise<ExtractionResult> {\n if (!input.rawText) {\n return { ok: false, error: 'No raw text available for extraction' };\n }\n const isHtml = (input.contentType ?? '').includes('text/html') || /<html/i.test(input.rawText);\n\n if (!isHtml) {\n const title = clean(input.rawText.split(/\\r?\\n/, 1)[0] || '').slice(0, 200);\n const asserts = title || clean(input.rawText).slice(0, 240);\n const keyPoints = clean(input.rawText)\n .split(/(?<=[.!?])\\s+/)\n .slice(0, 3)\n .map((s) => clean(s))\n .filter((s) => s.length > 0);\n return {\n ok: true,\n publisher: null,\n published_at: null,\n title: title || '(untitled)',\n source_type: deriveSourceType(input.url, input.finalUrl),\n relevance: 'unknown',\n key_points: keyPoints,\n limitations: [],\n asserts: asserts || '(empty)',\n scope: null,\n not: null,\n };\n }\n\n const $ = cheerio.load(input.rawText);\n\n $('script, style, noscript, nav, header, footer').remove();\n\n const title =\n clean($('meta[property=\"og:title\"]').attr('content')) ||\n clean($('meta[name=\"twitter:title\"]').attr('content')) ||\n clean($('title').first().text()) ||\n clean($('h1').first().text()) ||\n '(untitled)';\n\n const description =\n clean($('meta[property=\"og:description\"]').attr('content')) ||\n clean($('meta[name=\"description\"]').attr('content')) ||\n '';\n\n let publisher: string | null =\n clean($('meta[property=\"og:site_name\"]').attr('content')) || null;\n if (!publisher) {\n try {\n publisher = new URL(input.finalUrl ?? input.url).hostname;\n } catch {\n publisher = null;\n }\n }\n\n let publishedAt: string | null =\n clean($('meta[property=\"article:published_time\"]').attr('content')) ||\n clean($('meta[name=\"date\"]').attr('content')) ||\n clean($('time[datetime]').first().attr('datetime')) ||\n null;\n if (publishedAt === '') publishedAt = null;\n\n const mainNode =\n $('article').first().length > 0\n ? $('article').first()\n : $('main').first().length > 0\n ? $('main').first()\n : $('body');\n\n const paragraphs = mainNode\n .find('p')\n .map((_, el) => clean($(el).text()))\n .get()\n .filter((t) => t.length > 40);\n\n const keyPoints = paragraphs.slice(0, 5);\n const asserts = description || paragraphs[0] || title;\n\n return {\n ok: true,\n publisher,\n published_at: publishedAt,\n title,\n source_type: deriveSourceType(input.url, input.finalUrl),\n relevance: 'unknown' as Relevance,\n key_points: keyPoints,\n limitations: [],\n asserts: asserts.slice(0, 600),\n scope: null,\n not: null,\n };\n }\n}\n","import type {\n Extractor,\n ExtractionInput,\n ExtractionResult,\n SourceType,\n Relevance,\n} from '../types.js';\n\nconst DEFAULT_HOST = 'http://localhost:11434';\nconst DEFAULT_MODEL = 'hermes3:8b';\n\nexport function normalizeOllamaHost(host: string): string {\n const trimmed = host.trim().replace(/\\/+$/, '');\n if (/^https?:\\/\\//i.test(trimmed)) return trimmed;\n return `http://${trimmed}`;\n}\n\nconst SYSTEM_PROMPT = `You are an extractor for a gated research pack. Given the URL, content type, and raw text of a fetched source, return ONE JSON object with these fields and no other prose:\n\n{\n \"publisher\": string | null,\n \"published_at\": ISO-8601 string | null,\n \"title\": short string,\n \"source_type\": \"primary\" | \"secondary\" | \"forum\" | \"benchmark\" | \"docs\" | \"unknown\",\n \"relevance\": \"high\" | \"medium\" | \"low\" | \"unknown\",\n \"key_points\": string[] // 3-5 short factual points the source actually makes\n \"limitations\": string[] // honest caveats about source quality, recency, scope\n \"asserts\": string // ONE sentence summarizing what the source claims as its main thrust\n \"scope\": string | null // ONE sentence naming the contextual scope of \"asserts\" (the situation, system, or domain to which it applies). null only if the scope is genuinely indeterminable from the source.\n \"not\": string | null // ONE sentence stating what the source explicitly is NOT a claim about, to prevent overgeneralization. null if no such limit can be inferred.\n}\n\nBe strict. Do not fabricate. If the source does not state a value, leave it null. If the source argues a contextual position, \"scope\" must reflect that context — never widen a contextual claim into a universal one.`;\n\nexport interface OllamaConfig {\n host?: string;\n model?: string;\n timeoutMs?: number;\n fetchImpl?: typeof fetch;\n}\n\nexport class OllamaInternExtractor implements Extractor {\n readonly name = 'ollama-intern' as const;\n private readonly host: string;\n private readonly model: string;\n private readonly timeoutMs: number;\n private readonly fetchImpl: typeof fetch;\n\n constructor(config: OllamaConfig = {}) {\n this.host = normalizeOllamaHost(config.host ?? process.env.OLLAMA_HOST ?? DEFAULT_HOST);\n this.model = config.model ?? process.env.OLLAMA_INTERN_MODEL ?? DEFAULT_MODEL;\n this.timeoutMs = config.timeoutMs ?? 60_000;\n this.fetchImpl = config.fetchImpl ?? globalThis.fetch;\n }\n\n async available(): Promise<boolean> {\n try {\n const ctrl = new AbortController();\n const t = setTimeout(() => ctrl.abort(), 1500);\n const res = await this.fetchImpl(`${this.host}/api/tags`, { signal: ctrl.signal });\n clearTimeout(t);\n if (!res.ok) return false;\n const body = (await res.json()) as { models?: Array<{ name: string }> };\n const names = (body.models ?? []).map((m) => m.name);\n return names.some((n) => n === this.model || n.startsWith(this.model.split(':')[0]));\n } catch {\n return false;\n }\n }\n\n async extract(input: ExtractionInput): Promise<ExtractionResult> {\n if (!input.rawText) {\n return { ok: false, error: 'No raw text available for extraction' };\n }\n\n const truncated = input.rawText.slice(0, 16_000);\n const userMsg = `URL: ${input.url}\\nFinal URL: ${input.finalUrl ?? input.url}\\nContent-Type: ${input.contentType ?? 'unknown'}\\n\\nRAW TEXT BEGIN\\n${truncated}\\nRAW TEXT END`;\n\n const ctrl = new AbortController();\n const t = setTimeout(() => ctrl.abort(), this.timeoutMs);\n\n let body: { message?: { content?: string }; response?: string };\n try {\n const res = await this.fetchImpl(`${this.host}/api/chat`, {\n method: 'POST',\n signal: ctrl.signal,\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n model: this.model,\n stream: false,\n format: 'json',\n messages: [\n { role: 'system', content: SYSTEM_PROMPT },\n { role: 'user', content: userMsg },\n ],\n }),\n });\n if (!res.ok) {\n return { ok: false, error: `Ollama HTTP ${res.status}` };\n }\n body = (await res.json()) as typeof body;\n } catch (err) {\n return {\n ok: false,\n error: err instanceof Error ? err.message : 'Ollama request failed',\n };\n } finally {\n clearTimeout(t);\n }\n\n const text = body.message?.content ?? body.response ?? '';\n let parsed: Record<string, unknown>;\n try {\n parsed = JSON.parse(text);\n } catch {\n return { ok: false, error: 'Ollama response was not valid JSON' };\n }\n\n const sourceTypes: SourceType[] = ['primary', 'secondary', 'forum', 'benchmark', 'docs', 'unknown'];\n const relevances: Relevance[] = ['high', 'medium', 'low', 'unknown'];\n\n const sourceType = sourceTypes.includes(parsed.source_type as SourceType)\n ? (parsed.source_type as SourceType)\n : 'unknown';\n const relevance = relevances.includes(parsed.relevance as Relevance)\n ? (parsed.relevance as Relevance)\n : 'unknown';\n\n const stringOrNull = (v: unknown): string | null =>\n typeof v === 'string' && v.trim().length > 0 ? v.trim() : null;\n\n const stringArray = (v: unknown): string[] =>\n Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string').map((s) => s.trim()) : [];\n\n return {\n ok: true,\n publisher: stringOrNull(parsed.publisher),\n published_at: stringOrNull(parsed.published_at),\n title: typeof parsed.title === 'string' && parsed.title.trim().length > 0 ? parsed.title.trim() : '(untitled)',\n source_type: sourceType,\n relevance,\n key_points: stringArray(parsed.key_points),\n limitations: stringArray(parsed.limitations),\n asserts: typeof parsed.asserts === 'string' && parsed.asserts.trim().length > 0 ? parsed.asserts.trim() : '(no assertion extracted)',\n scope: stringOrNull(parsed.scope),\n not: stringOrNull(parsed.not),\n };\n }\n}\n","import type { Extractor } from '../types.js';\nimport { HeuristicExtractor } from './heuristic.js';\nimport { OllamaInternExtractor } from './ollama-intern.js';\n\nexport { HeuristicExtractor } from './heuristic.js';\nexport { OllamaInternExtractor } from './ollama-intern.js';\n\nexport function defaultExtractors(): Extractor[] {\n return [new OllamaInternExtractor(), new HeuristicExtractor()];\n}\n\nexport async function pickExtractor(extractors: Extractor[]): Promise<Extractor> {\n for (const e of extractors) {\n if (await e.available()) return e;\n }\n throw new Error(\n 'No extractor available. The HeuristicExtractor should always be available — this indicates a bug.',\n );\n}\n","import { z } from 'zod';\n\nexport const SourceTypeSchema = z.enum([\n 'primary',\n 'secondary',\n 'forum',\n 'benchmark',\n 'docs',\n 'unknown',\n]);\n\nexport const RelevanceSchema = z.enum(['high', 'medium', 'low', 'unknown']);\n\nexport const ExtractorNameSchema = z.enum(['heuristic', 'ollama-intern']);\n\nexport const FetchReceiptSchema = z.object({\n receipt_id: z.string().regex(/^rcpt_[a-z0-9]+_\\d+$/),\n source_id: z.string().regex(/^src_[a-f0-9]{12}$/),\n section_id: z.string().regex(/^[0-9]{2}-[a-z0-9-]+$/),\n requested_url: z.string().url(),\n final_url: z.string().url().nullable(),\n status: z.number().int().nullable(),\n status_text: z.string().nullable(),\n content_type: z.string().nullable(),\n fetched_at: z.string(),\n byte_count: z.number().int().nonnegative().nullable(),\n sha256: z.string().regex(/^[a-f0-9]{64}$/).nullable(),\n title: z.string().nullable(),\n raw_text_path: z.string().nullable(),\n fetch_outcome: z.enum(['ok', 'http_error', 'network_error']),\n fetch_error: z.string().nullable(),\n extraction_outcome: z.enum(['ok', 'failed', 'skipped']),\n extraction_extractor: ExtractorNameSchema.nullable(),\n extraction_error: z.string().nullable(),\n});\n\nexport const SourceCardSchema = z.object({\n source_id: z.string().regex(/^src_[a-f0-9]{12}$/),\n receipt_id: z.string().regex(/^rcpt_[a-z0-9]+_\\d+$/),\n section_id: z.string().regex(/^[0-9]{2}-[a-z0-9-]+$/),\n url: z.string().url(),\n final_url: z.string().url().nullable(),\n fetched_at: z.string(),\n publisher: z.string().nullable(),\n published_at: z.string().nullable(),\n title: z.string().min(1),\n source_type: SourceTypeSchema,\n relevance: RelevanceSchema,\n key_points: z.array(z.string()),\n limitations: z.array(z.string()),\n asserts: z.string().min(1),\n scope: z.string().nullable(),\n not: z.string().nullable(),\n extracted_by: ExtractorNameSchema,\n extracted_at: z.string(),\n});\n\nexport type FetchReceipt = z.infer<typeof FetchReceiptSchema>;\nexport type SourceCard = z.infer<typeof SourceCardSchema>;\n","import { mkdir, readFile, writeFile, appendFile } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\n\nimport { SourceCardSchema, type FetchReceipt, type SourceCard } from './schema.js';\nimport type { ExtractionResult, ExtractorName } from './types.js';\n\nexport function buildCard(args: {\n receipt: FetchReceipt;\n extraction: Extract<ExtractionResult, { ok: true }>;\n extractedBy: ExtractorName;\n}): SourceCard {\n const { receipt, extraction, extractedBy } = args;\n const card = SourceCardSchema.parse({\n source_id: receipt.source_id,\n receipt_id: receipt.receipt_id,\n section_id: receipt.section_id,\n url: receipt.requested_url,\n final_url: receipt.final_url,\n fetched_at: receipt.fetched_at,\n publisher: extraction.publisher,\n published_at: extraction.published_at,\n title: extraction.title,\n source_type: extraction.source_type,\n relevance: extraction.relevance,\n key_points: extraction.key_points,\n limitations: extraction.limitations,\n asserts: extraction.asserts,\n scope: extraction.scope,\n not: extraction.not,\n extracted_by: extractedBy,\n extracted_at: new Date().toISOString(),\n });\n return card;\n}\n\nexport async function writeSourceCard(packPath: string, card: SourceCard): Promise<string> {\n const dir = join(packPath, 'evidence', 'source-cards');\n await mkdir(dir, { recursive: true });\n const cardPath = join(dir, `${card.source_id}.json`);\n await writeFile(cardPath, JSON.stringify(card, null, 2), 'utf8');\n return cardPath;\n}\n\nexport async function appendFetchLog(packPath: string, receipt: FetchReceipt): Promise<void> {\n const path = join(packPath, 'evidence', 'fetch-log.jsonl');\n await appendFile(path, JSON.stringify(receipt) + '\\n', 'utf8');\n}\n\nexport async function appendSectionSourceId(\n packPath: string,\n sectionId: string,\n sourceId: string,\n): Promise<void> {\n const path = join(packPath, 'sections', sectionId, 'sources.jsonl');\n if (!existsSync(path)) {\n await writeFile(path, '', 'utf8');\n }\n const existing = await readFile(path, 'utf8');\n const ids = new Set(\n existing\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter(Boolean)\n .map((line) => {\n try {\n return (JSON.parse(line) as { source_id: string }).source_id;\n } catch {\n return null;\n }\n })\n .filter((x): x is string => x !== null),\n );\n if (ids.has(sourceId)) return;\n await appendFile(path, JSON.stringify({ source_id: sourceId, added_at: new Date().toISOString() }) + '\\n', 'utf8');\n}\n","import { existsSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\n\nimport {\n NoUrlsProvidedError,\n PackNotFoundError,\n SectionNotFoundError,\n} from '../errors.js';\nimport { fetchOnce } from './fetch.js';\nimport { collectUrls } from './url-input.js';\nimport { defaultExtractors, pickExtractor } from './extractors/index.js';\nimport {\n appendFetchLog,\n appendSectionSourceId,\n buildCard,\n writeSourceCard,\n} from './cards.js';\nimport type { GatherOptions, GatherSummary, Extractor } from './types.js';\n\nexport async function gather(options: GatherOptions): Promise<GatherSummary> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n if (!existsSync(join(packPath, 'research.yaml'))) throw new PackNotFoundError(packPath);\n if (!existsSync(join(packPath, 'sections', options.sectionId)))\n throw new SectionNotFoundError(options.sectionId);\n\n const { urls } = await collectUrls({ urls: options.urls, urlsFile: options.urlsFile });\n if (urls.length === 0) throw new NoUrlsProvidedError();\n\n const extractorList: Extractor[] = options.extractors ?? defaultExtractors();\n const extractor = await pickExtractor(extractorList);\n\n const summary: GatherSummary = {\n sectionId: options.sectionId,\n attempted: urls.length,\n fetchedOk: 0,\n fetchedFailed: 0,\n extractedOk: 0,\n extractedFailed: 0,\n cardsWritten: 0,\n receiptsAppended: 0,\n sourceIds: [],\n };\n\n for (const url of urls) {\n const { receipt, rawText } = await fetchOnce(url, {\n sectionId: options.sectionId,\n packPath,\n fetchImpl: options.fetchImpl,\n });\n\n let receiptToWrite = receipt;\n\n if (receipt.fetch_outcome === 'ok' && rawText !== null) {\n summary.fetchedOk += 1;\n const result = await extractor.extract({\n url,\n finalUrl: receipt.final_url,\n rawText,\n contentType: receipt.content_type,\n });\n if (result.ok) {\n summary.extractedOk += 1;\n receiptToWrite = {\n ...receipt,\n extraction_outcome: 'ok',\n extraction_extractor: extractor.name,\n extraction_error: null,\n };\n const card = buildCard({ receipt: receiptToWrite, extraction: result, extractedBy: extractor.name });\n await writeSourceCard(packPath, card);\n await appendSectionSourceId(packPath, options.sectionId, card.source_id);\n summary.cardsWritten += 1;\n summary.sourceIds.push(card.source_id);\n } else {\n summary.extractedFailed += 1;\n receiptToWrite = {\n ...receipt,\n extraction_outcome: 'failed',\n extraction_extractor: extractor.name,\n extraction_error: result.error,\n };\n }\n } else {\n summary.fetchedFailed += 1;\n }\n\n await appendFetchLog(packPath, receiptToWrite);\n summary.receiptsAppended += 1;\n }\n\n return summary;\n}\n","import { z } from 'zod';\n\n// Excerpts are deterministic source spans owned by research-os.\n// Models may interpret excerpts; they may not author them.\n//\n// Excerpt ID format: ex_<source_id_hex_12>_<3-digit_index>\n// e.g. ex_abcdef012345_001\nexport const EXCERPT_ID_PATTERN = /^ex_[a-f0-9]{12}_\\d{3,}$/;\n\nexport const ExcerptOriginSchema = z.enum(['raw_text', 'key_point']);\n\nexport const ExcerptSchema = z.object({\n excerpt_id: z.string().regex(EXCERPT_ID_PATTERN),\n source_id: z.string().regex(/^src_[a-f0-9]{12}$/),\n source_hash: z.string().regex(/^[a-f0-9]{64}$/).nullable(),\n text: z.string().min(1),\n location_hint: z.string().nullable(),\n char_start: z.number().int().nonnegative(),\n char_end: z.number().int().nonnegative(),\n origin: ExcerptOriginSchema,\n created_at: z.string(),\n});\n\nexport type Excerpt = z.infer<typeof ExcerptSchema>;\nexport type ExcerptOrigin = z.infer<typeof ExcerptOriginSchema>;\n","// Deterministic source-span chunker. Given raw text (HTML or plain), produces a\n// stable ordered list of excerpts. Same input → same output, byte-for-byte.\n// The model never authors evidence spans; this is where they come from.\n\nconst MIN_EXCERPT_CHARS = 30;\nconst MAX_EXCERPT_CHARS = 800;\n\nconst HTML_ENTITIES: Record<string, string> = {\n '&amp;': '&',\n '&lt;': '<',\n '&gt;': '>',\n '&quot;': '\"',\n '&#39;': \"'\",\n '&apos;': \"'\",\n '&nbsp;': ' ',\n};\n\nfunction decodeEntities(s: string): string {\n return s.replace(/&(amp|lt|gt|quot|#39|apos|nbsp);/g, (m) => HTML_ENTITIES[m] ?? m);\n}\n\nfunction looksLikeHtml(text: string): boolean {\n return /<\\/?(p|div|br|li|h[1-6]|article|section|main|body|html)\\b/i.test(text);\n}\n\n// Replace block-level HTML tags with paragraph breaks, then strip inline tags.\n// Preserves character flow but forces paragraph boundaries.\nfunction htmlToParagraphedText(text: string): string {\n let t = text\n .replace(/<script[\\s\\S]*?<\\/script>/gi, ' ')\n .replace(/<style[\\s\\S]*?<\\/style>/gi, ' ')\n .replace(/<\\/(p|div|li|h[1-6]|article|section|main|tr|table|blockquote)>/gi, '\\n\\n')\n .replace(/<br\\s*\\/?>/gi, '\\n')\n .replace(/<(p|div|li|h[1-6]|article|section|main|tr|table|blockquote)\\b[^>]*>/gi, '\\n\\n')\n .replace(/<[^>]+>/g, ' ');\n t = decodeEntities(t);\n // Normalise within-line whitespace but preserve paragraph breaks (\\n\\n+).\n t = t.replace(/[ \\t]+/g, ' ');\n t = t.replace(/\\n{2,}/g, '\\n\\n');\n t = t.replace(/[ \\t]*\\n[ \\t]*/g, '\\n');\n return t.trim();\n}\n\nfunction plainToParagraphedText(text: string): string {\n let t = text.replace(/\\r\\n/g, '\\n').replace(/\\r/g, '\\n');\n t = t.replace(/[ \\t]+/g, ' ');\n t = t.replace(/\\n{2,}/g, '\\n\\n');\n return t.trim();\n}\n\nexport interface ExcerptDraft {\n text: string;\n char_start: number;\n char_end: number;\n location_hint: string | null;\n}\n\n// Split a paragraph into sentences. Conservative: only splits on .!? followed\n// by whitespace + uppercase / end-of-text. Won't split inside common abbreviations.\nfunction splitSentences(paragraph: string): string[] {\n // Quick path: short paragraph stays intact.\n if (paragraph.length <= MAX_EXCERPT_CHARS) return [paragraph];\n const out: string[] = [];\n let buf = '';\n for (let i = 0; i < paragraph.length; i += 1) {\n const ch = paragraph[i]!;\n buf += ch;\n if (ch === '.' || ch === '!' || ch === '?') {\n const next = paragraph[i + 1];\n const nextNext = paragraph[i + 2];\n // boundary if next is space and nextNext is uppercase, OR end of string\n if (\n next === undefined ||\n (next === ' ' && nextNext !== undefined && /[A-Z0-9\"'([]/u.test(nextNext))\n ) {\n out.push(buf.trim());\n buf = '';\n }\n }\n }\n if (buf.trim().length > 0) out.push(buf.trim());\n // Merge tiny tail-fragments so we don't produce sub-min excerpts here.\n const merged: string[] = [];\n for (const s of out) {\n if (merged.length > 0 && (merged[merged.length - 1]!.length < MIN_EXCERPT_CHARS || s.length < MIN_EXCERPT_CHARS)) {\n merged[merged.length - 1] = `${merged[merged.length - 1]} ${s}`.trim();\n } else {\n merged.push(s);\n }\n }\n return merged;\n}\n\n// Produces a stable ordered list of excerpt drafts from raw source text.\n// char_start/char_end are positions inside the *cleaned* paragraphed text,\n// not the original raw HTML — that's intentional: the cleaned text is what\n// the model sees, so offsets must be reproducible from it.\nexport function chunkRawText(rawText: string): { cleaned: string; drafts: ExcerptDraft[] } {\n const cleaned = looksLikeHtml(rawText) ? htmlToParagraphedText(rawText) : plainToParagraphedText(rawText);\n const drafts: ExcerptDraft[] = [];\n if (cleaned.length === 0) return { cleaned, drafts };\n\n // Walk the cleaned text and recover paragraph offsets so char_start/char_end\n // are accurate inside `cleaned`.\n const paragraphRegex = /([^\\n][\\s\\S]*?)(?:\\n\\n+|$)/g;\n let m: RegExpExecArray | null;\n let paraIndex = 0;\n while ((m = paragraphRegex.exec(cleaned)) !== null) {\n const paraText = m[1]!.trim();\n if (paraText.length === 0) continue;\n paraIndex += 1;\n const paraStart = m.index;\n const sentences = splitSentences(paraText);\n let cursor = 0;\n for (const sentence of sentences) {\n // Locate the sentence inside the original paragraph at-or-after cursor.\n const idxInPara = m[1]!.indexOf(sentence, cursor);\n const start = idxInPara >= 0 ? paraStart + idxInPara : paraStart;\n const end = idxInPara >= 0 ? start + sentence.length : start + sentence.length;\n cursor = idxInPara >= 0 ? idxInPara + sentence.length : cursor + sentence.length;\n let text = sentence;\n if (text.length > MAX_EXCERPT_CHARS) {\n text = text.slice(0, MAX_EXCERPT_CHARS).trimEnd() + ' …';\n }\n if (text.length < MIN_EXCERPT_CHARS) continue;\n drafts.push({\n text,\n char_start: start,\n char_end: end,\n location_hint: `paragraph ${paraIndex}`,\n });\n }\n }\n return { cleaned, drafts };\n}\n\n// Build excerpt drafts from source-card key_points (used when no raw text is\n// available — still deterministic).\nexport function chunkKeyPoints(keyPoints: string[]): ExcerptDraft[] {\n const drafts: ExcerptDraft[] = [];\n let cursor = 0;\n let kpIndex = 0;\n for (const kpRaw of keyPoints) {\n const kp = kpRaw.trim();\n if (kp.length === 0) continue;\n kpIndex += 1;\n let text = kp;\n if (text.length > MAX_EXCERPT_CHARS) {\n text = text.slice(0, MAX_EXCERPT_CHARS).trimEnd() + ' …';\n }\n // Skip too-short key points: they'd fail evidence_excerpt min length anyway.\n if (text.length < 1) continue;\n drafts.push({\n text,\n char_start: cursor,\n char_end: cursor + text.length,\n location_hint: `key_point ${kpIndex}`,\n });\n cursor += text.length + 2;\n }\n return drafts;\n}\n","import { existsSync } from 'node:fs';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\n\nimport { chunkKeyPoints, chunkRawText } from './chunk.js';\nimport { ExcerptSchema, type Excerpt, type ExcerptOrigin } from './schema.js';\nimport type { SourceCard } from '../schema.js';\n\nexport function ledgerPathFor(packPath: string, sourceId: string): string {\n return join(packPath, 'evidence', 'excerpts', `${sourceId}.jsonl`);\n}\n\nfunction makeExcerptId(sourceId: string, index: number): string {\n // 1-indexed, zero-padded to at least 3 digits.\n const idx = String(index).padStart(3, '0');\n // Source IDs are always src_<12 hex>; strip the prefix so excerpts mirror the hex.\n const hex = sourceId.replace(/^src_/, '');\n return `ex_${hex}_${idx}`;\n}\n\nasync function readLedger(path: string): Promise<Excerpt[]> {\n const text = await readFile(path, 'utf8');\n const out: Excerpt[] = [];\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n out.push(ExcerptSchema.parse(JSON.parse(line)));\n } catch {\n /* skip malformed line — append-only ledgers tolerate corrupt tails */\n }\n }\n return out;\n}\n\nasync function writeLedger(path: string, excerpts: Excerpt[]): Promise<void> {\n await mkdir(dirname(path), { recursive: true });\n const body = excerpts.map((e) => JSON.stringify(e)).join('\\n') + (excerpts.length > 0 ? '\\n' : '');\n await writeFile(path, body, 'utf8');\n}\n\nexport interface LoadOrBuildArgs {\n packPath: string;\n sourceCard: SourceCard;\n sourceHash: string | null;\n rawText: string | null;\n now?: () => string;\n}\n\nexport interface LoadOrBuildResult {\n excerpts: Excerpt[];\n origin: ExcerptOrigin | 'mixed';\n built: boolean;\n}\n\n// Returns the excerpt ledger for a source. If it already exists on disk, load\n// it (deterministic input → already-deterministic ledger). Otherwise build it\n// from raw text when available, falling back to source card key_points.\nexport async function loadOrBuildLedger(args: LoadOrBuildArgs): Promise<LoadOrBuildResult> {\n const { packPath, sourceCard, sourceHash, rawText } = args;\n const now = args.now ?? (() => new Date().toISOString());\n const path = ledgerPathFor(packPath, sourceCard.source_id);\n\n if (existsSync(path)) {\n const excerpts = await readLedger(path);\n if (excerpts.length > 0) {\n const origins = new Set(excerpts.map((e) => e.origin));\n const origin: ExcerptOrigin | 'mixed' = origins.size === 1 ? (excerpts[0]!.origin) : 'mixed';\n return { excerpts, origin, built: false };\n }\n }\n\n let drafts;\n let origin: ExcerptOrigin;\n if (rawText && rawText.trim().length > 0) {\n drafts = chunkRawText(rawText).drafts;\n origin = 'raw_text';\n }\n if (!drafts || drafts.length === 0) {\n drafts = chunkKeyPoints(sourceCard.key_points);\n origin = 'key_point';\n }\n\n const createdAt = now();\n const excerpts: Excerpt[] = drafts.map((d, i) => ({\n excerpt_id: makeExcerptId(sourceCard.source_id, i + 1),\n source_id: sourceCard.source_id,\n source_hash: sourceHash,\n text: d.text,\n location_hint: d.location_hint,\n char_start: d.char_start,\n char_end: d.char_end,\n origin: origin!,\n created_at: createdAt,\n }));\n\n await writeLedger(path, excerpts);\n\n return { excerpts, origin: origin!, built: true };\n}\n\n// Render excerpts in the order the model will see them.\nexport function renderLedgerForPrompt(excerpts: Excerpt[]): string {\n return excerpts\n .map((e) => `${e.excerpt_id}${e.location_hint ? ` (${e.location_hint})` : ''}: ${e.text}`)\n .join('\\n');\n}\n\nexport function buildExcerptIndex(excerpts: Excerpt[]): Map<string, Excerpt> {\n const index = new Map<string, Excerpt>();\n for (const e of excerpts) index.set(e.excerpt_id, e);\n return index;\n}\n","export {\n EXCERPT_ID_PATTERN,\n ExcerptSchema,\n ExcerptOriginSchema,\n type Excerpt,\n type ExcerptOrigin,\n} from './schema.js';\nexport { chunkRawText, chunkKeyPoints, type ExcerptDraft } from './chunk.js';\nexport {\n loadOrBuildLedger,\n ledgerPathFor,\n renderLedgerForPrompt,\n buildExcerptIndex,\n type LoadOrBuildArgs,\n type LoadOrBuildResult,\n} from './ledger.js';\n","export { gather } from './gather.js';\nexport { fetchOnce, makeSourceId, makeReceiptId } from './fetch.js';\nexport {\n parseUrlsFileText,\n readUrlsFile,\n dedupeAndValidate,\n collectUrls,\n} from './url-input.js';\nexport {\n HeuristicExtractor,\n OllamaInternExtractor,\n defaultExtractors,\n pickExtractor,\n} from './extractors/index.js';\nexport { normalizeOllamaHost } from './extractors/ollama-intern.js';\nexport { buildCard, writeSourceCard, appendFetchLog, appendSectionSourceId } from './cards.js';\nexport {\n FetchReceiptSchema,\n SourceCardSchema,\n SourceTypeSchema,\n RelevanceSchema,\n ExtractorNameSchema,\n type FetchReceipt,\n type SourceCard,\n} from './schema.js';\nexport type {\n Extractor,\n ExtractionInput,\n ExtractionResult,\n ExtractorName,\n GatherOptions,\n GatherSummary,\n SourceType,\n Relevance,\n} from './types.js';\nexport {\n EXCERPT_ID_PATTERN,\n ExcerptSchema,\n ExcerptOriginSchema,\n chunkRawText,\n chunkKeyPoints,\n loadOrBuildLedger,\n ledgerPathFor,\n renderLedgerForPrompt,\n buildExcerptIndex,\n type Excerpt,\n type ExcerptOrigin,\n type ExcerptDraft,\n type LoadOrBuildArgs,\n type LoadOrBuildResult,\n} from './excerpts/index.js';\n","import type { Excerpt } from '../../sources/excerpts/schema.js';\nimport type {\n ClaimExtractionInput,\n ClaimExtractionResult,\n ClaimExtractorAdapter,\n DraftClaim,\n} from '../types.js';\n\nfunction normalize(s: string): string {\n return s.replace(/\\s+/g, ' ').toLowerCase().trim();\n}\n\n// For a given key_point, find the ledger excerpt that best matches it.\n// Preference order:\n// 1. Exact substring of key_point inside excerpt\n// 2. Exact substring of excerpt inside key_point\n// 3. First excerpt whose origin is key_point and whose text equals key_point\n// 4. null (no usable excerpt)\nfunction findExcerptForKeyPoint(keyPoint: string, excerpts: Excerpt[]): Excerpt | null {\n const norm = normalize(keyPoint);\n if (norm.length === 0) return null;\n for (const e of excerpts) {\n if (normalize(e.text).includes(norm)) return e;\n }\n for (const e of excerpts) {\n if (norm.includes(normalize(e.text))) return e;\n }\n return null;\n}\n\nexport class HeuristicClaimExtractor implements ClaimExtractorAdapter {\n readonly name = 'heuristic' as const;\n\n async available(): Promise<boolean> {\n return true;\n }\n\n async extract(input: ClaimExtractionInput): Promise<ClaimExtractionResult> {\n const card = input.sourceCard;\n const excerpts = input.excerpts;\n const keyPoints = card.key_points\n .map((kp) => kp.trim())\n .filter((kp) => kp.length > 0);\n\n const drafts: DraftClaim[] = [];\n if (keyPoints.length === 0) {\n // No key_points — fall back to source-card asserts paired with the\n // first available excerpt.\n const first = excerpts[0];\n if (first) {\n drafts.push({\n asserts: card.asserts,\n scope: null,\n not: null,\n evidence_excerpt_ids: [first.excerpt_id],\n evidence_location: first.location_hint,\n confidence: 'low',\n });\n }\n } else {\n let fallbackIdx = 0;\n for (const kp of keyPoints) {\n const matched = findExcerptForKeyPoint(kp, excerpts);\n const chosen = matched ?? excerpts[fallbackIdx % excerpts.length];\n if (!chosen) continue;\n if (!matched) fallbackIdx += 1;\n drafts.push({\n asserts: kp,\n scope: null,\n not: null,\n evidence_excerpt_ids: [chosen.excerpt_id],\n evidence_location: chosen.location_hint,\n confidence: 'low',\n });\n }\n }\n\n return { ok: true, claims: drafts, method: 'heuristic_key_point' };\n }\n}\n","import { renderLedgerForPrompt } from '../../sources/excerpts/ledger.js';\nimport { normalizeOllamaHost } from '../../sources/extractors/ollama-intern.js';\nimport type { Excerpt } from '../../sources/excerpts/schema.js';\nimport type {\n ClaimExtractionInput,\n ClaimExtractionResult,\n ClaimExtractorAdapter,\n Confidence,\n DraftClaim,\n} from '../types.js';\n\nconst DEFAULT_HOST = 'http://localhost:11434';\nconst DEFAULT_MODEL = 'hermes3:8b';\nconst DEFAULT_TIMEOUT_MS = 240_000;\n// Per-window character budget. Keeps the rendered ledger small enough that a\n// 12B-class model can return JSON within DEFAULT_TIMEOUT_MS even on a modest\n// rig. Larger ledgers are paged into multiple windows; claims are merged and\n// deduped after.\nconst DEFAULT_WINDOW_CHARS = 5_000;\n\n// Span-first extraction prompt. The model is shown a deterministic excerpt\n// ledger and asked to choose excerpt IDs — it must NOT author or paraphrase\n// evidence text. research-os copies the literal text from the ledger into the\n// claim's evidence_excerpt field.\nconst SYSTEM_PROMPT = `You are extracting atomic propositional claims from a source for a gated research pack. Return ONE JSON object: {\"claims\": [ ... ]}.\n\nEach claim is an atomic, source-grounded proposition that:\n- Asserts ONE thing\n- Could later be cited, challenged, scoped, contradicted, or promoted into synthesis\n- Is grounded in one or more LITERAL excerpt spans you select from the supplied ledger\n\nA claim is NOT a sentence, a paragraph summary, or a generic topic restatement.\n\nYou will be given a ledger of source spans, each with a stable ID like \"ex_abcdef012345_001\". Pick the IDs that ground each claim. DO NOT author or paraphrase evidence text. The system fills the literal text from the ledger after you respond.\n\nReturn 3 to 7 claims per source. For each claim:\n{\n \"asserts\": \"ONE sentence stating the proposition in your own words\",\n \"scope\": \"ONE sentence naming the contextual scope of the assertion (situation, system, domain). null ONLY if the source's wording is genuinely universal.\",\n \"not\": \"ONE sentence stating what this claim is explicitly NOT about, to prevent overgeneralization. null if no such limit can be inferred.\",\n \"evidence_excerpt_ids\": [\"ex_..._001\", \"ex_..._002\"], // 1 or more IDs FROM THE LEDGER. Required.\n \"evidence_location\": \"short locator like 'paragraph 3' / 'heading: Foo' / null\",\n \"confidence\": \"low\" | \"medium\" | \"high\"\n}\n\nHard rules:\n- Do not fabricate. Every excerpt ID must come from the supplied ledger verbatim.\n- Do not author or paraphrase evidence text — only cite excerpt IDs.\n- Do not widen scope beyond what the chosen spans actually say.\n- Do not synthesize across multiple claims into one — emit them separately.\n- If the source genuinely makes fewer than 3 distinct propositional claims, return whatever it actually makes.`;\n\nexport interface OllamaClaimConfig {\n host?: string;\n model?: string;\n timeoutMs?: number;\n // Per-window ledger character budget. Defaults to DEFAULT_WINDOW_CHARS.\n windowChars?: number;\n fetchImpl?: typeof fetch;\n}\n\ninterface ChatResponse {\n message?: { content?: string };\n response?: string;\n}\n\nfunction asConfidence(v: unknown): Confidence {\n if (v === 'low' || v === 'medium' || v === 'high') return v;\n return 'low';\n}\n\nfunction asStringOrNull(v: unknown): string | null {\n if (typeof v !== 'string') return null;\n const trimmed = v.trim();\n if (trimmed.length === 0) return null;\n if (trimmed.toLowerCase() === 'null') return null;\n return trimmed;\n}\n\nfunction asIdArray(v: unknown): string[] {\n if (!Array.isArray(v)) return [];\n const out: string[] = [];\n for (const x of v) {\n if (typeof x === 'string' && x.trim().length > 0) out.push(x.trim());\n }\n return out;\n}\n\n// Split an excerpt list into windows each under windowChars, never breaking\n// inside an excerpt. Deterministic — same input → same windows.\nexport function pageExcerpts(excerpts: Excerpt[], windowChars: number): Excerpt[][] {\n const windows: Excerpt[][] = [];\n let cursor: Excerpt[] = [];\n let cursorChars = 0;\n for (const ex of excerpts) {\n // Approximate the rendered cost: id + location_hint + ': ' + text + '\\n'\n const approxLine =\n ex.excerpt_id.length +\n (ex.location_hint ? ex.location_hint.length + 3 : 0) +\n 2 +\n ex.text.length +\n 1;\n if (cursor.length > 0 && cursorChars + approxLine > windowChars) {\n windows.push(cursor);\n cursor = [];\n cursorChars = 0;\n }\n cursor.push(ex);\n cursorChars += approxLine;\n }\n if (cursor.length > 0) windows.push(cursor);\n return windows;\n}\n\nexport class OllamaInternClaimExtractor implements ClaimExtractorAdapter {\n readonly name = 'ollama-intern' as const;\n private readonly host: string;\n private readonly model: string;\n private readonly timeoutMs: number;\n private readonly windowChars: number;\n private readonly fetchImpl: typeof fetch;\n\n constructor(config: OllamaClaimConfig = {}) {\n this.host = normalizeOllamaHost(config.host ?? process.env.OLLAMA_HOST ?? DEFAULT_HOST);\n this.model = config.model ?? process.env.OLLAMA_INTERN_MODEL ?? DEFAULT_MODEL;\n this.timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const envWindow = process.env.OLLAMA_INTERN_WINDOW_CHARS;\n this.windowChars =\n config.windowChars ??\n (envWindow ? parseInt(envWindow, 10) || DEFAULT_WINDOW_CHARS : DEFAULT_WINDOW_CHARS);\n this.fetchImpl = config.fetchImpl ?? globalThis.fetch;\n }\n\n async available(): Promise<boolean> {\n try {\n const ctrl = new AbortController();\n const t = setTimeout(() => ctrl.abort(), 1500);\n const res = await this.fetchImpl(`${this.host}/api/tags`, { signal: ctrl.signal });\n clearTimeout(t);\n if (!res.ok) return false;\n const body = (await res.json()) as { models?: Array<{ name: string }> };\n const names = (body.models ?? []).map((m) => m.name);\n const family = this.model.split(':')[0] ?? this.model;\n return names.some((n) => n === this.model || n === family || n.startsWith(`${family}:`));\n } catch {\n return false;\n }\n }\n\n // One LLM call against a single ledger window. Returns drafts or an error.\n // Errors here become page-level failures; the orchestrating extract() method\n // tolerates page failures and merges drafts from successful pages.\n private async extractOnePage(\n cardSummary: string,\n ledgerText: string,\n ): Promise<{ ok: true; drafts: DraftClaim[] } | { ok: false; error: string }> {\n const userMsg = `${cardSummary}\n\nEXCERPT LEDGER BEGIN\n${ledgerText}\nEXCERPT LEDGER END`;\n\n const ctrl = new AbortController();\n const t = setTimeout(() => ctrl.abort(), this.timeoutMs);\n let body: ChatResponse;\n try {\n const res = await this.fetchImpl(`${this.host}/api/chat`, {\n method: 'POST',\n signal: ctrl.signal,\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n model: this.model,\n stream: false,\n format: 'json',\n // Override Ollama's default 4096 context — the rendered ledger\n // window is sized in chars, but the prompt + system message can\n // easily exceed 4K tokens for hermes3:8b without this option,\n // and the silent server-side truncation eats excerpt IDs.\n options: { num_ctx: 8192 },\n messages: [\n { role: 'system', content: SYSTEM_PROMPT },\n { role: 'user', content: userMsg },\n ],\n }),\n });\n if (!res.ok) return { ok: false, error: `Ollama HTTP ${res.status}` };\n body = (await res.json()) as ChatResponse;\n } catch (err) {\n return { ok: false, error: err instanceof Error ? err.message : 'Ollama request failed' };\n } finally {\n clearTimeout(t);\n }\n\n const text = body.message?.content ?? body.response ?? '';\n let parsed: { claims?: unknown };\n try {\n parsed = JSON.parse(text) as { claims?: unknown };\n } catch {\n return { ok: false, error: 'Ollama response was not valid JSON' };\n }\n\n if (!Array.isArray(parsed.claims)) {\n return { ok: false, error: 'Ollama response did not contain a claims array' };\n }\n\n const drafts: DraftClaim[] = [];\n for (const raw of parsed.claims) {\n if (!raw || typeof raw !== 'object') continue;\n const r = raw as Record<string, unknown>;\n const asserts = asStringOrNull(r.asserts);\n const ids = asIdArray(r.evidence_excerpt_ids);\n if (!asserts || ids.length === 0) continue;\n drafts.push({\n asserts,\n scope: asStringOrNull(r.scope),\n not: asStringOrNull(r.not),\n evidence_excerpt_ids: ids,\n evidence_location: asStringOrNull(r.evidence_location),\n confidence: asConfidence(r.confidence),\n });\n }\n return { ok: true, drafts };\n }\n\n async extract(input: ClaimExtractionInput): Promise<ClaimExtractionResult> {\n if (input.excerpts.length === 0) {\n return { ok: false, error: 'No excerpts available; ledger is empty for this source' };\n }\n\n const card = input.sourceCard;\n const cardSummary = `URL: ${card.url}\nSource title: ${card.title}\nPublisher: ${card.publisher ?? 'unknown'}\nSource-card asserts: ${card.asserts}\nSource-card scope: ${card.scope ?? 'null'}\nSource-card not: ${card.not ?? 'null'}`;\n\n const windows = pageExcerpts(input.excerpts, this.windowChars);\n const allDrafts: DraftClaim[] = [];\n const pageErrors: string[] = [];\n let pagesOk = 0;\n for (const window of windows) {\n const ledgerText = renderLedgerForPrompt(window);\n const page = await this.extractOnePage(cardSummary, ledgerText);\n if (!page.ok) {\n pageErrors.push(page.error);\n continue;\n }\n pagesOk += 1;\n allDrafts.push(...page.drafts);\n }\n\n // If every page failed, surface the most common error so the caller sees\n // the right diagnostic (HTTP 500 vs JSON parse vs timeout).\n if (pagesOk === 0) {\n const summary =\n pageErrors.length === 1\n ? pageErrors[0]!\n : `all ${windows.length} ledger pages failed (first error: ${pageErrors[0] ?? 'unknown'})`;\n return { ok: false, error: summary };\n }\n\n // Dedup by normalised asserts — when the same theme appears in adjacent\n // windows the model often emits parallel claims.\n const seen = new Set<string>();\n const drafts: DraftClaim[] = [];\n for (const d of allDrafts) {\n const key = d.asserts.toLowerCase().replace(/\\s+/g, ' ').trim();\n if (seen.has(key)) continue;\n seen.add(key);\n drafts.push(d);\n }\n\n if (drafts.length === 0) {\n return { ok: false, error: 'Ollama returned no usable claims (all missing evidence_excerpt_ids)' };\n }\n\n const method =\n windows.length > 1 ? 'ollama_intern_propositional_paged' : 'ollama_intern_propositional';\n return { ok: true, claims: drafts, method };\n }\n}\n","import type { ClaimExtractorAdapter } from '../types.js';\nimport { HeuristicClaimExtractor } from './heuristic.js';\nimport { OllamaInternClaimExtractor } from './ollama-intern.js';\n\nexport { HeuristicClaimExtractor } from './heuristic.js';\nexport { OllamaInternClaimExtractor } from './ollama-intern.js';\n\nexport function defaultClaimExtractors(): ClaimExtractorAdapter[] {\n return [new OllamaInternClaimExtractor(), new HeuristicClaimExtractor()];\n}\n\nexport async function pickClaimExtractor(\n extractors: ClaimExtractorAdapter[],\n): Promise<ClaimExtractorAdapter> {\n for (const e of extractors) {\n if (await e.available()) return e;\n }\n throw new Error(\n 'No claim extractor available. The HeuristicClaimExtractor should always be available — this indicates a bug.',\n );\n}\n","import { z } from 'zod';\n\nimport { EXCERPT_ID_PATTERN } from '../sources/excerpts/schema.js';\n\nexport const ConfidenceSchema = z.enum(['low', 'medium', 'high']);\n\nexport const ClaimExtractorSchema = z.enum(['heuristic', 'ollama-intern']);\n\nexport const ReviewStateSchema = z.enum([\n 'candidate',\n 'gated',\n 'reviewed',\n 'rejected',\n 'accepted',\n]);\n\nexport const ClaimSchema = z.object({\n claim_id: z.string().regex(/^clm_[a-f0-9]{12}_(heuristic|ollama_intern)_\\d+$/),\n section_id: z.string().regex(/^[0-9]{2}-[a-z0-9-]+$/),\n source_ids: z\n .array(z.string().regex(/^src_[a-f0-9]{12}$/))\n .min(1, 'every claim must reference at least one source_id'),\n source_hashes: z.array(z.string().regex(/^[a-f0-9]{64}$/)),\n asserts: z.string().min(1),\n scope: z.string().nullable(),\n not: z.string().nullable(),\n // Span-first extraction: the model picks excerpt IDs from the deterministic\n // ledger; research-os copies the literal text into evidence_excerpt. Models\n // may interpret source spans; they may not author evidence spans.\n // Allowed empty for legacy claims that pre-date span-first extraction —\n // those should be re-extracted; new writes always populate at least one ID.\n evidence_excerpt_ids: z.array(z.string().regex(EXCERPT_ID_PATTERN)).default([]),\n evidence_excerpt: z.string().min(1),\n evidence_location: z.string().nullable(),\n confidence: ConfidenceSchema,\n extractor: ClaimExtractorSchema,\n extraction_method: z.string().min(1),\n created_at: z.string(),\n review_state: ReviewStateSchema,\n});\n\nexport type Claim = z.infer<typeof ClaimSchema>;\n","import { existsSync } from 'node:fs';\nimport { appendFile, mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { join, resolve } from 'node:path';\n\nimport {\n NoSourcesGatheredError,\n PackNotFoundError,\n SectionNotFoundError,\n} from '../errors.js';\nimport { RESEARCH_OS_VERSION } from '../index.js';\nimport {\n buildExcerptIndex,\n EXCERPT_ID_PATTERN,\n loadOrBuildLedger,\n type Excerpt,\n} from '../sources/excerpts/index.js';\nimport {\n FetchReceiptSchema,\n SourceCardSchema,\n type FetchReceipt,\n type SourceCard,\n} from '../sources/schema.js';\nimport { defaultClaimExtractors, pickClaimExtractor } from './extractors/index.js';\nimport { ClaimSchema, type Claim } from './schema.js';\nimport type {\n ClaimExtractor,\n DraftClaim,\n ExtractClaimsOptions,\n ExtractClaimsSummary,\n} from './types.js';\n\nconst MIN_EXCERPT_LEN_FOR_GROUNDING = 8;\nconst EVIDENCE_EXCERPT_JOIN = ' … ';\nconst EVIDENCE_EXCERPT_MAX_CHARS = 1200;\n\nfunction normalize(text: string): string {\n return text.replace(/<[^>]+>/g, ' ').replace(/\\s+/g, ' ').toLowerCase().trim();\n}\n\n// Legacy text-substring grounding check, retained for callers that still need it\n// (e.g. reviewer post-checks). Span-first extraction does NOT use this — claims\n// are grounded by excerpt-id resolution against the ledger instead.\nexport function evidenceGrounded(excerpt: string, rawText: string | null): boolean {\n if (!rawText) return false;\n const e = normalize(excerpt);\n if (e.length < MIN_EXCERPT_LEN_FOR_GROUNDING) return false;\n return normalize(rawText).includes(e);\n}\n\nconst EXTRACTOR_ID_PART: Record<ClaimExtractor, string> = {\n heuristic: 'heuristic',\n 'ollama-intern': 'ollama_intern',\n};\n\ninterface SectionSourceEntry {\n source_id: string;\n}\n\nasync function readSectionSourceIds(\n packPath: string,\n sectionId: string,\n): Promise<string[]> {\n const path = join(packPath, 'sections', sectionId, 'sources.jsonl');\n if (!existsSync(path)) return [];\n const text = await readFile(path, 'utf8');\n const ids: string[] = [];\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n const entry = JSON.parse(line) as SectionSourceEntry;\n if (typeof entry.source_id === 'string') ids.push(entry.source_id);\n } catch {\n /* skip malformed line */\n }\n }\n return ids;\n}\n\nasync function readSourceCard(packPath: string, sourceId: string): Promise<SourceCard | null> {\n const path = join(packPath, 'evidence', 'source-cards', `${sourceId}.json`);\n if (!existsSync(path)) return null;\n const text = await readFile(path, 'utf8');\n return SourceCardSchema.parse(JSON.parse(text));\n}\n\nasync function findLatestReceipt(\n packPath: string,\n sourceId: string,\n): Promise<FetchReceipt | null> {\n const path = join(packPath, 'evidence', 'fetch-log.jsonl');\n if (!existsSync(path)) return null;\n const text = await readFile(path, 'utf8');\n let latest: FetchReceipt | null = null;\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n const r = FetchReceiptSchema.parse(JSON.parse(line));\n if (r.source_id !== sourceId) continue;\n if (r.fetch_outcome !== 'ok') continue;\n if (!latest || r.fetched_at > latest.fetched_at) latest = r;\n } catch {\n /* skip malformed */\n }\n }\n return latest;\n}\n\nasync function readExistingClaimIds(\n packPath: string,\n sectionId: string,\n): Promise<Set<string>> {\n const path = join(packPath, 'sections', sectionId, 'claims.jsonl');\n if (!existsSync(path)) return new Set();\n const text = await readFile(path, 'utf8');\n const set = new Set<string>();\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n const obj = JSON.parse(line) as { claim_id?: string };\n if (typeof obj.claim_id === 'string') set.add(obj.claim_id);\n } catch {\n /* skip */\n }\n }\n return set;\n}\n\ninterface ResolveResult {\n ok: boolean;\n evidenceText: string;\n resolvedIds: string[];\n failureMode: 'excerpt_id_missing' | 'excerpt_id_malformed' | null;\n}\n\nfunction resolveExcerpts(\n rawIds: string[],\n index: Map<string, Excerpt>,\n): ResolveResult {\n if (!Array.isArray(rawIds) || rawIds.length === 0) {\n return { ok: false, evidenceText: '', resolvedIds: [], failureMode: 'excerpt_id_missing' };\n }\n const resolvedIds: string[] = [];\n const texts: string[] = [];\n for (const idRaw of rawIds) {\n const id = String(idRaw).trim();\n if (!EXCERPT_ID_PATTERN.test(id)) {\n return { ok: false, evidenceText: '', resolvedIds: [], failureMode: 'excerpt_id_malformed' };\n }\n const ex = index.get(id);\n if (!ex) {\n return { ok: false, evidenceText: '', resolvedIds: [], failureMode: 'excerpt_id_missing' };\n }\n if (!resolvedIds.includes(id)) {\n resolvedIds.push(id);\n texts.push(ex.text);\n }\n }\n let combined = texts.join(EVIDENCE_EXCERPT_JOIN);\n if (combined.length > EVIDENCE_EXCERPT_MAX_CHARS) {\n combined = combined.slice(0, EVIDENCE_EXCERPT_MAX_CHARS - 2).trimEnd() + ' …';\n }\n if (combined.length === 0) {\n return { ok: false, evidenceText: '', resolvedIds: [], failureMode: 'excerpt_id_missing' };\n }\n return { ok: true, evidenceText: combined, resolvedIds, failureMode: null };\n}\n\nfunction buildClaim(args: {\n draft: DraftClaim;\n evidenceText: string;\n resolvedExcerptIds: string[];\n index: number;\n sectionId: string;\n sourceId: string;\n sourceHash: string | null;\n extractor: ClaimExtractor;\n extractionMethod: string;\n}): Claim {\n const {\n draft,\n evidenceText,\n resolvedExcerptIds,\n index,\n sectionId,\n sourceId,\n sourceHash,\n extractor,\n extractionMethod,\n } = args;\n const idPart = EXTRACTOR_ID_PART[extractor];\n const claimId = `clm_${sourceId.replace(/^src_/, '')}_${idPart}_${index + 1}`;\n return ClaimSchema.parse({\n claim_id: claimId,\n section_id: sectionId,\n source_ids: [sourceId],\n source_hashes: sourceHash ? [sourceHash] : [],\n asserts: draft.asserts,\n scope: draft.scope,\n not: draft.not,\n evidence_excerpt_ids: resolvedExcerptIds,\n evidence_excerpt: evidenceText,\n evidence_location: draft.evidence_location,\n confidence: draft.confidence,\n extractor,\n extraction_method: extractionMethod,\n created_at: new Date().toISOString(),\n review_state: 'candidate',\n });\n}\n\nexport async function extract(options: ExtractClaimsOptions): Promise<ExtractClaimsSummary> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n if (!existsSync(join(packPath, 'research.yaml'))) throw new PackNotFoundError(packPath);\n if (!existsSync(join(packPath, 'sections', options.sectionId)))\n throw new SectionNotFoundError(options.sectionId);\n\n const sourceIds = await readSectionSourceIds(packPath, options.sectionId);\n if (sourceIds.length === 0) throw new NoSourcesGatheredError(options.sectionId);\n\n const adapters = options.extractors ?? defaultClaimExtractors();\n const extractor = await pickClaimExtractor(adapters);\n\n const claimsPath = join(packPath, 'sections', options.sectionId, 'claims.jsonl');\n const existingIds = await readExistingClaimIds(packPath, options.sectionId);\n\n const summary: ExtractClaimsSummary = {\n sectionId: options.sectionId,\n extractor: extractor.name,\n extractionMethod: '',\n sourcesProcessed: 0,\n sourcesSkipped: 0,\n sourcesFailed: 0,\n excerptLedgersBuilt: 0,\n claimsAdded: 0,\n claimsDeduped: 0,\n claimsRejectedUngrounded: 0,\n claimsRejectedExcerptIdMissing: 0,\n claimsRejectedExcerptIdMalformed: 0,\n claimsRejectedScopeMissing: 0,\n claimsRejectedExtractorParaphrase: 0,\n claimIds: [],\n failures: [],\n };\n\n for (const sourceId of sourceIds) {\n const card = await readSourceCard(packPath, sourceId);\n if (!card) {\n summary.sourcesSkipped += 1;\n continue;\n }\n const receipt = await findLatestReceipt(packPath, sourceId);\n let rawText: string | null = null;\n if (receipt?.raw_text_path) {\n const raw = join(packPath, receipt.raw_text_path);\n if (existsSync(raw)) {\n rawText = await readFile(raw, 'utf8');\n }\n }\n\n const ledger = await loadOrBuildLedger({\n packPath,\n sourceCard: card,\n sourceHash: receipt?.sha256 ?? null,\n rawText,\n });\n if (ledger.built) summary.excerptLedgersBuilt += 1;\n\n if (ledger.excerpts.length === 0) {\n // No spans available — extractor cannot produce span-first claims.\n summary.sourcesSkipped += 1;\n continue;\n }\n\n const result = await extractor.extract({\n sourceCard: card,\n sourceHash: receipt?.sha256 ?? null,\n excerpts: ledger.excerpts,\n });\n\n if (!result.ok) {\n summary.sourcesFailed += 1;\n summary.failures.push({ source_id: sourceId, reason: result.error });\n continue;\n }\n\n summary.sourcesProcessed += 1;\n summary.extractionMethod = result.method;\n\n const excerptIndex = buildExcerptIndex(ledger.excerpts);\n\n let writtenIndex = 0;\n for (let i = 0; i < result.claims.length; i += 1) {\n const draft = result.claims[i]!;\n const resolved = resolveExcerpts(draft.evidence_excerpt_ids, excerptIndex);\n if (!resolved.ok) {\n summary.claimsRejectedUngrounded += 1;\n if (resolved.failureMode === 'excerpt_id_missing') {\n summary.claimsRejectedExcerptIdMissing += 1;\n } else if (resolved.failureMode === 'excerpt_id_malformed') {\n summary.claimsRejectedExcerptIdMalformed += 1;\n }\n continue;\n }\n const claim = buildClaim({\n draft,\n evidenceText: resolved.evidenceText,\n resolvedExcerptIds: resolved.resolvedIds,\n index: writtenIndex,\n sectionId: options.sectionId,\n sourceId,\n sourceHash: receipt?.sha256 ?? null,\n extractor: extractor.name,\n extractionMethod: result.method,\n });\n writtenIndex += 1;\n if (existingIds.has(claim.claim_id)) {\n summary.claimsDeduped += 1;\n continue;\n }\n await appendFile(claimsPath, JSON.stringify(claim) + '\\n', 'utf8');\n existingIds.add(claim.claim_id);\n summary.claimsAdded += 1;\n summary.claimIds.push(claim.claim_id);\n }\n }\n\n // Persist a small extraction receipt next to the section's other audit\n // outputs. The section report reads this for the Extraction panel.\n const receipt = {\n receipt_id: `cle_${Date.now()}_${options.sectionId}`,\n section_id: options.sectionId,\n extracted_at: new Date().toISOString(),\n research_os_version: RESEARCH_OS_VERSION,\n extractor: summary.extractor,\n extraction_method: summary.extractionMethod,\n sources_processed: summary.sourcesProcessed,\n sources_skipped: summary.sourcesSkipped,\n sources_failed: summary.sourcesFailed,\n excerpt_ledgers_built: summary.excerptLedgersBuilt,\n claims_added: summary.claimsAdded,\n claims_deduped: summary.claimsDeduped,\n claims_rejected_ungrounded: summary.claimsRejectedUngrounded,\n claims_rejected_excerpt_id_missing: summary.claimsRejectedExcerptIdMissing,\n claims_rejected_excerpt_id_malformed: summary.claimsRejectedExcerptIdMalformed,\n failures: summary.failures.map((f) => ({\n source_id: f.source_id,\n reason: f.reason,\n // Tag transport / parse failures so the report can bucket them.\n kind: /not valid JSON/i.test(f.reason)\n ? 'extractor_invalid_json'\n : /aborted|timeout/i.test(f.reason)\n ? 'extractor_timeout'\n : /HTTP \\d{3}/i.test(f.reason)\n ? 'extractor_http_error'\n : 'extractor_other',\n })),\n };\n const auditsDir = join(packPath, 'audits');\n await mkdir(auditsDir, { recursive: true });\n await writeFile(\n join(auditsDir, `${options.sectionId}-claim-extract.json`),\n JSON.stringify(receipt, null, 2),\n 'utf8',\n );\n\n return summary;\n}\n","import { z } from 'zod';\n\n// A claim density audit reports how dense and redundant a section's\n// candidate claim ledger is, BEFORE review runs. It surfaces signals the\n// reviewer can route into claim_overproduction findings (or that a human\n// can use to decide whether to consolidate the ledger by hand).\n//\n// Span-first + paged extraction can yield individually-grounded but\n// collectively-noisy claim sets. This audit measures that without\n// touching the canonical artifacts.\n\nexport const PerSourceDensitySchema = z.object({\n source_id: z.string().regex(/^src_[a-f0-9]{12}$/),\n publisher: z.string().nullable(),\n source_word_count: z.number().int().nonnegative(),\n claim_count: z.number().int().nonnegative(),\n claims_per_1k_words: z.number(),\n share_of_section: z.number(), // 0..1\n weak_scope_count: z.number().int().nonnegative(),\n generic_scope_count: z.number().int().nonnegative(),\n});\n\nexport const NearDuplicateClusterSchema = z.object({\n representative_assert: z.string(),\n member_count: z.number().int().nonnegative(),\n claim_ids: z.array(z.string().regex(/^clm_[a-f0-9]{12}_(heuristic|ollama_intern)_\\d+$/)),\n});\n\nexport const DensityFlagSchema = z.object({\n type: z.enum([\n 'source_dominance',\n 'high_per_word_density',\n 'large_near_duplicate_cluster',\n 'weak_scope_majority',\n ]),\n severity: z.enum(['info', 'warn', 'block']),\n message: z.string(),\n affects_source_ids: z.array(z.string().regex(/^src_[a-f0-9]{12}$/)).default([]),\n affects_claim_ids: z\n .array(z.string().regex(/^clm_[a-f0-9]{12}_(heuristic|ollama_intern)_\\d+$/))\n .default([]),\n});\n\nexport const ClaimDensityAuditSchema = z.object({\n audit_id: z.string().regex(/^cda_[0-9]+_[a-z0-9-]+$/),\n section_id: z.string().regex(/^[0-9]{2}-[a-z0-9-]+$/),\n audited_at: z.string(),\n research_os_version: z.string(),\n candidate_claim_count: z.number().int().nonnegative(),\n source_count: z.number().int().nonnegative(),\n total_source_word_count: z.number().int().nonnegative(),\n claims_per_1k_words: z.number(),\n weak_scope_count: z.number().int().nonnegative(),\n generic_scope_count: z.number().int().nonnegative(),\n per_source: z.array(PerSourceDensitySchema),\n near_duplicate_clusters: z.array(NearDuplicateClusterSchema),\n flags: z.array(DensityFlagSchema),\n});\n\nexport type PerSourceDensity = z.infer<typeof PerSourceDensitySchema>;\nexport type NearDuplicateCluster = z.infer<typeof NearDuplicateClusterSchema>;\nexport type DensityFlag = z.infer<typeof DensityFlagSchema>;\nexport type ClaimDensityAudit = z.infer<typeof ClaimDensityAuditSchema>;\n","import { existsSync } from 'node:fs';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { join, resolve } from 'node:path';\n\nimport { PackNotFoundError, SectionNotFoundError } from '../../errors.js';\nimport { RESEARCH_OS_VERSION } from '../../index.js';\nimport {\n FetchReceiptSchema,\n SourceCardSchema,\n type FetchReceipt,\n type SourceCard,\n} from '../../sources/schema.js';\nimport { ClaimSchema, type Claim } from '../schema.js';\nimport {\n ClaimDensityAuditSchema,\n type ClaimDensityAudit,\n type DensityFlag,\n type NearDuplicateCluster,\n type PerSourceDensity,\n} from './schema.js';\n\nexport interface AuditDensityOptions {\n sectionId: string;\n packPath?: string;\n now?: () => Date;\n}\n\nexport interface AuditDensityResult {\n audit: ClaimDensityAudit;\n jsonPath: string;\n markdownPath: string;\n}\n\nconst NEAR_DUP_CLUSTER_MIN = 3;\nconst SOURCE_DOMINANCE_RATIO = 0.4;\nconst SOURCE_DOMINANCE_MIN_TOTAL = 10;\nconst SOURCE_DOMINANCE_MIN_PER_SOURCE = 8;\nconst HIGH_DENSITY_PER_1K = 5;\nconst WEAK_SCOPE_MAJORITY_RATIO = 0.5;\n\nfunction normalize(s: string): string {\n return s\n .replace(/<[^>]+>/g, ' ')\n .replace(/\\s+/g, ' ')\n .toLowerCase()\n .replace(/[^a-z0-9 ]+/g, ' ')\n .replace(/\\s+/g, ' ')\n .trim();\n}\n\nfunction countWords(text: string): number {\n if (!text) return 0;\n return normalize(text).split(' ').filter((w) => w.length > 0).length;\n}\n\nasync function readClaims(packPath: string, sectionId: string): Promise<Claim[]> {\n const path = join(packPath, 'sections', sectionId, 'claims.jsonl');\n if (!existsSync(path)) return [];\n const text = await readFile(path, 'utf8');\n const out: Claim[] = [];\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n out.push(ClaimSchema.parse(JSON.parse(line)));\n } catch {\n /* skip malformed line */\n }\n }\n return out;\n}\n\nasync function readSourceCards(\n packPath: string,\n sourceIds: string[],\n): Promise<Map<string, SourceCard>> {\n const out = new Map<string, SourceCard>();\n for (const sid of sourceIds) {\n const p = join(packPath, 'evidence', 'source-cards', `${sid}.json`);\n if (!existsSync(p)) continue;\n try {\n out.set(sid, SourceCardSchema.parse(JSON.parse(await readFile(p, 'utf8'))));\n } catch {\n /* skip malformed */\n }\n }\n return out;\n}\n\nasync function readLatestReceipts(packPath: string): Promise<Map<string, FetchReceipt>> {\n const out = new Map<string, FetchReceipt>();\n const path = join(packPath, 'evidence', 'fetch-log.jsonl');\n if (!existsSync(path)) return out;\n const text = await readFile(path, 'utf8');\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n const r = FetchReceiptSchema.parse(JSON.parse(line));\n if (r.fetch_outcome !== 'ok') continue;\n const prev = out.get(r.source_id);\n if (!prev || prev.fetched_at < r.fetched_at) out.set(r.source_id, r);\n } catch {\n /* skip */\n }\n }\n return out;\n}\n\nasync function readRawText(packPath: string, receipt: FetchReceipt): Promise<string | null> {\n if (!receipt.raw_text_path) return null;\n const p = join(packPath, receipt.raw_text_path);\n if (!existsSync(p)) return null;\n return await readFile(p, 'utf8');\n}\n\n// A claim's scope is \"weak\" when scope is null AND not is null AND asserts > 40 chars.\nfunction isWeakScope(claim: Claim): boolean {\n return claim.scope === null && claim.not === null && claim.asserts.length > 40;\n}\n\n// A claim's scope is \"generic source\" when scope is non-null but quotes the\n// source title or topic without adding situational context. Heuristic: scope\n// length is short AND a substantial fraction of the scope tokens appear in the\n// source-card title (case-insensitive).\nfunction isGenericScope(claim: Claim, sourceTitle: string | null): boolean {\n if (!claim.scope || !sourceTitle) return false;\n if (claim.scope.length > 80) return false;\n const titleTokens = new Set(normalize(sourceTitle).split(' ').filter((t) => t.length > 3));\n const scopeTokens = normalize(claim.scope).split(' ').filter((t) => t.length > 3);\n if (scopeTokens.length === 0) return false;\n const overlap = scopeTokens.filter((t) => titleTokens.has(t)).length;\n return overlap / scopeTokens.length >= 0.5;\n}\n\nfunction buildClusters(claims: Claim[]): NearDuplicateCluster[] {\n const buckets = new Map<string, Claim[]>();\n for (const c of claims) {\n const key = normalize(c.asserts);\n if (key.length === 0) continue;\n const arr = buckets.get(key) ?? [];\n arr.push(c);\n buckets.set(key, arr);\n }\n const clusters: NearDuplicateCluster[] = [];\n for (const [, members] of buckets) {\n if (members.length >= NEAR_DUP_CLUSTER_MIN) {\n clusters.push({\n representative_assert: members[0]!.asserts.slice(0, 240),\n member_count: members.length,\n claim_ids: members.map((m) => m.claim_id),\n });\n }\n }\n // Sort largest cluster first.\n clusters.sort((a, b) => b.member_count - a.member_count);\n return clusters;\n}\n\nfunction buildFlags(audit: Omit<ClaimDensityAudit, 'flags'>): DensityFlag[] {\n const flags: DensityFlag[] = [];\n // source_dominance\n for (const s of audit.per_source) {\n if (\n s.claim_count >= 30 ||\n (audit.candidate_claim_count >= SOURCE_DOMINANCE_MIN_TOTAL &&\n s.claim_count >= SOURCE_DOMINANCE_MIN_PER_SOURCE &&\n s.share_of_section >= SOURCE_DOMINANCE_RATIO)\n ) {\n const severity = s.claim_count >= 50 || s.share_of_section >= 0.6 ? 'block' : 'warn';\n flags.push({\n type: 'source_dominance',\n severity,\n message: `Source ${s.source_id} contributes ${s.claim_count} of ${audit.candidate_claim_count} claims (${(s.share_of_section * 100).toFixed(0)}% of section).`,\n affects_source_ids: [s.source_id],\n affects_claim_ids: [],\n });\n }\n }\n // high_per_word_density (per-source)\n for (const s of audit.per_source) {\n if (s.source_word_count > 0 && s.claims_per_1k_words >= HIGH_DENSITY_PER_1K) {\n flags.push({\n type: 'high_per_word_density',\n severity: 'warn',\n message: `Source ${s.source_id} has ${s.claims_per_1k_words.toFixed(1)} claims per 1k source words — likely over-atomization.`,\n affects_source_ids: [s.source_id],\n affects_claim_ids: [],\n });\n }\n }\n // weak_scope_majority\n if (\n audit.candidate_claim_count > 0 &&\n audit.weak_scope_count / audit.candidate_claim_count >= WEAK_SCOPE_MAJORITY_RATIO\n ) {\n flags.push({\n type: 'weak_scope_majority',\n severity: 'warn',\n message: `${audit.weak_scope_count} of ${audit.candidate_claim_count} claims (${((audit.weak_scope_count / audit.candidate_claim_count) * 100).toFixed(0)}%) carry no scope and no not constraint.`,\n affects_source_ids: [],\n affects_claim_ids: [],\n });\n }\n return flags;\n}\n\nfunction buildMarkdown(audit: ClaimDensityAudit): string {\n const lines: string[] = [];\n lines.push(`# Claim density audit: ${audit.section_id}`);\n lines.push('');\n lines.push(`- **Audit ID:** \\`${audit.audit_id}\\``);\n lines.push(`- **Audited at:** ${audit.audited_at}`);\n lines.push(`- **research-os version:** ${audit.research_os_version}`);\n lines.push(`- **Candidate claims:** ${audit.candidate_claim_count}`);\n lines.push(`- **Sources:** ${audit.source_count}`);\n lines.push(`- **Total source words:** ${audit.total_source_word_count.toLocaleString()}`);\n lines.push(`- **Claims per 1k source words (section):** ${audit.claims_per_1k_words.toFixed(2)}`);\n lines.push(`- **Weak-scope claims (scope=null, not=null, substantive asserts):** ${audit.weak_scope_count}`);\n lines.push(`- **Generic-scope claims (scope mirrors source title):** ${audit.generic_scope_count}`);\n lines.push('');\n\n lines.push(`## Flags (${audit.flags.length})`);\n lines.push('');\n if (audit.flags.length === 0) {\n lines.push('_No density flags raised. Section claim ledger looks proportionate._');\n } else {\n lines.push('| Type | Severity | Message |');\n lines.push('|---|---|---|');\n for (const f of audit.flags) {\n lines.push(`| \\`${f.type}\\` | ${f.severity} | ${f.message.replace(/\\|/g, '\\\\|')} |`);\n }\n }\n lines.push('');\n\n lines.push(`## Per source (${audit.per_source.length})`);\n lines.push('');\n if (audit.per_source.length === 0) {\n lines.push('_No sources contributed claims._');\n } else {\n lines.push('| Source | Words | Claims | Per 1k words | Share | Weak scope | Generic scope |');\n lines.push('|---|---:|---:|---:|---:|---:|---:|');\n for (const s of audit.per_source) {\n lines.push(\n `| \\`${s.source_id}\\`${s.publisher ? ` (${s.publisher})` : ''} | ${s.source_word_count.toLocaleString()} | ${s.claim_count} | ${s.claims_per_1k_words.toFixed(2)} | ${(s.share_of_section * 100).toFixed(0)}% | ${s.weak_scope_count} | ${s.generic_scope_count} |`,\n );\n }\n }\n lines.push('');\n\n lines.push(`## Near-duplicate clusters (>= ${NEAR_DUP_CLUSTER_MIN} members) — ${audit.near_duplicate_clusters.length}`);\n lines.push('');\n if (audit.near_duplicate_clusters.length === 0) {\n lines.push('_No near-duplicate clusters detected._');\n } else {\n lines.push('Each row is a cluster of claims whose normalised assertions collapse to the same key.');\n lines.push('');\n lines.push('| Members | Representative assertion |');\n lines.push('|---:|---|');\n for (const c of audit.near_duplicate_clusters) {\n lines.push(`| ${c.member_count} | ${c.representative_assert.replace(/\\|/g, '\\\\|')} |`);\n }\n }\n lines.push('');\n lines.push('---');\n lines.push('');\n lines.push('_This audit is read-only. The reviewer (Link 7) decides which claims are accepted, rejected, or flagged for collapse via `claim_overproduction` findings._');\n return lines.join('\\n');\n}\n\nexport async function auditDensity(\n options: AuditDensityOptions,\n): Promise<AuditDensityResult> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n if (!existsSync(join(packPath, 'research.yaml'))) throw new PackNotFoundError(packPath);\n if (!existsSync(join(packPath, 'sections', options.sectionId)))\n throw new SectionNotFoundError(options.sectionId);\n\n const claims = await readClaims(packPath, options.sectionId);\n const allSourceIds = Array.from(\n new Set(claims.flatMap((c) => c.source_ids)),\n ).sort();\n const cards = await readSourceCards(packPath, allSourceIds);\n const receipts = await readLatestReceipts(packPath);\n\n // Source word counts via raw text (preferred) or fallback to source-card asserts.\n const wordsBySource = new Map<string, number>();\n for (const sid of allSourceIds) {\n let words = 0;\n const r = receipts.get(sid);\n if (r) {\n const raw = await readRawText(packPath, r);\n if (raw) words = countWords(raw);\n }\n if (words === 0) {\n const card = cards.get(sid);\n if (card) words = countWords(card.asserts);\n }\n wordsBySource.set(sid, words);\n }\n\n // Per-source aggregations.\n const perSource: PerSourceDensity[] = [];\n let totalWords = 0;\n let weakTotal = 0;\n let genericTotal = 0;\n for (const sid of allSourceIds) {\n const claimsHere = claims.filter((c) => c.source_ids.includes(sid));\n const words = wordsBySource.get(sid) ?? 0;\n totalWords += words;\n const card = cards.get(sid) ?? null;\n const weak = claimsHere.filter(isWeakScope).length;\n const generic = claimsHere.filter((c) => isGenericScope(c, card?.title ?? null)).length;\n weakTotal += weak;\n genericTotal += generic;\n perSource.push({\n source_id: sid,\n publisher: card?.publisher ?? null,\n source_word_count: words,\n claim_count: claimsHere.length,\n claims_per_1k_words: words > 0 ? (claimsHere.length / words) * 1000 : 0,\n share_of_section: claims.length > 0 ? claimsHere.length / claims.length : 0,\n weak_scope_count: weak,\n generic_scope_count: generic,\n });\n }\n perSource.sort((a, b) => b.claim_count - a.claim_count);\n\n const clusters = buildClusters(claims);\n\n const stamp = (options.now ?? (() => new Date()))();\n const auditId = `cda_${stamp.getTime()}_${options.sectionId}`;\n\n const partial: Omit<ClaimDensityAudit, 'flags'> = {\n audit_id: auditId,\n section_id: options.sectionId,\n audited_at: stamp.toISOString(),\n research_os_version: RESEARCH_OS_VERSION,\n candidate_claim_count: claims.length,\n source_count: allSourceIds.length,\n total_source_word_count: totalWords,\n claims_per_1k_words: totalWords > 0 ? (claims.length / totalWords) * 1000 : 0,\n weak_scope_count: weakTotal,\n generic_scope_count: genericTotal,\n per_source: perSource,\n near_duplicate_clusters: clusters,\n };\n // Also flag clusters of >= NEAR_DUP_CLUSTER_MIN as a section-level signal.\n const clusterFlags: DensityFlag[] = clusters.map((c) => ({\n type: 'large_near_duplicate_cluster',\n severity: c.member_count >= 6 ? 'block' : 'warn',\n message: `Cluster of ${c.member_count} claims share a normalised assertion: \"${c.representative_assert.slice(0, 120)}\".`,\n affects_source_ids: [],\n affects_claim_ids: c.claim_ids,\n }));\n const flags = [...buildFlags(partial), ...clusterFlags];\n const audit: ClaimDensityAudit = ClaimDensityAuditSchema.parse({ ...partial, flags });\n\n // Write audits/<section>-claim-density.{json,md}.\n const auditsDir = join(packPath, 'audits');\n await mkdir(auditsDir, { recursive: true });\n const jsonPath = join(auditsDir, `${options.sectionId}-claim-density.json`);\n const markdownPath = join(auditsDir, `${options.sectionId}-claim-density.md`);\n await writeFile(jsonPath, JSON.stringify(audit, null, 2), 'utf8');\n await writeFile(markdownPath, buildMarkdown(audit), 'utf8');\n\n return { audit, jsonPath, markdownPath };\n}\n","export { auditDensity, type AuditDensityOptions, type AuditDensityResult } from './run.js';\nexport {\n ClaimDensityAuditSchema,\n PerSourceDensitySchema,\n NearDuplicateClusterSchema,\n DensityFlagSchema,\n type ClaimDensityAudit,\n type PerSourceDensity,\n type NearDuplicateCluster,\n type DensityFlag,\n} from './schema.js';\n","export { extract, evidenceGrounded } from './extract.js';\nexport {\n auditDensity,\n ClaimDensityAuditSchema,\n PerSourceDensitySchema,\n NearDuplicateClusterSchema,\n DensityFlagSchema,\n type ClaimDensityAudit,\n type PerSourceDensity,\n type NearDuplicateCluster,\n type DensityFlag,\n type AuditDensityOptions,\n type AuditDensityResult,\n} from './density/index.js';\nexport {\n HeuristicClaimExtractor,\n OllamaInternClaimExtractor,\n defaultClaimExtractors,\n pickClaimExtractor,\n} from './extractors/index.js';\nexport {\n ClaimSchema,\n ConfidenceSchema,\n ClaimExtractorSchema,\n ReviewStateSchema,\n type Claim,\n} from './schema.js';\nexport type {\n ClaimExtractor,\n ClaimExtractorAdapter,\n ClaimExtractionInput,\n ClaimExtractionResult,\n Confidence,\n DraftClaim,\n ExtractClaimsOptions,\n ExtractClaimsSummary,\n ReviewState,\n SourceFetchPair,\n} from './types.js';\n","import { z } from 'zod';\n\nexport const ContradictionTypeSchema = z.enum([\n 'direct_conflict',\n 'scope_conflict',\n 'temporal_conflict',\n 'definition_conflict',\n 'evidence_conflict',\n 'overgeneralization_risk',\n]);\n\nexport const SeveritySchema = z.enum(['low', 'medium', 'high', 'blocking']);\n\nexport const OverlapAssessmentSchema = z.enum([\n 'fully_overlapping',\n 'partially_overlapping',\n 'non_overlapping',\n 'unknown',\n]);\n\nexport const ContradictionDetectorSchema = z.enum(['heuristic', 'ollama-intern']);\n\nexport const ContradictionStatusSchema = z.enum([\n 'unresolved',\n 'reconciled',\n 'preserved_deliberately',\n 'rejected',\n]);\n\nexport const ContradictionConfidenceSchema = z.enum(['low', 'medium', 'high']);\n\nexport const ContradictionSchema = z.object({\n contradiction_id: z.string().regex(/^cnt_[a-f0-9]{12}_(heuristic|ollama_intern)$/),\n section_id: z.string().regex(/^[0-9]{2}-[a-z0-9-]+$/),\n claim_ids: z\n .array(z.string().regex(/^clm_[a-f0-9]{12}_(heuristic|ollama_intern)_\\d+$/))\n .length(2, 'contradictions are pair-wise in v0.1'),\n source_ids: z.array(z.string().regex(/^src_[a-f0-9]{12}$/)).min(1),\n type: ContradictionTypeSchema,\n summary: z.string().min(1),\n scope_analysis: z.string(),\n overlap_assessment: OverlapAssessmentSchema,\n severity: SeveritySchema,\n confidence: ContradictionConfidenceSchema,\n detector: ContradictionDetectorSchema,\n detection_method: z.string().min(1),\n evidence: z.string(),\n status: ContradictionStatusSchema,\n created_at: z.string(),\n});\n\nexport type Contradiction = z.infer<typeof ContradictionSchema>;\n","import type { OverlapAssessment } from './types.js';\n\nconst STOP_WORDS = new Set([\n 'a', 'an', 'the', 'and', 'or', 'but', 'of', 'in', 'on', 'at', 'to', 'from',\n 'for', 'by', 'with', 'as', 'is', 'are', 'was', 'were', 'be', 'been', 'being',\n 'this', 'that', 'these', 'those', 'it', 'its', 'their', 'them', 'they',\n 'has', 'have', 'had', 'do', 'does', 'did', 'will', 'would', 'should', 'could',\n 'than', 'then', 'so', 'such', 'into', 'about', 'above', 'below', 'across',\n]);\n\nconst NEGATION_PATTERN =\n /\\b(not|never|no|none|cannot|can't|won't|don't|doesn't|isn't|aren't|wasn't|weren't|nothing|neither|nor)\\b/i;\n\nexport function tokenize(text: string): string[] {\n const matches = text.toLowerCase().match(/[a-z0-9]+/g);\n if (!matches) return [];\n return matches.filter((t) => !STOP_WORDS.has(t) && t.length > 2);\n}\n\nexport function jaccardSimilarity(a: string, b: string): number {\n const tokA = new Set(tokenize(a));\n const tokB = new Set(tokenize(b));\n if (tokA.size === 0 || tokB.size === 0) return 0;\n let intersection = 0;\n for (const t of tokA) if (tokB.has(t)) intersection += 1;\n const union = new Set([...tokA, ...tokB]).size;\n return intersection / union;\n}\n\nexport function hasNegation(text: string): boolean {\n return NEGATION_PATTERN.test(text);\n}\n\nexport function assessScopeOverlap(\n a: string | null,\n b: string | null,\n): OverlapAssessment {\n if (a === null && b === null) return 'unknown';\n if (a === null || b === null) return 'non_overlapping';\n const sim = jaccardSimilarity(a, b);\n if (sim >= 0.7) return 'fully_overlapping';\n if (sim >= 0.3) return 'partially_overlapping';\n return 'non_overlapping';\n}\n","import type { Claim } from '../../claims/schema.js';\nimport {\n assessScopeOverlap,\n hasNegation,\n jaccardSimilarity,\n} from '../scope.js';\nimport type {\n ContradictionDetector,\n DetectionResult,\n DraftContradiction,\n PairedDraft,\n} from '../types.js';\n\nconst TOKEN_OVERLAP_DIRECT_THRESHOLD = 0.5;\nconst TOKEN_OVERLAP_OVERGEN_THRESHOLD = 0.4;\n\nfunction compare(a: Claim, b: Claim): DraftContradiction | null {\n const overlap = assessScopeOverlap(a.scope, b.scope);\n const sim = jaccardSimilarity(a.asserts, b.asserts);\n const negA = hasNegation(a.asserts);\n const negB = hasNegation(b.asserts);\n const negationMismatch = negA !== negB;\n\n const oneScopedOneUniversal = (a.scope === null) !== (b.scope === null);\n if (oneScopedOneUniversal && sim >= TOKEN_OVERLAP_OVERGEN_THRESHOLD) {\n const universalSide = a.scope === null ? 'A' : 'B';\n const scopedSide = a.scope === null ? 'B' : 'A';\n const scopedScope = a.scope ?? b.scope!;\n return {\n type: 'overgeneralization_risk',\n summary: `Claim ${universalSide} appears to make a universal assertion while claim ${scopedSide} is contextually scoped to \"${scopedScope}\". Promotion of contextual claims to universal rules is the failure mode this gate is designed to catch.`,\n scope_analysis: `Claim ${scopedSide} has scope \"${scopedScope}\". Claim ${universalSide} has no recorded scope. The two assertions share key tokens (jaccard=${sim.toFixed(2)}), suggesting they address the same subject — but at incompatible levels of generality.`,\n overlap_assessment: overlap,\n severity: 'medium',\n confidence: sim >= 0.7 ? 'medium' : 'low',\n evidence: 'Asserts overlap on substantive tokens; scope-tagging is asymmetric (one universal, one specific).',\n };\n }\n\n if (\n sim >= TOKEN_OVERLAP_DIRECT_THRESHOLD &&\n negationMismatch &&\n (overlap === 'fully_overlapping' ||\n overlap === 'partially_overlapping' ||\n overlap === 'unknown')\n ) {\n return {\n type: 'direct_conflict',\n summary: `Claims share core terms but one negates a proposition the other affirms.`,\n scope_analysis: `Scope overlap assessed as ${overlap}; assertions disagree on a negated proposition (jaccard=${sim.toFixed(2)}).`,\n overlap_assessment: overlap,\n severity: 'medium',\n confidence: sim >= 0.75 ? 'medium' : 'low',\n evidence: 'Token similarity suggests the same subject. Negation marker mismatch suggests opposing positions on it.',\n };\n }\n\n return null;\n}\n\nexport class HeuristicContradictionDetector implements ContradictionDetector {\n readonly name = 'heuristic' as const;\n\n async available(): Promise<boolean> {\n return true;\n }\n\n async detect(claims: Claim[]): Promise<DetectionResult> {\n const drafts: PairedDraft[] = [];\n for (let i = 0; i < claims.length; i += 1) {\n for (let j = i + 1; j < claims.length; j += 1) {\n const a = claims[i]!;\n const b = claims[j]!;\n const draft = compare(a, b);\n if (draft) drafts.push({ claim_a: a, claim_b: b, draft });\n }\n }\n return { ok: true, drafts, method: 'heuristic_similarity_negation' };\n }\n}\n","import { normalizeOllamaHost } from '../../sources/extractors/ollama-intern.js';\nimport type { Claim } from '../../claims/schema.js';\nimport type {\n ContradictionDetector,\n ContradictionType,\n DetectionResult,\n DraftContradiction,\n OverlapAssessment,\n PairedDraft,\n Severity,\n} from '../types.js';\n\nconst DEFAULT_HOST = 'http://localhost:11434';\nconst DEFAULT_MODEL = 'hermes3:8b';\nconst DEFAULT_TIMEOUT_MS = 120_000;\n\nconst SYSTEM_PROMPT = `You are detecting tension between two atomic claims from a research pack.\n\nReturn ONE JSON object. If there is no contradiction, return {\"type\": \"none\"}.\n\nIf there IS a contradiction:\n{\n \"type\": \"direct_conflict\" | \"scope_conflict\" | \"temporal_conflict\" | \"definition_conflict\" | \"evidence_conflict\" | \"overgeneralization_risk\",\n \"summary\": \"ONE sentence describing the tension\",\n \"scope_analysis\": \"ONE sentence on whether and how the claims' scopes overlap\",\n \"overlap_assessment\": \"fully_overlapping\" | \"partially_overlapping\" | \"non_overlapping\" | \"unknown\",\n \"severity\": \"low\" | \"medium\" | \"high\" | \"blocking\",\n \"confidence\": \"low\" | \"medium\" | \"high\",\n \"evidence\": \"what specifically about the two claims signals the tension\"\n}\n\nHard rules:\n- direct_conflict requires overlapping scopes. If scopes do not overlap, choose scope_conflict, temporal_conflict, definition_conflict, evidence_conflict, or \"none\".\n- overgeneralization_risk fires when one claim appears to widen a contextual assertion into a universal rule without evidence. The publish-policy-promoted-from-role-os-rollout failure mode is the canonical example.\n- Be conservative. If the tension is unclear, return \"none\".\n- Do not invent claims. Only assess what is given.\n- Do not decide which claim is true.`;\n\ninterface ChatResponse {\n message?: { content?: string };\n response?: string;\n}\n\nconst VALID_TYPES: ContradictionType[] = [\n 'direct_conflict',\n 'scope_conflict',\n 'temporal_conflict',\n 'definition_conflict',\n 'evidence_conflict',\n 'overgeneralization_risk',\n];\n\nconst VALID_OVERLAPS: OverlapAssessment[] = [\n 'fully_overlapping',\n 'partially_overlapping',\n 'non_overlapping',\n 'unknown',\n];\n\nconst VALID_SEVERITIES: Severity[] = ['low', 'medium', 'high', 'blocking'];\n\nconst VALID_CONFIDENCES = ['low', 'medium', 'high'] as const;\ntype ValidConfidence = (typeof VALID_CONFIDENCES)[number];\n\nfunction asEnum<T extends string>(value: unknown, allowed: readonly T[], fallback: T): T {\n return typeof value === 'string' && (allowed as readonly string[]).includes(value)\n ? (value as T)\n : fallback;\n}\n\nfunction asString(value: unknown, fallback: string): string {\n return typeof value === 'string' && value.trim().length > 0 ? value.trim() : fallback;\n}\n\nexport interface OllamaContradictionConfig {\n host?: string;\n model?: string;\n timeoutMs?: number;\n fetchImpl?: typeof fetch;\n}\n\nexport class OllamaInternContradictionDetector implements ContradictionDetector {\n readonly name = 'ollama-intern' as const;\n private readonly host: string;\n readonly model: string;\n private readonly timeoutMs: number;\n private readonly fetchImpl: typeof fetch;\n\n constructor(config: OllamaContradictionConfig = {}) {\n this.host = normalizeOllamaHost(config.host ?? process.env.OLLAMA_HOST ?? DEFAULT_HOST);\n this.model = config.model ?? process.env.OLLAMA_INTERN_MODEL ?? DEFAULT_MODEL;\n this.timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n this.fetchImpl = config.fetchImpl ?? globalThis.fetch;\n }\n\n async available(): Promise<boolean> {\n try {\n const ctrl = new AbortController();\n const t = setTimeout(() => ctrl.abort(), 1500);\n const res = await this.fetchImpl(`${this.host}/api/tags`, { signal: ctrl.signal });\n clearTimeout(t);\n if (!res.ok) return false;\n const body = (await res.json()) as { models?: Array<{ name: string }> };\n const names = (body.models ?? []).map((m) => m.name);\n const family = this.model.split(':')[0] ?? this.model;\n return names.some(\n (n) => n === this.model || n === family || n.startsWith(`${family}:`),\n );\n } catch {\n return false;\n }\n }\n\n private formatClaim(label: string, claim: Claim): string {\n return [\n `Claim ${label} (${claim.claim_id}):`,\n ` asserts: ${claim.asserts}`,\n ` scope: ${claim.scope ?? 'null'}`,\n ` not: ${claim.not ?? 'null'}`,\n ` evidence_excerpt: ${claim.evidence_excerpt}`,\n ` source_ids: ${claim.source_ids.join(', ')}`,\n ].join('\\n');\n }\n\n private async classifyPair(a: Claim, b: Claim): Promise<DraftContradiction | null> {\n const userMsg = [this.formatClaim('A', a), '', this.formatClaim('B', b)].join('\\n');\n\n const ctrl = new AbortController();\n const t = setTimeout(() => ctrl.abort(), this.timeoutMs);\n let body: ChatResponse;\n try {\n const res = await this.fetchImpl(`${this.host}/api/chat`, {\n method: 'POST',\n signal: ctrl.signal,\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n model: this.model,\n stream: false,\n format: 'json',\n // Override Ollama's default 4096 context for the same reason as\n // the claim extractor — pairwise prompts with full claim+scope+\n // not+evidence_excerpt can exceed 4K on dense fields.\n options: { num_ctx: 8192 },\n messages: [\n { role: 'system', content: SYSTEM_PROMPT },\n { role: 'user', content: userMsg },\n ],\n }),\n });\n if (!res.ok) return null;\n body = (await res.json()) as ChatResponse;\n } catch {\n return null;\n } finally {\n clearTimeout(t);\n }\n\n const text = body.message?.content ?? body.response ?? '';\n let parsed: Record<string, unknown>;\n try {\n parsed = JSON.parse(text) as Record<string, unknown>;\n } catch {\n return null;\n }\n\n if (parsed.type === 'none' || !parsed.type) return null;\n\n const type = asEnum<ContradictionType>(parsed.type, VALID_TYPES, 'direct_conflict');\n if (!VALID_TYPES.includes(parsed.type as ContradictionType)) return null;\n\n return {\n type,\n summary: asString(parsed.summary, '(no summary)'),\n scope_analysis: asString(parsed.scope_analysis, ''),\n overlap_assessment: asEnum<OverlapAssessment>(\n parsed.overlap_assessment,\n VALID_OVERLAPS,\n 'unknown',\n ),\n severity: asEnum<Severity>(parsed.severity, VALID_SEVERITIES, 'low'),\n confidence: asEnum<ValidConfidence>(parsed.confidence, VALID_CONFIDENCES, 'low'),\n evidence: asString(parsed.evidence, ''),\n };\n }\n\n async detect(claims: Claim[]): Promise<DetectionResult> {\n // Prefilter: only LLM-classify pairs that look like potential tensions.\n // For dense sections (50+ claims) full N² is feasible but expensive; for\n // huge sections it's outright intractable. The prefilter is a token\n // Jaccard score plus a scope-overlap signal — both cheap and\n // deterministic. Pairs failing the prefilter contribute nothing to the\n // final ledger; the model never sees them.\n const candidatePairs = candidateContradictionPairs(claims);\n const drafts: PairedDraft[] = [];\n for (const [i, j] of candidatePairs) {\n const a = claims[i]!;\n const b = claims[j]!;\n const draft = await this.classifyPair(a, b);\n if (draft) drafts.push({ claim_a: a, claim_b: b, draft });\n }\n return {\n ok: true,\n drafts,\n method:\n candidatePairs.length === (claims.length * (claims.length - 1)) / 2\n ? 'ollama_intern_pairwise_classification'\n : 'ollama_intern_prefiltered_pairwise_classification',\n };\n }\n}\n\n// Deterministic prefilter for which claim pairs are worth LLM classification.\n// Returns pair indices [i,j] (i < j). A pair qualifies if EITHER:\n// - normalised-asserts token Jaccard >= 0.25 (similar topic — potential\n// tension worth checking), OR\n// - scopes both non-null AND share >= 1 token of length > 3 (claims about\n// the same scope are the canonical site of contradiction)\n// A claim with empty asserts is never paired.\nexport function candidateContradictionPairs(claims: Claim[]): Array<[number, number]> {\n const SIM_THRESHOLD = 0.25;\n const tokenSets: Array<Set<string>> = claims.map((c) =>\n tokenSet(c.asserts),\n );\n const scopeTokens: Array<Set<string>> = claims.map((c) =>\n c.scope ? tokenSet(c.scope) : new Set<string>(),\n );\n\n const out: Array<[number, number]> = [];\n for (let i = 0; i < claims.length; i += 1) {\n if (tokenSets[i]!.size === 0) continue;\n for (let j = i + 1; j < claims.length; j += 1) {\n if (tokenSets[j]!.size === 0) continue;\n const sim = jaccard(tokenSets[i]!, tokenSets[j]!);\n if (sim >= SIM_THRESHOLD) {\n out.push([i, j]);\n continue;\n }\n // Scope-overlap fallback.\n const aScope = scopeTokens[i]!;\n const bScope = scopeTokens[j]!;\n if (aScope.size > 0 && bScope.size > 0) {\n let shared = 0;\n for (const t of aScope) if (bScope.has(t)) shared += 1;\n if (shared >= 1) out.push([i, j]);\n }\n }\n }\n return out;\n}\n\nfunction tokenSet(s: string): Set<string> {\n const out = new Set<string>();\n for (const tok of s\n .toLowerCase()\n .replace(/[^a-z0-9 ]+/g, ' ')\n .split(/\\s+/)) {\n if (tok.length > 3) out.add(tok);\n }\n return out;\n}\n\nfunction jaccard(a: Set<string>, b: Set<string>): number {\n if (a.size === 0 && b.size === 0) return 0;\n let inter = 0;\n for (const t of a) if (b.has(t)) inter += 1;\n const union = a.size + b.size - inter;\n return union === 0 ? 0 : inter / union;\n}\n","import type { ContradictionDetector } from '../types.js';\nimport { HeuristicContradictionDetector } from './heuristic.js';\nimport { OllamaInternContradictionDetector } from './ollama-intern.js';\n\nexport { HeuristicContradictionDetector } from './heuristic.js';\nexport { OllamaInternContradictionDetector } from './ollama-intern.js';\n\nexport function defaultContradictionDetectors(): ContradictionDetector[] {\n return [new OllamaInternContradictionDetector(), new HeuristicContradictionDetector()];\n}\n\nexport async function pickContradictionDetector(\n detectors: ContradictionDetector[],\n): Promise<ContradictionDetector> {\n for (const d of detectors) {\n if (await d.available()) return d;\n }\n throw new Error(\n 'No contradiction detector available. The HeuristicContradictionDetector should always be available — this indicates a bug.',\n );\n}\n","import type { Contradiction } from './schema.js';\n\nexport function renderMarkdownView(args: {\n sectionId: string;\n candidateClaims: number;\n contradictions: Contradiction[];\n detector: string;\n detectionMethod: string;\n}): string {\n const { sectionId, candidateClaims, contradictions, detector, detectionMethod } = args;\n const lines: string[] = [];\n lines.push(`# Contradictions: ${sectionId}`);\n lines.push('');\n if (contradictions.length === 0) {\n lines.push(\n `No contradiction candidates detected by ${detector} (${detectionMethod}) over ${candidateClaims} candidate claim${candidateClaims === 1 ? '' : 's'}.`,\n );\n lines.push('');\n lines.push(\n `Detection methods are not exhaustive. Adversarial review may surface tensions the detector missed. A clean section is a valid result, not proof of completeness.`,\n );\n return lines.join('\\n') + '\\n';\n }\n\n lines.push(\n `${contradictions.length} contradiction candidate${contradictions.length === 1 ? '' : 's'} detected by ${detector} (${detectionMethod}) over ${candidateClaims} candidate claim${candidateClaims === 1 ? '' : 's'}.`,\n );\n lines.push('');\n lines.push(\n 'Status: all unresolved. The gate engine determines whether unresolved contradictions block synthesis. The adversarial reviewer determines whether each contradiction is real, weak, or misclassified. This view is the map, not the judgment.',\n );\n lines.push('');\n lines.push('---');\n lines.push('');\n\n for (const c of contradictions) {\n lines.push(`## ${c.contradiction_id}: ${c.type}`);\n lines.push('');\n lines.push(`- **Severity:** ${c.severity}`);\n lines.push(`- **Confidence:** ${c.confidence}`);\n lines.push(`- **Status:** ${c.status}`);\n lines.push(`- **Overlap:** ${c.overlap_assessment}`);\n lines.push(`- **Detector:** ${c.detector} (${c.detection_method})`);\n lines.push('');\n lines.push(`**Claims:** \\`${c.claim_ids.join('`, `')}\\``);\n lines.push(`**Sources:** \\`${c.source_ids.join('`, `')}\\``);\n lines.push('');\n lines.push(`**Summary:** ${c.summary}`);\n lines.push('');\n if (c.scope_analysis) {\n lines.push(`**Scope analysis:** ${c.scope_analysis}`);\n lines.push('');\n }\n if (c.evidence) {\n lines.push(`**Evidence:** ${c.evidence}`);\n lines.push('');\n }\n lines.push('---');\n lines.push('');\n }\n return lines.join('\\n');\n}\n","import { z } from 'zod';\n\n// Triage is the deterministic / semi-deterministic shaping pass between\n// extraction and review. It does NOT mutate claims.jsonl. Triage decisions\n// live in their own append-only ledger and downstream commands (contradict,\n// review) can opt into reading only the selected_for_review subset via\n// --triaged-only.\n//\n// Law #13 (the law this module enforces):\n// Extraction may overproduce; synthesis may not inherit abundance.\n// Claim abundance is not research quality. Claims must be triaged before\n// they can compete for synthesis.\n\nexport const TriageDecisionSchema = z.enum([\n // Passes triage and is forwarded to review.\n 'selected_for_review',\n // Parked: kept on the canonical ledger as research truth, but not advanced.\n 'parked_duplicate',\n 'parked_overdense_source',\n 'parked_weak_scope',\n 'parked_low_value',\n // Routed for repair before re-triage.\n 'needs_scope_repair',\n 'needs_human_review',\n]);\n\nexport const ClaimTriageSchema = z.object({\n triage_id: z.string().regex(/^tri_[a-f0-9]{12}$/),\n claim_id: z.string().regex(/^clm_[a-f0-9]{12}_(heuristic|ollama_intern)_\\d+$/),\n section_id: z.string().regex(/^[0-9]{2}-[a-z0-9-]+$/),\n decision: TriageDecisionSchema,\n reason: z.string().min(1),\n // Rank among selected_for_review claims (1 = highest priority). null for\n // any non-selected decision.\n rank: z.number().int().positive().nullable(),\n // Quality score [0..1] used to sort. Stable. Higher = better.\n quality_score: z.number().min(0).max(1),\n triage_method: z.string().min(1),\n created_at: z.string(),\n});\n\nexport const TriageSummarySchema = z.object({\n summary_id: z.string().regex(/^tris_[0-9]+_[a-z0-9-]+$/),\n section_id: z.string().regex(/^[0-9]{2}-[a-z0-9-]+$/),\n triaged_at: z.string(),\n research_os_version: z.string(),\n triage_method: z.string(),\n candidate_claims: z.number().int().nonnegative(),\n decisions: z.record(TriageDecisionSchema, z.number().int().nonnegative()),\n per_source_cap: z.number().int().positive(),\n duplicate_clusters_collapsed: z.number().int().nonnegative(),\n selected_count: z.number().int().nonnegative(),\n selected_per_source: z.array(\n z.object({\n source_id: z.string().regex(/^src_[a-f0-9]{12}$/),\n selected: z.number().int().nonnegative(),\n total: z.number().int().nonnegative(),\n }),\n ),\n});\n\nexport type TriageDecision = z.infer<typeof TriageDecisionSchema>;\nexport type ClaimTriage = z.infer<typeof ClaimTriageSchema>;\nexport type TriageSummary = z.infer<typeof TriageSummarySchema>;\n","import { existsSync } from 'node:fs';\nimport { createHash } from 'node:crypto';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { join, resolve } from 'node:path';\n\nimport { PackNotFoundError, SectionNotFoundError } from '../errors.js';\nimport { RESEARCH_OS_VERSION } from '../index.js';\nimport { ClaimSchema, type Claim } from '../claims/schema.js';\nimport {\n ClaimTriageSchema,\n TriageSummarySchema,\n type ClaimTriage,\n type TriageDecision,\n type TriageSummary,\n} from './schema.js';\nimport type { TriageOptions, TriageRunResult } from './types.js';\n\nconst DEFAULT_PER_SOURCE_CAP = 10;\nconst DEFAULT_MIN_ASSERT_CHARS = 30;\n\n\nfunction normaliseAssert(s: string): string {\n return s\n .toLowerCase()\n .replace(/[^a-z0-9 ]+/g, ' ')\n .replace(/\\s+/g, ' ')\n .trim();\n}\n\n// Quality score in [0..1] — purely deterministic from claim fields. Higher\n// is better; ranking is stable.\nfunction qualityScore(claim: Claim): number {\n let score = 0;\n // scope present is the single largest signal (extractor met the law).\n if (claim.scope && claim.scope.length > 0) score += 0.4;\n if (claim.not && claim.not.length > 0) score += 0.2;\n if (claim.confidence === 'high') score += 0.2;\n else if (claim.confidence === 'medium') score += 0.1;\n // Goldilocks asserts length: 60..240 chars rewarded most.\n const len = claim.asserts.length;\n if (len >= 60 && len <= 240) score += 0.15;\n else if (len >= 30 && len < 60) score += 0.05;\n // Multi-excerpt grounding rewards a tiny bit (model crossed spans).\n if (claim.evidence_excerpt_ids.length > 1) score += 0.05;\n return Math.min(1, Math.max(0, score));\n}\n\nfunction makeTriageId(claimId: string): string {\n // 12 hex chars derived from claim_id so re-runs over identical claim\n // produce identical triage_ids — keeps the ledger idempotent.\n return 'tri_' + createHash('sha256').update(claimId).digest('hex').slice(0, 12);\n}\n\nasync function readClaims(packPath: string, sectionId: string): Promise<Claim[]> {\n const path = join(packPath, 'sections', sectionId, 'claims.jsonl');\n if (!existsSync(path)) return [];\n const text = await readFile(path, 'utf8');\n const out: Claim[] = [];\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n out.push(ClaimSchema.parse(JSON.parse(line)));\n } catch {\n /* skip */\n }\n }\n return out;\n}\n\ninterface TriageWorkRow {\n claim: Claim;\n decision: TriageDecision;\n reason: string;\n quality: number;\n rank: number | null;\n}\n\nexport async function triage(options: TriageOptions): Promise<TriageRunResult> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n if (!existsSync(join(packPath, 'research.yaml'))) throw new PackNotFoundError(packPath);\n if (!existsSync(join(packPath, 'sections', options.sectionId)))\n throw new SectionNotFoundError(options.sectionId);\n\n const perSourceCap = options.perSourceCap ?? DEFAULT_PER_SOURCE_CAP;\n const minAssertChars = options.minAssertChars ?? DEFAULT_MIN_ASSERT_CHARS;\n const stamp = (options.now ?? (() => new Date()))();\n const stampIso = stamp.toISOString();\n const stampMs = stamp.getTime();\n\n const claims = await readClaims(packPath, options.sectionId);\n\n // Pass 1 — apply per-claim filters in priority order. The first matching\n // filter wins; downstream filters skip any already-decided row.\n const rows: TriageWorkRow[] = claims.map((claim) => ({\n claim,\n decision: 'selected_for_review',\n reason: '',\n quality: qualityScore(claim),\n rank: null,\n }));\n\n // 1.1 parked_low_value — trivially short asserts (definitional / restating).\n for (const row of rows) {\n if (row.decision !== 'selected_for_review') continue;\n if (row.claim.asserts.length < minAssertChars) {\n row.decision = 'parked_low_value';\n row.reason = `Assert length ${row.claim.asserts.length} chars below the ${minAssertChars}-char floor; treated as definitional or restating.`;\n }\n }\n\n // 1.2 parked_weak_scope — both scope and not are null on a substantive\n // assertion. The reviewer can't even check overgeneralization without scope.\n for (const row of rows) {\n if (row.decision !== 'selected_for_review') continue;\n if (\n row.claim.scope === null &&\n row.claim.not === null &&\n row.claim.asserts.length > 40\n ) {\n row.decision = 'parked_weak_scope';\n row.reason =\n 'Substantive assertion with scope=null and not=null. Without scope/not boundaries the claim cannot earn a synthesis slot.';\n }\n }\n\n // 1.3 needs_scope_repair — scope is missing but `not` is set, OR vice\n // versa. The asymmetric case is recoverable: re-extract or hand-correct.\n for (const row of rows) {\n if (row.decision !== 'selected_for_review') continue;\n if (\n (row.claim.scope === null && row.claim.not !== null) ||\n (row.claim.scope !== null && row.claim.not === null && row.claim.asserts.length > 80)\n ) {\n row.decision = 'needs_scope_repair';\n row.reason = 'Scope or not is missing on a substantive claim; recoverable with a scope-repair pass.';\n }\n }\n\n // Pass 2 — dedupe by normalised asserts. Keep the highest-quality claim\n // in each cluster; park the rest as parked_duplicate. Only run on rows\n // still at selected_for_review.\n const clusters = new Map<string, TriageWorkRow[]>();\n for (const row of rows) {\n if (row.decision !== 'selected_for_review') continue;\n const key = normaliseAssert(row.claim.asserts);\n if (!key) continue;\n const arr = clusters.get(key) ?? [];\n arr.push(row);\n clusters.set(key, arr);\n }\n let duplicateClustersCollapsed = 0;\n for (const [, members] of clusters) {\n if (members.length <= 1) continue;\n duplicateClustersCollapsed += 1;\n // Sort by quality desc, then claim_id asc for determinism.\n members.sort((a, b) => {\n if (b.quality !== a.quality) return b.quality - a.quality;\n return a.claim.claim_id.localeCompare(b.claim.claim_id);\n });\n for (let i = 1; i < members.length; i += 1) {\n const r = members[i]!;\n r.decision = 'parked_duplicate';\n r.reason = `Normalised assertion matches ${members[0]!.claim.claim_id} which has higher quality (${members[0]!.quality.toFixed(2)} vs ${r.quality.toFixed(2)}).`;\n }\n }\n\n // Pass 3 — per-source cap. For each source with too many remaining\n // selected_for_review rows, keep the top perSourceCap by quality and park\n // the rest as parked_overdense_source.\n const stillSelectedBySrc = new Map<string, TriageWorkRow[]>();\n for (const row of rows) {\n if (row.decision !== 'selected_for_review') continue;\n for (const sid of row.claim.source_ids) {\n const arr = stillSelectedBySrc.get(sid) ?? [];\n arr.push(row);\n stillSelectedBySrc.set(sid, arr);\n }\n }\n for (const [sid, list] of stillSelectedBySrc) {\n if (list.length <= perSourceCap) continue;\n list.sort((a, b) => {\n if (b.quality !== a.quality) return b.quality - a.quality;\n return a.claim.claim_id.localeCompare(b.claim.claim_id);\n });\n for (let i = perSourceCap; i < list.length; i += 1) {\n const r = list[i]!;\n // Only mark the row over the cap if it isn't already parked by a\n // different source (a multi-source claim is kept if any of its\n // sources still has cap headroom).\n if (r.decision !== 'selected_for_review') continue;\n r.decision = 'parked_overdense_source';\n r.reason = `Source ${sid} contributed ${list.length} candidates; cap is ${perSourceCap}. This claim's quality (${r.quality.toFixed(2)}) ranks ${i + 1} for the source.`;\n }\n }\n\n // Pass 4 — assign ranks to surviving selected_for_review rows so review\n // can process in priority order.\n const surviving = rows.filter((r) => r.decision === 'selected_for_review');\n surviving.sort((a, b) => {\n if (b.quality !== a.quality) return b.quality - a.quality;\n return a.claim.claim_id.localeCompare(b.claim.claim_id);\n });\n surviving.forEach((r, i) => {\n r.rank = i + 1;\n if (!r.reason) r.reason = `Selected for review at rank ${r.rank} (quality ${r.quality.toFixed(2)}).`;\n });\n\n // Build triage records.\n const records: ClaimTriage[] = rows.map((r) =>\n ClaimTriageSchema.parse({\n triage_id: makeTriageId(r.claim.claim_id),\n claim_id: r.claim.claim_id,\n section_id: options.sectionId,\n decision: r.decision,\n reason: r.reason,\n rank: r.rank,\n quality_score: Number(r.quality.toFixed(4)),\n triage_method: 'research_os_triage_v1',\n created_at: stampIso,\n }),\n );\n\n // Per-source counts for the summary.\n const perSourceTotal = new Map<string, number>();\n const perSourceSelected = new Map<string, number>();\n for (const r of rows) {\n for (const sid of r.claim.source_ids) {\n perSourceTotal.set(sid, (perSourceTotal.get(sid) ?? 0) + 1);\n if (r.decision === 'selected_for_review') {\n perSourceSelected.set(sid, (perSourceSelected.get(sid) ?? 0) + 1);\n }\n }\n }\n const decisions: Record<string, number> = {};\n for (const r of rows) {\n decisions[r.decision] = (decisions[r.decision] ?? 0) + 1;\n }\n\n const summary: TriageSummary = TriageSummarySchema.parse({\n summary_id: `tris_${stampMs}_${options.sectionId}`,\n section_id: options.sectionId,\n triaged_at: stampIso,\n research_os_version: RESEARCH_OS_VERSION,\n triage_method: 'research_os_triage_v1',\n candidate_claims: claims.length,\n decisions,\n per_source_cap: perSourceCap,\n duplicate_clusters_collapsed: duplicateClustersCollapsed,\n selected_count: surviving.length,\n selected_per_source: Array.from(perSourceTotal.entries())\n .map(([source_id, total]) => ({\n source_id,\n selected: perSourceSelected.get(source_id) ?? 0,\n total,\n }))\n .sort((a, b) => b.total - a.total),\n });\n\n // Write outputs.\n const sectionDir = join(packPath, 'sections', options.sectionId);\n const auditsDir = join(packPath, 'audits');\n await mkdir(sectionDir, { recursive: true });\n await mkdir(auditsDir, { recursive: true });\n const triageJsonlPath = join(sectionDir, 'claim-triage.jsonl');\n const triageMarkdownPath = join(sectionDir, 'claim-triage.md');\n const summaryJsonPath = join(auditsDir, `${options.sectionId}-claim-triage.json`);\n\n await writeFile(triageJsonlPath, records.map((r) => JSON.stringify(r)).join('\\n') + '\\n', 'utf8');\n await writeFile(triageMarkdownPath, buildMarkdown(records, summary), 'utf8');\n await writeFile(summaryJsonPath, JSON.stringify(summary, null, 2), 'utf8');\n\n const parkedCount = rows.filter((r) => r.decision.startsWith('parked_')).length;\n const needsRepairCount = rows.filter(\n (r) => r.decision === 'needs_scope_repair' || r.decision === 'needs_human_review',\n ).length;\n\n return {\n triageJsonlPath,\n triageMarkdownPath,\n summaryJsonPath,\n candidateClaims: claims.length,\n selectedCount: surviving.length,\n parkedCount,\n needsRepairCount,\n decisions,\n };\n}\n\n// Read the triage ledger for a section. Used by --triaged-only consumers.\nexport async function readTriagedClaimIds(\n packPath: string,\n sectionId: string,\n): Promise<Set<string>> {\n const path = join(packPath, 'sections', sectionId, 'claim-triage.jsonl');\n const out = new Set<string>();\n if (!existsSync(path)) return out;\n const text = await readFile(path, 'utf8');\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n const r = ClaimTriageSchema.parse(JSON.parse(line));\n if (r.decision === 'selected_for_review') out.add(r.claim_id);\n } catch {\n /* skip */\n }\n }\n return out;\n}\n\nfunction buildMarkdown(records: ClaimTriage[], summary: TriageSummary): string {\n const lines: string[] = [];\n lines.push(`# Claim triage: ${summary.section_id}`);\n lines.push('');\n lines.push(`- **Summary ID:** \\`${summary.summary_id}\\``);\n lines.push(`- **Triaged at:** ${summary.triaged_at}`);\n lines.push(`- **Method:** ${summary.triage_method}`);\n lines.push(`- **Candidate claims:** ${summary.candidate_claims}`);\n lines.push(`- **Selected for review:** ${summary.selected_count}`);\n lines.push(`- **Per-source cap:** ${summary.per_source_cap}`);\n lines.push(`- **Duplicate clusters collapsed:** ${summary.duplicate_clusters_collapsed}`);\n lines.push('');\n lines.push('## Decisions');\n lines.push('');\n lines.push('| Decision | Count |');\n lines.push('|---|---:|');\n for (const [k, v] of Object.entries(summary.decisions)) {\n lines.push(`| \\`${k}\\` | ${v} |`);\n }\n lines.push('');\n lines.push('## Selected per source');\n lines.push('');\n lines.push('| Source | Selected | Total |');\n lines.push('|---|---:|---:|');\n for (const s of summary.selected_per_source) {\n lines.push(`| \\`${s.source_id}\\` | ${s.selected} | ${s.total} |`);\n }\n lines.push('');\n lines.push('## Triage records (compact)');\n lines.push('');\n lines.push('| Rank | Decision | Quality | Claim ID | Reason |');\n lines.push('|---:|---|---:|---|---|');\n // Selected first (in rank order), then everything else grouped by decision.\n const selected = records.filter((r) => r.decision === 'selected_for_review');\n selected.sort((a, b) => (a.rank ?? 0) - (b.rank ?? 0));\n for (const r of selected) {\n lines.push(`| ${r.rank ?? ''} | \\`${r.decision}\\` | ${r.quality_score.toFixed(2)} | \\`${r.claim_id}\\` | ${r.reason.replace(/\\|/g, '\\\\|')} |`);\n }\n const parked = records.filter((r) => r.decision !== 'selected_for_review');\n parked.sort((a, b) => a.decision.localeCompare(b.decision));\n for (const r of parked) {\n lines.push(`| | \\`${r.decision}\\` | ${r.quality_score.toFixed(2)} | \\`${r.claim_id}\\` | ${r.reason.replace(/\\|/g, '\\\\|')} |`);\n }\n lines.push('');\n lines.push('---');\n lines.push('');\n lines.push('_Triage does not mutate `claims.jsonl`. Parked claims remain on the canonical ledger as research truth; they are simply excluded from the next review pass._');\n return lines.join('\\n');\n}\n","import { createHash } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { appendFile, readFile, writeFile } from 'node:fs/promises';\nimport { join, resolve } from 'node:path';\n\nimport { PackNotFoundError, SectionNotFoundError } from '../errors.js';\nimport { ClaimSchema, type Claim } from '../claims/schema.js';\nimport { ContradictionSchema, type Contradiction } from './schema.js';\nimport {\n pickContradictionDetector,\n} from './detectors/index.js';\nimport { HeuristicContradictionDetector } from './detectors/heuristic.js';\nimport { OllamaInternContradictionDetector } from './detectors/ollama-intern.js';\nimport { renderMarkdownView } from './markdown.js';\nimport type {\n ContradictionDetector,\n ContradictionDetectorName,\n MapOptions,\n MapSummary,\n PairedDraft,\n} from './types.js';\n\nconst DETECTOR_ID_PART: Record<ContradictionDetectorName, string> = {\n heuristic: 'heuristic',\n 'ollama-intern': 'ollama_intern',\n};\n\nasync function readCandidateClaims(packPath: string, sectionId: string): Promise<Claim[]> {\n const path = join(packPath, 'sections', sectionId, 'claims.jsonl');\n if (!existsSync(path)) return [];\n const text = await readFile(path, 'utf8');\n const claims: Claim[] = [];\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n const parsed = ClaimSchema.parse(JSON.parse(line));\n if (parsed.review_state !== 'candidate') continue;\n claims.push(parsed);\n }\n return claims;\n}\n\nasync function readExistingContradictions(\n packPath: string,\n sectionId: string,\n): Promise<Contradiction[]> {\n const path = join(packPath, 'sections', sectionId, 'contradictions.jsonl');\n if (!existsSync(path)) return [];\n const text = await readFile(path, 'utf8');\n const list: Contradiction[] = [];\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n list.push(ContradictionSchema.parse(JSON.parse(line)));\n } catch {\n /* skip malformed */\n }\n }\n return list;\n}\n\nfunction pairHash(claimAId: string, claimBId: string): string {\n const sorted = [claimAId, claimBId].sort();\n return createHash('sha256')\n .update(sorted.join('|'))\n .digest('hex')\n .slice(0, 12);\n}\n\nfunction buildContradiction(args: {\n paired: PairedDraft;\n sectionId: string;\n detector: ContradictionDetectorName;\n detectionMethod: string;\n}): Contradiction {\n const { paired, sectionId, detector, detectionMethod } = args;\n const { claim_a, claim_b, draft } = paired;\n const detectorIdPart = DETECTOR_ID_PART[detector];\n const id = `cnt_${pairHash(claim_a.claim_id, claim_b.claim_id)}_${detectorIdPart}`;\n const sourceIds = Array.from(\n new Set<string>([...claim_a.source_ids, ...claim_b.source_ids]),\n );\n return ContradictionSchema.parse({\n contradiction_id: id,\n section_id: sectionId,\n claim_ids: [claim_a.claim_id, claim_b.claim_id].sort(),\n source_ids: sourceIds,\n type: draft.type,\n summary: draft.summary,\n scope_analysis: draft.scope_analysis,\n overlap_assessment: draft.overlap_assessment,\n severity: draft.severity,\n confidence: draft.confidence,\n detector,\n detection_method: detectionMethod,\n evidence: draft.evidence,\n status: 'unresolved',\n created_at: new Date().toISOString(),\n });\n}\n\nconst VALID_DETECTOR_MODES = ['auto', 'heuristic', 'ollama-intern'] as const;\n\nasync function resolveDetector(options: MapOptions): Promise<{\n detector: ContradictionDetector;\n announcement: string;\n}> {\n const mode = options.detectorMode ?? 'auto';\n\n if (!VALID_DETECTOR_MODES.includes(mode as (typeof VALID_DETECTOR_MODES)[number])) {\n throw new Error(\n `contradict map: invalid --detector value \"${mode}\"; valid values are: auto, heuristic, ollama-intern`,\n );\n }\n\n if (mode === 'heuristic') {\n return {\n detector: new HeuristicContradictionDetector(),\n announcement: 'contradict map: using heuristic detector',\n };\n }\n\n if (mode === 'ollama-intern') {\n const d = new OllamaInternContradictionDetector(options.ollamaConfig ?? {});\n if (!(await d.available())) {\n throw new Error(\n `contradict map: ollama-intern detector requested but model ${d.model} is unavailable; aborting (use --detector heuristic to bypass)`,\n );\n }\n return {\n detector: d,\n announcement: `contradict map: using ollama-intern detector with model ${d.model}`,\n };\n }\n\n // auto mode — preserve existing env-var-driven behavior; announce which path ran\n const detectors =\n options.detectors ??\n [\n new OllamaInternContradictionDetector(options.ollamaConfig ?? {}),\n new HeuristicContradictionDetector(),\n ];\n const detector = await pickContradictionDetector(detectors);\n\n if (detector.name === 'ollama-intern') {\n const modelName =\n detector instanceof OllamaInternContradictionDetector\n ? detector.model\n : (process.env.OLLAMA_INTERN_MODEL ?? 'hermes3:8b');\n return {\n detector,\n announcement: `contradict map: using ollama-intern detector with model ${modelName}`,\n };\n }\n\n return {\n detector,\n announcement: 'contradict map: ollama-intern unavailable; using heuristic detector',\n };\n}\n\nexport async function map(options: MapOptions): Promise<MapSummary> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n if (!existsSync(join(packPath, 'research.yaml'))) throw new PackNotFoundError(packPath);\n const sectionDir = join(packPath, 'sections', options.sectionId);\n if (!existsSync(sectionDir)) throw new SectionNotFoundError(options.sectionId);\n\n let candidateClaims = await readCandidateClaims(packPath, options.sectionId);\n if (options.triagedOnly) {\n const { readTriagedClaimIds } = await import('../triage/run.js');\n const allowed = await readTriagedClaimIds(packPath, options.sectionId);\n candidateClaims = candidateClaims.filter((c) => allowed.has(c.claim_id));\n }\n const { detector, announcement } = await resolveDetector(options);\n\n const summary: MapSummary = {\n sectionId: options.sectionId,\n detector: detector.name,\n detectionMethod: '',\n candidateClaims: candidateClaims.length,\n pairsCompared: 0,\n contradictionsAdded: 0,\n contradictionsDeduped: 0,\n contradictionIds: [],\n detectorError: null,\n detectorAnnouncement: announcement,\n };\n\n const ledgerPath = join(sectionDir, 'contradictions.jsonl');\n const mdPath = join(sectionDir, 'contradictions.md');\n\n const existingContradictions = await readExistingContradictions(\n packPath,\n options.sectionId,\n );\n const existingIds = new Set(existingContradictions.map((c) => c.contradiction_id));\n\n if (candidateClaims.length < 2) {\n summary.detectionMethod = 'no_pairs';\n const md = renderMarkdownView({\n sectionId: options.sectionId,\n candidateClaims: candidateClaims.length,\n contradictions: existingContradictions,\n detector: detector.name,\n detectionMethod: 'no_pairs',\n });\n await writeFile(mdPath, md, 'utf8');\n return summary;\n }\n\n const detectionResult = await detector.detect(candidateClaims);\n if (!detectionResult.ok) {\n summary.detectorError = detectionResult.error;\n summary.detectionMethod = 'failed';\n const md = renderMarkdownView({\n sectionId: options.sectionId,\n candidateClaims: candidateClaims.length,\n contradictions: existingContradictions,\n detector: detector.name,\n detectionMethod: 'failed',\n });\n await writeFile(mdPath, md, 'utf8');\n return summary;\n }\n\n summary.detectionMethod = detectionResult.method;\n summary.pairsCompared = (candidateClaims.length * (candidateClaims.length - 1)) / 2;\n\n for (const paired of detectionResult.drafts) {\n const c = buildContradiction({\n paired,\n sectionId: options.sectionId,\n detector: detector.name,\n detectionMethod: detectionResult.method,\n });\n if (existingIds.has(c.contradiction_id)) {\n summary.contradictionsDeduped += 1;\n continue;\n }\n await appendFile(ledgerPath, JSON.stringify(c) + '\\n', 'utf8');\n existingIds.add(c.contradiction_id);\n existingContradictions.push(c);\n summary.contradictionsAdded += 1;\n summary.contradictionIds.push(c.contradiction_id);\n }\n\n const md = renderMarkdownView({\n sectionId: options.sectionId,\n candidateClaims: candidateClaims.length,\n contradictions: existingContradictions,\n detector: detector.name,\n detectionMethod: detectionResult.method,\n });\n await writeFile(mdPath, md, 'utf8');\n\n return summary;\n}\n","import { z } from 'zod';\n\nexport const ResolutionStatusSchema = z.enum([\n 'unresolved',\n 'resolved',\n 'preserved',\n 'rejected',\n]);\n\nexport const ContradictionResolutionSchema = z.object({\n contradiction_id: z.string().min(1),\n status: ResolutionStatusSchema,\n reason: z.string().min(4),\n resolved_at: z.string().min(1),\n resolved_by: z.string().min(1),\n});\n\nexport type ContradictionResolution = z.infer<typeof ContradictionResolutionSchema>;\nexport type ResolutionStatus = z.infer<typeof ResolutionStatusSchema>;\n","import { appendFile, readFile } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\n\nimport { SectionNotFoundError } from '../errors.js';\nimport {\n ContradictionResolutionSchema,\n type ContradictionResolution,\n type ResolutionStatus,\n} from './resolution-schema.js';\n\nexport interface ResolveOptions {\n sectionId: string;\n packPath: string;\n /** Specific contradiction IDs to resolve. Mutually exclusive with `all`. */\n contradictionIds?: string[];\n /** Resolve all currently-unresolved contradictions in the section. */\n all?: boolean;\n /** Target status — cannot be 'unresolved' (use the candidates file for that default). */\n status: Exclude<ResolutionStatus, 'unresolved'>;\n reason: string;\n resolvedBy?: string;\n}\n\nexport interface ResolveResult {\n sectionId: string;\n applied: number;\n skipped: number;\n ledgerPath: string;\n}\n\nfunction latestEffectiveStatuses(ledgerPath: string, text: string): Map<string, string> {\n const entries: Array<{ contradiction_id: string; status: string; resolved_at: string }> = [];\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n const obj = JSON.parse(line) as Record<string, unknown>;\n if (\n typeof obj['contradiction_id'] === 'string' &&\n typeof obj['status'] === 'string' &&\n typeof obj['resolved_at'] === 'string'\n ) {\n entries.push({\n contradiction_id: obj['contradiction_id'],\n status: obj['status'],\n resolved_at: obj['resolved_at'],\n });\n }\n } catch {\n // skip malformed\n }\n }\n entries.sort((a, b) => a.resolved_at.localeCompare(b.resolved_at));\n const map = new Map<string, string>();\n for (const e of entries) map.set(e.contradiction_id, e.status);\n return map;\n}\n\nexport async function resolve(options: ResolveOptions): Promise<ResolveResult> {\n const { sectionId, packPath, contradictionIds, all, status, reason, resolvedBy = 'operator' } = options;\n\n if (reason.length < 4) {\n throw new Error('reason must be at least 4 characters');\n }\n\n const sectionDir = join(packPath, 'sections', sectionId);\n if (!existsSync(sectionDir)) {\n throw new SectionNotFoundError(sectionId);\n }\n\n const candidatesPath = join(sectionDir, 'contradictions.jsonl');\n const ledgerPath = join(sectionDir, 'contradiction-resolutions.jsonl');\n\n // Load known contradiction IDs and their candidate statuses\n const candidates: Array<{ contradiction_id: string; status: string }> = [];\n if (existsSync(candidatesPath)) {\n const text = await readFile(candidatesPath, 'utf8');\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n const obj = JSON.parse(line) as Record<string, unknown>;\n if (typeof obj['contradiction_id'] === 'string') {\n candidates.push({\n contradiction_id: obj['contradiction_id'],\n status: typeof obj['status'] === 'string' ? obj['status'] : 'unresolved',\n });\n }\n } catch {\n // skip malformed\n }\n }\n }\n\n // Load current effective statuses from ledger (latest-wins)\n const existingResolutions = existsSync(ledgerPath)\n ? latestEffectiveStatuses(ledgerPath, await readFile(ledgerPath, 'utf8'))\n : new Map<string, string>();\n\n const knownIds = new Set(candidates.map((c) => c.contradiction_id));\n\n // Determine target IDs\n let targetIds: string[];\n if (all) {\n targetIds = candidates\n .filter((c) => {\n const effective = existingResolutions.get(c.contradiction_id);\n return effective !== undefined ? effective === 'unresolved' : c.status === 'unresolved';\n })\n .map((c) => c.contradiction_id);\n } else {\n targetIds = contradictionIds ?? [];\n }\n\n const resolvedAt = new Date().toISOString();\n let applied = 0;\n let skipped = 0;\n const lines: string[] = [];\n\n for (const cid of targetIds) {\n if (!knownIds.has(cid)) {\n skipped++;\n continue;\n }\n const entry: ContradictionResolution = {\n contradiction_id: cid,\n status,\n reason,\n resolved_at: resolvedAt,\n resolved_by: resolvedBy,\n };\n ContradictionResolutionSchema.parse(entry);\n lines.push(JSON.stringify(entry));\n applied++;\n }\n\n if (lines.length > 0) {\n await appendFile(ledgerPath, lines.join('\\n') + '\\n', 'utf8');\n }\n\n return { sectionId, applied, skipped, ledgerPath };\n}\n","export { map } from './map.js';\nexport { resolve } from './resolve.js';\nexport {\n ContradictionResolutionSchema,\n ResolutionStatusSchema,\n type ContradictionResolution,\n type ResolutionStatus,\n} from './resolution-schema.js';\nexport {\n HeuristicContradictionDetector,\n OllamaInternContradictionDetector,\n defaultContradictionDetectors,\n pickContradictionDetector,\n} from './detectors/index.js';\nexport {\n ContradictionSchema,\n ContradictionTypeSchema,\n SeveritySchema,\n OverlapAssessmentSchema,\n ContradictionStatusSchema,\n ContradictionDetectorSchema,\n ContradictionConfidenceSchema,\n type Contradiction,\n} from './schema.js';\nexport {\n assessScopeOverlap,\n jaccardSimilarity,\n hasNegation,\n tokenize,\n} from './scope.js';\nexport { renderMarkdownView } from './markdown.js';\nexport type {\n ContradictionType,\n Severity,\n ContradictionDetectorName,\n DetectorMode,\n OverlapAssessment,\n ContradictionStatus,\n DraftContradiction,\n PairedDraft,\n DetectionResult,\n ContradictionDetector,\n MapOptions,\n MapSummary,\n} from './types.js';\n","import { z } from 'zod';\n\nexport const FindingCategorySchema = z.enum([\n 'unsupported_claim',\n 'ungrounded_excerpt',\n 'stale_claim',\n 'overgeneralized_claim',\n 'scope_widening',\n 'missing_not_constraint',\n 'source_quality_problem',\n 'source_cluster_monopoly',\n 'unmapped_contradiction',\n 'recommendation_exceeds_evidence',\n 'hidden_synthesis',\n 'definition_drift',\n 'temporal_mismatch',\n // Span-first + paged extraction can yield dense, atomized claim sets that\n // are individually grounded but collectively redundant. The reviewer flags\n // these so synthesis-worthiness — not just structural grounding — decides\n // what reaches synthesis.\n 'claim_overproduction',\n // Per-claim synthesis-worthiness call: this individual claim is grounded\n // and well-formed but does not earn a synthesis slot (low leverage,\n // restating context, definitional boilerplate, etc.). Distinct from\n // claim_overproduction (section/source-level pressure signal): a section\n // can be over-dense without every claim being individually low-value, and\n // a low-value claim can appear in a perfectly-sized section.\n 'valid_but_low_value',\n]);\n\nexport const FindingSeveritySchema = z.enum(['info', 'warn', 'block']);\n\nexport const ReviewerNameSchema = z.enum(['heuristic', 'ollama-intern']);\n\nexport const ReviewDecisionSchema = z.enum([\n 'accepted_for_synthesis',\n 'rejected',\n 'needs_scope_repair',\n 'needs_source_repair',\n 'needs_contradiction_mapping',\n 'needs_human_review',\n]);\n\nexport const ReviewConfidenceSchema = z.enum(['low', 'medium', 'high']);\n\nexport const ReviewFindingSchema = z.object({\n finding_id: z.string().regex(/^fnd_[a-f0-9]{12}$/),\n section_id: z.string().regex(/^[0-9]{2}-[a-z0-9-]+$/),\n claim_ids: z.array(z.string().regex(/^clm_[a-f0-9]{12}_(heuristic|ollama_intern)_\\d+$/)),\n source_ids: z.array(z.string().regex(/^src_[a-f0-9]{12}$/)),\n category: FindingCategorySchema,\n severity: FindingSeveritySchema,\n summary: z.string().min(1),\n evidence: z.string(),\n required_action: z.string(),\n reviewer: ReviewerNameSchema,\n review_method: z.string().min(1),\n confidence: ReviewConfidenceSchema,\n created_at: z.string(),\n});\n\nexport const ClaimReviewSchema = z.object({\n claim_id: z.string().regex(/^clm_[a-f0-9]{12}_(heuristic|ollama_intern)_\\d+$/),\n decision: ReviewDecisionSchema,\n reason: z.string().min(1),\n finding_ids: z.array(z.string()),\n reviewer: ReviewerNameSchema,\n review_method: z.string().min(1),\n created_at: z.string(),\n});\n\nexport const ReviewSnapshotSchema = z.object({\n section_id: z.string().regex(/^[0-9]{2}-[a-z0-9-]+$/),\n reviewer: ReviewerNameSchema,\n review_method: z.string(),\n reviewed_at: z.string(),\n candidate_claims: z.number().int().nonnegative(),\n findings: z.array(ReviewFindingSchema),\n claim_reviews: z.array(ClaimReviewSchema),\n decision_counts: z.record(ReviewDecisionSchema, z.number().int().nonnegative()),\n severity_counts: z.record(FindingSeveritySchema, z.number().int().nonnegative()),\n llm_findings_rejected_ungrounded: z.number().int().nonnegative(),\n promoted_to_reviewed: z.boolean(),\n});\n\nexport type ReviewFinding = z.infer<typeof ReviewFindingSchema>;\nexport type ClaimReview = z.infer<typeof ClaimReviewSchema>;\nexport type ReviewSnapshot = z.infer<typeof ReviewSnapshotSchema>;\n","import type { GateCheckResult, GateInput } from '../types.js';\n\nexport function checkSourceFloor(input: GateInput): GateCheckResult[] {\n const cfg = input.research.gates.source_floor;\n const results: GateCheckResult[] = [];\n const cards = input.sources;\n\n // min_sources\n const sourceCount = cards.length;\n if (sourceCount < cfg.min_sources) {\n results.push({\n family: 'source_floor',\n check: 'min_sources',\n status: 'fail',\n detail: `Found ${sourceCount} source card(s); minimum ${cfg.min_sources} required.`,\n evidence: cards.map((c) => c.source_id),\n blocks_synthesis: true,\n });\n } else {\n results.push({\n family: 'source_floor',\n check: 'min_sources',\n status: 'pass',\n detail: `${sourceCount} source card(s) >= minimum ${cfg.min_sources}.`,\n evidence: [],\n blocks_synthesis: false,\n });\n }\n\n // min_independent_publishers\n const publishers = new Set(\n cards.map((c) => c.publisher).filter((p): p is string => typeof p === 'string'),\n );\n if (publishers.size < cfg.min_independent_publishers) {\n results.push({\n family: 'source_floor',\n check: 'min_independent_publishers',\n status: 'fail',\n detail: `Found ${publishers.size} independent publisher(s); minimum ${cfg.min_independent_publishers} required.`,\n evidence: [...publishers],\n blocks_synthesis: true,\n });\n } else {\n results.push({\n family: 'source_floor',\n check: 'min_independent_publishers',\n status: 'pass',\n detail: `${publishers.size} independent publisher(s) >= minimum ${cfg.min_independent_publishers}.`,\n evidence: [],\n blocks_synthesis: false,\n });\n }\n\n // primary_sources_required\n const primaryCount = cards.filter((c) => c.source_type === 'primary').length;\n if (primaryCount < cfg.primary_sources_required) {\n results.push({\n family: 'source_floor',\n check: 'primary_sources_required',\n status: 'fail',\n detail: `Found ${primaryCount} primary source(s); minimum ${cfg.primary_sources_required} required. Pre-waiver.`,\n evidence: cards.filter((c) => c.source_type === 'primary').map((c) => c.source_id),\n blocks_synthesis: true,\n });\n } else {\n results.push({\n family: 'source_floor',\n check: 'primary_sources_required',\n status: 'pass',\n detail: `${primaryCount} primary source(s) >= minimum ${cfg.primary_sources_required}.`,\n evidence: [],\n blocks_synthesis: false,\n });\n }\n\n // failed-fetches visibility (warn-only; not fatal unless source floor fails)\n const failed = input.receipts.filter((r) => r.fetch_outcome !== 'ok').length;\n if (failed > 0) {\n results.push({\n family: 'source_floor',\n check: 'failed_fetches_visible',\n status: 'warn',\n detail: `${failed} fetch attempt(s) recorded as non-ok in fetch-log.jsonl.`,\n evidence: [],\n blocks_synthesis: false,\n });\n } else {\n results.push({\n family: 'source_floor',\n check: 'failed_fetches_visible',\n status: 'pass',\n detail: `No failed fetches in fetch-log.jsonl.`,\n evidence: [],\n blocks_synthesis: false,\n });\n }\n\n return results;\n}\n","import type { GateCheckResult, GateInput } from '../types.js';\n\nexport function checkClaimIntegrity(input: GateInput): GateCheckResult[] {\n const cfg = input.research.gates.claim_integrity;\n const results: GateCheckResult[] = [];\n const claims = input.candidateClaims;\n const cardIds = new Set(input.sources.map((c) => c.source_id));\n const okReceiptSourceIds = new Set(\n input.receipts.filter((r) => r.fetch_outcome === 'ok').map((r) => r.source_id),\n );\n\n // every_claim_needs_source — schema-enforced, but verify at gate too\n const noSourceIds = claims.filter((c) => c.source_ids.length === 0);\n if (noSourceIds.length > 0) {\n results.push({\n family: 'claim_integrity',\n check: 'every_claim_needs_source',\n status: 'fail',\n detail: `${noSourceIds.length} claim(s) lack source_ids.`,\n evidence: noSourceIds.map((c) => c.claim_id),\n blocks_synthesis: cfg.every_claim_needs_source,\n });\n } else {\n results.push({\n family: 'claim_integrity',\n check: 'every_claim_needs_source',\n status: 'pass',\n detail: `All ${claims.length} candidate claim(s) reference at least one source_id.`,\n evidence: [],\n blocks_synthesis: false,\n });\n }\n\n // no_orphan_claims — claim's source_ids must exist in source-cards\n const orphans = claims.filter((c) => c.source_ids.some((sid) => !cardIds.has(sid)));\n if (orphans.length > 0) {\n results.push({\n family: 'claim_integrity',\n check: 'no_orphan_claims',\n status: 'fail',\n detail: `${orphans.length} claim(s) cite source_id(s) not present in evidence/source-cards/.`,\n evidence: orphans.map((c) => c.claim_id),\n blocks_synthesis: cfg.no_orphan_claims,\n });\n } else {\n results.push({\n family: 'claim_integrity',\n check: 'no_orphan_claims',\n status: 'pass',\n detail: `All claim source_ids resolve to source cards.`,\n evidence: [],\n blocks_synthesis: false,\n });\n }\n\n // source_hashes present\n const noHash = claims.filter((c) => c.source_hashes.length === 0);\n if (noHash.length > 0) {\n results.push({\n family: 'claim_integrity',\n check: 'source_hashes_present',\n status: 'fail',\n detail: `${noHash.length} claim(s) have empty source_hashes — tamper detection cannot anchor to a fetch receipt.`,\n evidence: noHash.map((c) => c.claim_id),\n blocks_synthesis: true,\n });\n } else {\n results.push({\n family: 'claim_integrity',\n check: 'source_hashes_present',\n status: 'pass',\n detail: `All candidate claims carry source_hashes.`,\n evidence: [],\n blocks_synthesis: false,\n });\n }\n\n // evidence_excerpt grounded — schema requires non-empty; here we re-verify\n const noEvidence = claims.filter((c) => c.evidence_excerpt.trim().length === 0);\n if (noEvidence.length > 0) {\n results.push({\n family: 'claim_integrity',\n check: 'evidence_excerpt_present',\n status: 'fail',\n detail: `${noEvidence.length} claim(s) have empty evidence_excerpt.`,\n evidence: noEvidence.map((c) => c.claim_id),\n blocks_synthesis: true,\n });\n } else {\n results.push({\n family: 'claim_integrity',\n check: 'evidence_excerpt_present',\n status: 'pass',\n detail: `All candidate claims carry an evidence_excerpt.`,\n evidence: [],\n blocks_synthesis: false,\n });\n }\n\n // claims must reference a source with a successful fetch receipt\n const missingReceipt = claims.filter((c) => !c.source_ids.some((sid) => okReceiptSourceIds.has(sid)));\n if (missingReceipt.length > 0) {\n results.push({\n family: 'claim_integrity',\n check: 'fetch_receipt_anchored',\n status: 'fail',\n detail: `${missingReceipt.length} claim(s) cite source_id(s) without a successful fetch receipt.`,\n evidence: missingReceipt.map((c) => c.claim_id),\n blocks_synthesis: true,\n });\n } else {\n results.push({\n family: 'claim_integrity',\n check: 'fetch_receipt_anchored',\n status: 'pass',\n detail: `All candidate claims trace to at least one successful fetch receipt.`,\n evidence: [],\n blocks_synthesis: false,\n });\n }\n\n // no_source_cluster_monopoly — claim-level: a claim whose every source traces to one publisher\n if (cfg.no_source_cluster_monopoly && claims.length > 0) {\n const monoClaims: string[] = [];\n for (const claim of claims) {\n const pubs = new Set<string>();\n for (const sid of claim.source_ids) {\n const card = input.sources.find((c) => c.source_id === sid);\n if (card?.publisher) pubs.add(card.publisher);\n }\n if (claim.source_ids.length > 0 && pubs.size <= 1) {\n monoClaims.push(claim.claim_id);\n }\n }\n if (monoClaims.length > claims.length / 2) {\n results.push({\n family: 'claim_integrity',\n check: 'no_source_cluster_monopoly',\n status: 'warn',\n detail: `${monoClaims.length}/${claims.length} claim(s) source from a single publisher. Independent corroboration recommended before synthesis.`,\n evidence: monoClaims,\n blocks_synthesis: false,\n });\n } else {\n results.push({\n family: 'claim_integrity',\n check: 'no_source_cluster_monopoly',\n status: 'pass',\n detail: `${monoClaims.length}/${claims.length} claim(s) source from a single publisher (within tolerance).`,\n evidence: [],\n blocks_synthesis: false,\n });\n }\n }\n\n return results;\n}\n","import type { GateCheckResult, GateInput } from '../types.js';\nimport type { ContradictionResolution } from '../../contradictions/resolution-schema.js';\n\nfunction buildEffectiveStatuses(resolutions: ContradictionResolution[] | undefined): Map<string, string> {\n const map = new Map<string, string>();\n if (!resolutions || resolutions.length === 0) return map;\n const sorted = [...resolutions].sort((a, b) => a.resolved_at.localeCompare(b.resolved_at));\n for (const r of sorted) map.set(r.contradiction_id, r.status);\n return map;\n}\n\nexport function checkScopeIntegrity(input: GateInput): GateCheckResult[] {\n const results: GateCheckResult[] = [];\n const claims = input.candidateClaims;\n\n const universal = claims.filter((c) => c.scope === null);\n const scoped = claims.filter((c) => c.scope !== null);\n const withNot = claims.filter((c) => c.not !== null);\n\n // universal claim warning — claims with scope=null cannot be treated as broad\n if (universal.length > 0) {\n results.push({\n family: 'scope_integrity',\n check: 'no_untagged_universal_claims',\n status: 'warn',\n detail: `${universal.length}/${claims.length} candidate claim(s) have scope=null. These must not be treated as broad-applicability claims downstream — they are scope-undetermined, not scope-universal. Run a richer extractor or add scope manually before synthesis.`,\n evidence: universal.map((c) => c.claim_id),\n blocks_synthesis: false,\n });\n } else if (claims.length > 0) {\n results.push({\n family: 'scope_integrity',\n check: 'no_untagged_universal_claims',\n status: 'pass',\n detail: `Every candidate claim has a non-null scope.`,\n evidence: [],\n blocks_synthesis: false,\n });\n }\n\n // not-constraint preservation — informational warn\n if (claims.length > 0) {\n const ratio = withNot.length / claims.length;\n if (ratio < 0.3) {\n results.push({\n family: 'scope_integrity',\n check: 'not_constraint_present',\n status: 'warn',\n detail: `Only ${withNot.length}/${claims.length} candidate claim(s) carry a 'not' constraint. The 'not' field is the structural defense against overgeneralization; sparse coverage means downstream synthesis must be more cautious.`,\n evidence: claims.filter((c) => c.not === null).map((c) => c.claim_id),\n blocks_synthesis: false,\n });\n } else {\n results.push({\n family: 'scope_integrity',\n check: 'not_constraint_present',\n status: 'pass',\n detail: `${withNot.length}/${claims.length} candidate claim(s) carry a 'not' constraint.`,\n evidence: [],\n blocks_synthesis: false,\n });\n }\n }\n\n // overgeneralization risks from contradictions ledger\n const effectiveStatuses = buildEffectiveStatuses(input.resolutions);\n const overgen = input.contradictions.filter((c) => {\n if (c.type !== 'overgeneralization_risk') return false;\n const eff = effectiveStatuses.get(c.contradiction_id);\n return eff !== undefined ? eff === 'unresolved' : c.status === 'unresolved';\n });\n const overgenBlocking = overgen.filter(\n (c) => c.severity === 'blocking' || c.severity === 'high',\n );\n const overgenWarn = overgen.filter(\n (c) => c.severity === 'medium' || c.severity === 'low',\n );\n\n if (overgenBlocking.length > 0) {\n results.push({\n family: 'scope_integrity',\n check: 'no_blocking_overgeneralization',\n status: 'fail',\n detail: `${overgenBlocking.length} unresolved overgeneralization_risk contradiction(s) at high or blocking severity. Contextual claims appear to be promoted into universal rules without scope-widening evidence.`,\n evidence: overgenBlocking.map((c) => c.contradiction_id),\n blocks_synthesis: true,\n });\n } else {\n results.push({\n family: 'scope_integrity',\n check: 'no_blocking_overgeneralization',\n status: 'pass',\n detail: `No high- or blocking-severity overgeneralization_risk contradictions.`,\n evidence: [],\n blocks_synthesis: false,\n });\n }\n\n if (overgenWarn.length > 0) {\n results.push({\n family: 'scope_integrity',\n check: 'low_severity_overgeneralization',\n status: 'warn',\n detail: `${overgenWarn.length} low/medium-severity overgeneralization_risk contradiction(s) recorded. Adversarial review should classify these before synthesis.`,\n evidence: overgenWarn.map((c) => c.contradiction_id),\n blocks_synthesis: false,\n });\n }\n\n // Scope-widening evidence requirement is checked per claim during contradiction mapping;\n // here we surface the universal-vs-scoped ratio as a synthesis-readiness signal.\n if (claims.length > 0) {\n results.push({\n family: 'scope_integrity',\n check: 'scope_tagging_summary',\n status: 'pass',\n detail: `${scoped.length} scoped, ${universal.length} universal/untagged, ${withNot.length} with 'not' constraint.`,\n evidence: [],\n blocks_synthesis: false,\n });\n }\n\n return results;\n}\n","import type { GateCheckResult, GateInput } from '../types.js';\n\nfunction monthsAgo(iso: string): number | null {\n const d = Date.parse(iso);\n if (Number.isNaN(d)) return null;\n return (Date.now() - d) / (1000 * 60 * 60 * 24 * 30.44);\n}\n\nexport function checkFreshness(input: GateInput): GateCheckResult[] {\n const cfg = input.research.gates.freshness;\n const policy = input.research.freshness;\n const results: GateCheckResult[] = [];\n const cards = input.sources;\n\n if (!policy.required && !cfg.required_for_current_topics) {\n results.push({\n family: 'freshness',\n check: 'policy_applicability',\n status: 'pass',\n detail: `Freshness policy not required for this pack.`,\n evidence: [],\n blocks_synthesis: false,\n });\n return results;\n }\n\n if (cards.length === 0) {\n results.push({\n family: 'freshness',\n check: 'policy_applicability',\n status: 'warn',\n detail: `Freshness policy required but no sources to evaluate.`,\n evidence: [],\n blocks_synthesis: false,\n });\n return results;\n }\n\n const maxAge = policy.max_source_age_months;\n const stale: string[] = [];\n const unknownDate: string[] = [];\n\n for (const card of cards) {\n if (!card.published_at) {\n unknownDate.push(card.source_id);\n continue;\n }\n if (maxAge === null) continue;\n const age = monthsAgo(card.published_at);\n if (age === null) {\n unknownDate.push(card.source_id);\n continue;\n }\n if (age > maxAge) stale.push(card.source_id);\n }\n\n if (stale.length > 0) {\n if (cfg.stale_source_policy === 'fail') {\n results.push({\n family: 'freshness',\n check: 'no_stale_sources',\n status: 'fail',\n detail: `${stale.length} source(s) older than ${maxAge ?? 'unset'} months. Pack policy: fail.`,\n evidence: stale,\n blocks_synthesis: true,\n });\n } else {\n results.push({\n family: 'freshness',\n check: 'no_stale_sources',\n status: 'warn',\n detail: `${stale.length} source(s) older than ${maxAge ?? 'unset'} months. Pack policy: warn.`,\n evidence: stale,\n blocks_synthesis: false,\n });\n }\n } else {\n results.push({\n family: 'freshness',\n check: 'no_stale_sources',\n status: 'pass',\n detail: maxAge === null\n ? `No max_source_age_months configured; per-source recency not evaluated.`\n : `No source older than ${maxAge} months.`,\n evidence: [],\n blocks_synthesis: false,\n });\n }\n\n if (unknownDate.length > 0) {\n results.push({\n family: 'freshness',\n check: 'publication_date_known',\n status: 'warn',\n detail: `${unknownDate.length} source(s) have no parseable published_at. Recency cannot be evaluated for these.`,\n evidence: unknownDate,\n blocks_synthesis: false,\n });\n } else {\n results.push({\n family: 'freshness',\n check: 'publication_date_known',\n status: 'pass',\n detail: `All sources have a recorded published_at date.`,\n evidence: [],\n blocks_synthesis: false,\n });\n }\n\n return results;\n}\n","import type { GateCheckResult, GateInput } from '../types.js';\nimport type { ContradictionResolution } from '../../contradictions/resolution-schema.js';\n\nfunction buildEffectiveStatuses(resolutions: ContradictionResolution[] | undefined): Map<string, string> {\n const map = new Map<string, string>();\n if (!resolutions || resolutions.length === 0) return map;\n const sorted = [...resolutions].sort((a, b) => a.resolved_at.localeCompare(b.resolved_at));\n for (const r of sorted) map.set(r.contradiction_id, r.status);\n return map;\n}\n\nexport function checkContradiction(input: GateInput): GateCheckResult[] {\n const cfg = input.research.gates.contradiction;\n const results: GateCheckResult[] = [];\n const all = input.contradictions;\n const effectiveStatuses = buildEffectiveStatuses(input.resolutions);\n const unresolved = all.filter((c) => {\n const eff = effectiveStatuses.get(c.contradiction_id);\n return eff !== undefined ? eff === 'unresolved' : c.status === 'unresolved';\n });\n const blocking = unresolved.filter(\n (c) => c.severity === 'blocking' || c.severity === 'high',\n );\n\n // unresolved contradictions visibility\n if (unresolved.length > 0) {\n results.push({\n family: 'contradiction',\n check: 'unresolved_visible',\n status: 'warn',\n detail: `${unresolved.length} unresolved contradiction(s) recorded. The contradiction ledger is the audit substrate; the gate engine does not resolve, only surfaces.`,\n evidence: unresolved.map((c) => c.contradiction_id),\n blocks_synthesis: false,\n });\n } else {\n results.push({\n family: 'contradiction',\n check: 'unresolved_visible',\n status: 'pass',\n detail: all.length === 0\n ? `No contradictions recorded. A clean ledger is not proof of completeness — it means the detector found nothing.`\n : `All ${all.length} contradiction(s) recorded are resolved.`,\n evidence: [],\n blocks_synthesis: false,\n });\n }\n\n // blocking contradictions actually block synthesis\n if (cfg.unresolved_contradictions_block_synthesis && blocking.length > 0) {\n results.push({\n family: 'contradiction',\n check: 'unresolved_contradictions_block_synthesis',\n status: 'fail',\n detail: `${blocking.length} unresolved contradiction(s) at high or blocking severity. Synthesis is not eligible until these are reconciled, preserved deliberately, or rejected.`,\n evidence: blocking.map((c) => c.contradiction_id),\n blocks_synthesis: true,\n });\n } else {\n results.push({\n family: 'contradiction',\n check: 'unresolved_contradictions_block_synthesis',\n status: 'pass',\n detail: cfg.unresolved_contradictions_block_synthesis\n ? `No high- or blocking-severity unresolved contradictions.`\n : `Pack policy does not block synthesis on unresolved contradictions; ${blocking.length} high/blocking still recorded for visibility.`,\n evidence: [],\n blocks_synthesis: false,\n });\n }\n\n // contradiction-required check — only if pack policy says so\n if (cfg.required && all.length === 0) {\n results.push({\n family: 'contradiction',\n check: 'contradiction_required_by_policy',\n status: 'warn',\n detail: `Pack policy requires contradiction coverage but no contradictions are recorded. A clean ledger may indicate a thin-source-set rather than genuine consensus. Adversarial review should re-examine.`,\n evidence: [],\n blocks_synthesis: false,\n });\n } else if (cfg.required) {\n results.push({\n family: 'contradiction',\n check: 'contradiction_required_by_policy',\n status: 'pass',\n detail: `Contradiction ledger has ${all.length} entry(ies); policy satisfied.`,\n evidence: [],\n blocks_synthesis: false,\n });\n }\n\n return results;\n}\n","import type { GateCheckResult, GateInput } from '../types.js';\n\nexport function checkSectionBudget(input: GateInput): GateCheckResult[] {\n const cfg = input.research.gates.section_budget;\n const section = input.section;\n const results: GateCheckResult[] = [];\n\n if (!section.max_time_minutes || section.max_time_minutes <= 0) {\n results.push({\n family: 'section_budget',\n check: 'budget_configured',\n status: 'warn',\n detail: `Section has no max_time_minutes configured.`,\n evidence: [section.id],\n blocks_synthesis: false,\n });\n } else {\n results.push({\n family: 'section_budget',\n check: 'budget_configured',\n status: 'pass',\n detail: `Section budget: ${section.max_time_minutes} minute(s). Pack default: ${cfg.max_time_minutes}.`,\n evidence: [],\n blocks_synthesis: false,\n });\n }\n\n results.push({\n family: 'section_budget',\n check: 'runtime_tracking',\n status: 'warn',\n detail: `Runtime tracking not yet implemented in v0.1; configured budget is recorded for future enforcement only. Extension policy (extension_requires_evidence=${cfg.extension_requires_evidence}) is documented but not enforced until actual run timestamps are tracked.`,\n evidence: [],\n blocks_synthesis: false,\n });\n\n return results;\n}\n","import type { SectionScopedWaiver } from '../../intake/schema.js';\nimport type {\n GateCheckResult,\n GateInput,\n WaiverApplication,\n} from '../types.js';\n\nexport interface WaiverPassResult {\n updatedResults: GateCheckResult[];\n waivers_applied: WaiverApplication[];\n waiver_validation_failures: GateCheckResult[];\n}\n\nexport function applyWaivers(\n input: GateInput,\n results: GateCheckResult[],\n): WaiverPassResult {\n const waiver = input.research.primary_source_waiver;\n const cfg = input.research.gates.source_floor;\n const updated = results.map((r) => ({ ...r }));\n const applied: WaiverApplication[] = [];\n const validationFailures: GateCheckResult[] = [];\n\n // Pack-level waiver — existing behavior, unchanged from v0.3.0.\n applyPackLevelWaiver({\n waiver,\n cfg,\n updated,\n applied,\n validationFailures,\n });\n\n // Section-scoped waivers (v0.3.1+). Each entry is independent: matched by\n // (section_id, scope) and validated for reason + compensating_controls\n // before any source_floor failure is converted. Pack policy\n // primary_source_waiver_allowed: false blocks ALL waivers (pack-level and\n // section-scoped) so an operator cannot smuggle a waiver past pack policy\n // by rerouting it to section scope.\n for (const sw of waiver.section_waivers ?? []) {\n if (sw.section_id !== input.section.id) continue;\n applySectionScopedWaiver({\n waiver: sw,\n cfg,\n updated,\n applied,\n validationFailures,\n });\n }\n\n return { updatedResults: updated, waivers_applied: applied, waiver_validation_failures: validationFailures };\n}\n\nfunction applyPackLevelWaiver(args: {\n waiver: GateInput['research']['primary_source_waiver'];\n cfg: GateInput['research']['gates']['source_floor'];\n updated: GateCheckResult[];\n applied: WaiverApplication[];\n validationFailures: GateCheckResult[];\n}): void {\n const { waiver, cfg, updated, applied, validationFailures } = args;\n\n if (waiver.status !== 'granted') return;\n\n if (!waiver.reason || waiver.reason.trim().length === 0) {\n validationFailures.push({\n family: 'waivers',\n check: 'primary_source_waiver_reason_required',\n status: 'fail',\n detail: `primary_source_waiver.status is \"granted\" but reason is empty. Waiver is invalid; original failures stand.`,\n evidence: [],\n blocks_synthesis: true,\n });\n return;\n }\n\n if (waiver.compensating_controls.length === 0) {\n validationFailures.push({\n family: 'waivers',\n check: 'primary_source_waiver_compensating_controls_required',\n status: 'fail',\n detail: `primary_source_waiver.status is \"granted\" but compensating_controls is empty. Waiver is invalid; original failures stand.`,\n evidence: [],\n blocks_synthesis: true,\n });\n return;\n }\n\n if (!cfg.primary_source_waiver_allowed) {\n validationFailures.push({\n family: 'waivers',\n check: 'primary_source_waiver_allowed_by_pack',\n status: 'fail',\n detail: `Pack policy gates.source_floor.primary_source_waiver_allowed=false; granted waiver cannot be applied.`,\n evidence: [],\n blocks_synthesis: true,\n });\n return;\n }\n\n // Convert primary_sources_required fail → pass_with_waiver\n for (let i = 0; i < updated.length; i += 1) {\n const r = updated[i]!;\n if (\n r.family === 'source_floor' &&\n r.check === 'primary_sources_required' &&\n r.status === 'fail'\n ) {\n const original = r.status;\n updated[i] = {\n ...r,\n status: 'pass_with_waiver',\n detail: `${r.detail} Waiver granted with ${waiver.compensating_controls.length} compensating control(s); converted from fail to pass_with_waiver.`,\n blocks_synthesis: false,\n };\n applied.push({\n family: 'source_floor',\n check: 'primary_sources_required',\n reason: waiver.reason,\n compensating_controls: waiver.compensating_controls,\n original_status: original,\n new_status: 'pass_with_waiver',\n });\n }\n }\n}\n\nfunction applySectionScopedWaiver(args: {\n waiver: SectionScopedWaiver;\n cfg: GateInput['research']['gates']['source_floor'];\n updated: GateCheckResult[];\n applied: WaiverApplication[];\n validationFailures: GateCheckResult[];\n}): void {\n const { waiver, cfg, updated, applied, validationFailures } = args;\n\n // Schema enforces reason.min(1) and compensating_controls.min(1), but a\n // hand-edited yaml can still parse with whitespace-only reason; check\n // explicitly so the validation surface is consistent with pack-level.\n if (!waiver.reason || waiver.reason.trim().length === 0) {\n validationFailures.push({\n family: 'waivers',\n check: 'section_scoped_waiver_reason_required',\n status: 'fail',\n detail: `Section-scoped waiver for ${waiver.section_id}/${waiver.scope} is missing a reason. Waiver is invalid; original failure stands.`,\n evidence: [waiver.section_id],\n blocks_synthesis: true,\n });\n return;\n }\n\n if (waiver.compensating_controls.length === 0) {\n validationFailures.push({\n family: 'waivers',\n check: 'section_scoped_waiver_compensating_controls_required',\n status: 'fail',\n detail: `Section-scoped waiver for ${waiver.section_id}/${waiver.scope} has empty compensating_controls. Waiver is invalid; original failure stands.`,\n evidence: [waiver.section_id],\n blocks_synthesis: true,\n });\n return;\n }\n\n if (!cfg.primary_source_waiver_allowed) {\n validationFailures.push({\n family: 'waivers',\n check: 'section_scoped_waiver_allowed_by_pack',\n status: 'fail',\n detail: `Pack policy gates.source_floor.primary_source_waiver_allowed=false; section-scoped waiver for ${waiver.section_id}/${waiver.scope} cannot be applied.`,\n evidence: [waiver.section_id],\n blocks_synthesis: true,\n });\n return;\n }\n\n // Convert matching source_floor.<scope> fail → pass_with_waiver\n for (let i = 0; i < updated.length; i += 1) {\n const r = updated[i]!;\n if (\n r.family === 'source_floor' &&\n r.check === waiver.scope &&\n r.status === 'fail'\n ) {\n const original = r.status;\n updated[i] = {\n ...r,\n status: 'pass_with_waiver',\n detail: `${r.detail} Section-scoped waiver granted for ${waiver.section_id} with ${waiver.compensating_controls.length} compensating control(s); converted from fail to pass_with_waiver.`,\n blocks_synthesis: false,\n };\n applied.push({\n family: 'source_floor',\n check: waiver.scope,\n reason: waiver.reason,\n compensating_controls: waiver.compensating_controls,\n original_status: original,\n new_status: 'pass_with_waiver',\n });\n }\n }\n}\n","import type { GateCheckResult, GateInput } from '../types.js';\nimport type { ClaimReview } from '../../review/schema.js';\n\nconst MIN_ACCEPTED_CLAIMS = 3;\nconst MIN_ACCEPTED_SOURCES = 2;\n\nexport function checkAcceptedClaimFloor(input: GateInput): GateCheckResult[] {\n const reviews = input.claimReviews;\n\n // Status-wins-by-latest: for each claim_id, the latest review entry wins.\n const latestByClaimId = new Map<string, ClaimReview>();\n for (const r of reviews) {\n const existing = latestByClaimId.get(r.claim_id);\n if (!existing || r.created_at > existing.created_at) {\n latestByClaimId.set(r.claim_id, r);\n }\n }\n\n const acceptedIds = [...latestByClaimId.values()]\n .filter((r) => r.decision === 'accepted_for_synthesis')\n .map((r) => r.claim_id);\n\n const acceptedCount = acceptedIds.length;\n\n // Map claim_id → source_ids from all claims in the section.\n const claimSourceMap = new Map<string, string[]>();\n for (const claim of input.claims) {\n claimSourceMap.set(claim.claim_id, claim.source_ids);\n }\n\n const distinctSources = new Set<string>();\n for (const cid of acceptedIds) {\n for (const sid of claimSourceMap.get(cid) ?? []) {\n distinctSources.add(sid);\n }\n }\n const distinctSourceCount = distinctSources.size;\n\n const belowClaimFloor = acceptedCount < MIN_ACCEPTED_CLAIMS;\n const belowSourceFloor = distinctSourceCount < MIN_ACCEPTED_SOURCES;\n\n if (belowClaimFloor || belowSourceFloor) {\n return [\n {\n family: 'accepted_claim_floor',\n check: 'min_accepted_claims_and_sources',\n status: 'fail',\n detail: `accepted-claim floor violated: ${acceptedCount} accepted claims from ${distinctSourceCount} sources (minimum: ${MIN_ACCEPTED_CLAIMS} claims from ${MIN_ACCEPTED_SOURCES} sources). Waivers cannot bypass evidence existence.`,\n evidence: acceptedIds,\n blocks_synthesis: true,\n },\n ];\n }\n\n return [\n {\n family: 'accepted_claim_floor',\n check: 'min_accepted_claims_and_sources',\n status: 'pass',\n detail: `${acceptedCount} accepted claims from ${distinctSourceCount} distinct sources (minimum: ${MIN_ACCEPTED_CLAIMS} from ${MIN_ACCEPTED_SOURCES}).`,\n evidence: [],\n blocks_synthesis: false,\n },\n ];\n}\n","export { checkSourceFloor } from './source-floor.js';\nexport { checkClaimIntegrity } from './claim-integrity.js';\nexport { checkScopeIntegrity } from './scope-integrity.js';\nexport { checkFreshness } from './freshness.js';\nexport { checkContradiction } from './contradiction.js';\nexport { checkSectionBudget } from './section-budget.js';\nexport { applyWaivers } from './waivers.js';\nexport { checkAcceptedClaimFloor } from './accepted-claim-floor.js';\n","import type { SectionGateResult } from './types.js';\n\nconst STATUS_GLYPH: Record<string, string> = {\n pass: '[PASS]',\n warn: '[WARN]',\n fail: '[FAIL]',\n pass_with_waiver: '[PASS+WAIVER]',\n warn_with_waiver: '[WARN+WAIVER]',\n};\n\nexport function renderGateMarkdown(result: SectionGateResult): string {\n const lines: string[] = [];\n lines.push(`# Gate Result: ${result.section_id}`);\n lines.push('');\n lines.push(`**Verdict:** ${result.verdict.toUpperCase()}`);\n lines.push(`**Synthesis eligible:** ${result.synthesis_eligible ? 'yes' : 'no'}`);\n lines.push(`**Checked at:** ${result.checked_at}`);\n lines.push('');\n lines.push(`> ${result.summary}`);\n lines.push('');\n\n if (result.blocking_reasons.length > 0) {\n lines.push('## Blocking reasons');\n lines.push('');\n for (const r of result.blocking_reasons) {\n lines.push(`- ${r}`);\n }\n lines.push('');\n }\n\n lines.push('## Counts');\n lines.push('');\n lines.push(`- Claims: ${result.claim_counts.total} total, ${result.claim_counts.candidate} candidate, ${result.claim_counts.with_evidence_excerpt} with evidence excerpt, ${result.claim_counts.orphans} orphan`);\n lines.push(`- Sources: ${result.source_counts.total} total (${result.source_counts.primary} primary / ${result.source_counts.secondary} secondary / ${result.source_counts.docs} docs / ${result.source_counts.forum} forum / ${result.source_counts.benchmark} benchmark / ${result.source_counts.unknown} unknown), ${result.source_counts.independent_publishers} independent publishers, ${result.source_counts.failed_fetches} failed fetches`);\n lines.push(`- Contradictions: ${result.contradiction_counts.total} total (${result.contradiction_counts.unresolved} unresolved, ${result.contradiction_counts.blocking} high/blocking)`);\n lines.push(`- Scope integrity: ${result.scope_integrity_summary.scoped_claims} scoped, ${result.scope_integrity_summary.universal_claims} universal/untagged, ${result.scope_integrity_summary.with_not_constraint} with 'not' constraint, ${result.scope_integrity_summary.overgen_risks_total} overgeneralization risk(s) (${result.scope_integrity_summary.overgen_risks_blocking} blocking)`);\n lines.push(`- Freshness: policy ${result.freshness_summary.policy_required ? 'required' : 'not required'}, ${result.freshness_summary.stale_count} stale, ${result.freshness_summary.unknown_date_count} unknown date`);\n lines.push('');\n\n if (result.waivers_applied.length > 0) {\n lines.push('## Waivers applied');\n lines.push('');\n for (const w of result.waivers_applied) {\n lines.push(`### ${w.family}.${w.check}`);\n lines.push('');\n lines.push(`- **Original status:** ${w.original_status}`);\n lines.push(`- **New status:** ${w.new_status}`);\n lines.push(`- **Reason:** ${w.reason}`);\n lines.push(`- **Compensating controls:**`);\n for (const c of w.compensating_controls) {\n lines.push(` - ${c}`);\n }\n lines.push('');\n }\n }\n\n lines.push('## Gate results');\n lines.push('');\n for (const r of result.gate_results) {\n const glyph = STATUS_GLYPH[r.status] ?? `[${r.status.toUpperCase()}]`;\n lines.push(`### ${glyph} ${r.family}.${r.check}`);\n lines.push('');\n lines.push(`${r.detail}`);\n lines.push('');\n lines.push(`*Blocks synthesis:* ${r.blocks_synthesis}`);\n if (r.evidence.length > 0) {\n lines.push('');\n lines.push(`*Evidence:* ${r.evidence.slice(0, 10).map((e) => `\\`${e}\\``).join(', ')}${r.evidence.length > 10 ? ` (+${r.evidence.length - 10} more)` : ''}`);\n }\n lines.push('');\n }\n\n if (result.next_actions.length > 0) {\n lines.push('## Next actions');\n lines.push('');\n for (const a of result.next_actions) {\n lines.push(`- ${a}`);\n }\n lines.push('');\n }\n\n return lines.join('\\n');\n}\n","import { z } from 'zod';\n\nexport const GateFamilySchema = z.enum([\n 'source_floor',\n 'claim_integrity',\n 'scope_integrity',\n 'freshness',\n 'contradiction',\n 'section_budget',\n 'waivers',\n 'accepted_claim_floor',\n]);\n\nexport const GateCheckStatusSchema = z.enum([\n 'pass',\n 'warn',\n 'fail',\n 'pass_with_waiver',\n 'warn_with_waiver',\n]);\n\nexport const VerdictSchema = z.enum(['pass', 'warn', 'fail', 'blocked']);\n\nexport const GateCheckResultSchema = z.object({\n family: GateFamilySchema,\n check: z.string().min(1),\n status: GateCheckStatusSchema,\n detail: z.string(),\n evidence: z.array(z.string()),\n blocks_synthesis: z.boolean(),\n});\n\nexport const WaiverApplicationSchema = z.object({\n family: GateFamilySchema,\n check: z.string().min(1),\n reason: z.string().min(1),\n compensating_controls: z.array(z.string()),\n original_status: GateCheckStatusSchema,\n new_status: GateCheckStatusSchema,\n});\n\nexport const SectionGateResultSchema = z.object({\n section_id: z.string().regex(/^[0-9]{2}-[a-z0-9-]+$/),\n verdict: VerdictSchema,\n summary: z.string(),\n checked_at: z.string(),\n synthesis_eligible: z.boolean(),\n gate_results: z.array(GateCheckResultSchema),\n failures: z.array(GateCheckResultSchema),\n warnings: z.array(GateCheckResultSchema),\n waivers_applied: z.array(WaiverApplicationSchema),\n blocking_reasons: z.array(z.string()),\n claim_counts: z.object({\n total: z.number().int().nonnegative(),\n candidate: z.number().int().nonnegative(),\n with_evidence_excerpt: z.number().int().nonnegative(),\n with_source_hashes: z.number().int().nonnegative(),\n with_scope: z.number().int().nonnegative(),\n with_not: z.number().int().nonnegative(),\n universal_scope_null: z.number().int().nonnegative(),\n orphans: z.number().int().nonnegative(),\n }),\n source_counts: z.object({\n total: z.number().int().nonnegative(),\n primary: z.number().int().nonnegative(),\n secondary: z.number().int().nonnegative(),\n forum: z.number().int().nonnegative(),\n benchmark: z.number().int().nonnegative(),\n docs: z.number().int().nonnegative(),\n unknown: z.number().int().nonnegative(),\n independent_publishers: z.number().int().nonnegative(),\n failed_fetches: z.number().int().nonnegative(),\n }),\n contradiction_counts: z.object({\n total: z.number().int().nonnegative(),\n unresolved: z.number().int().nonnegative(),\n blocking: z.number().int().nonnegative(),\n by_type: z.record(z.string(), z.number().int().nonnegative()),\n }),\n freshness_summary: z.object({\n policy_required: z.boolean(),\n max_source_age_months: z.number().int().nullable(),\n stale_source_policy: z.enum(['warn', 'fail']),\n stale_count: z.number().int().nonnegative(),\n unknown_date_count: z.number().int().nonnegative(),\n }),\n scope_integrity_summary: z.object({\n universal_claims: z.number().int().nonnegative(),\n scoped_claims: z.number().int().nonnegative(),\n with_not_constraint: z.number().int().nonnegative(),\n overgen_risks_total: z.number().int().nonnegative(),\n overgen_risks_blocking: z.number().int().nonnegative(),\n }),\n next_actions: z.array(z.string()),\n});\n\nexport type SectionGateResult = z.infer<typeof SectionGateResultSchema>;\n","import { existsSync } from 'node:fs';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { join, resolve } from 'node:path';\nimport { parse as yamlParse, stringify as yamlStringify } from 'yaml';\n\nimport { PackNotFoundError, SectionNotFoundError } from '../errors.js';\nimport { ResearchYamlSchema, type ResearchYaml } from '../intake/schema.js';\nimport { ClaimSchema, type Claim } from '../claims/schema.js';\nimport { ContradictionSchema, type Contradiction } from '../contradictions/schema.js';\nimport { ContradictionResolutionSchema, type ContradictionResolution } from '../contradictions/resolution-schema.js';\nimport { FetchReceiptSchema, SourceCardSchema, type FetchReceipt, type SourceCard } from '../sources/schema.js';\nimport { ClaimReviewSchema, type ClaimReview } from '../review/schema.js';\n\nimport {\n checkClaimIntegrity,\n checkContradiction,\n checkFreshness,\n checkScopeIntegrity,\n checkSectionBudget,\n checkSourceFloor,\n applyWaivers,\n checkAcceptedClaimFloor,\n} from './checks/index.js';\nimport { renderGateMarkdown } from './markdown.js';\nimport { SectionGateResultSchema } from './schema.js';\nimport type {\n ClaimCounts,\n ContradictionCounts,\n FreshnessSummary,\n GateCheckResult,\n GateInput,\n RunGateOptions,\n ScopeIntegritySummary,\n SectionGateResult,\n SourceCounts,\n Verdict,\n} from './types.js';\n\nasync function readJsonl<T>(\n packPath: string,\n rel: string,\n parse: (raw: unknown) => T,\n): Promise<T[]> {\n const path = join(packPath, rel);\n if (!existsSync(path)) return [];\n const text = await readFile(path, 'utf8');\n const out: T[] = [];\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n out.push(parse(JSON.parse(line)));\n }\n return out;\n}\n\nasync function readSourceCards(packPath: string): Promise<SourceCard[]> {\n const dir = join(packPath, 'evidence', 'source-cards');\n if (!existsSync(dir)) return [];\n const { readdir } = await import('node:fs/promises');\n const entries = await readdir(dir);\n const cards: SourceCard[] = [];\n for (const entry of entries) {\n if (!entry.endsWith('.json')) continue;\n const text = await readFile(join(dir, entry), 'utf8');\n cards.push(SourceCardSchema.parse(JSON.parse(text)));\n }\n return cards;\n}\n\nfunction summarizeClaimCounts(input: GateInput): ClaimCounts {\n const c = input.claims;\n const cand = input.candidateClaims;\n const cardIds = new Set(input.sources.map((s) => s.source_id));\n return {\n total: c.length,\n candidate: cand.length,\n with_evidence_excerpt: cand.filter((x) => x.evidence_excerpt.trim().length > 0).length,\n with_source_hashes: cand.filter((x) => x.source_hashes.length > 0).length,\n with_scope: cand.filter((x) => x.scope !== null).length,\n with_not: cand.filter((x) => x.not !== null).length,\n universal_scope_null: cand.filter((x) => x.scope === null).length,\n orphans: cand.filter((x) => x.source_ids.some((sid) => !cardIds.has(sid))).length,\n };\n}\n\nfunction summarizeSourceCounts(input: GateInput): SourceCounts {\n const cards = input.sources;\n const failed = input.receipts.filter((r) => r.fetch_outcome !== 'ok').length;\n const publishers = new Set(\n cards.map((c) => c.publisher).filter((p): p is string => typeof p === 'string'),\n );\n return {\n total: cards.length,\n primary: cards.filter((c) => c.source_type === 'primary').length,\n secondary: cards.filter((c) => c.source_type === 'secondary').length,\n forum: cards.filter((c) => c.source_type === 'forum').length,\n benchmark: cards.filter((c) => c.source_type === 'benchmark').length,\n docs: cards.filter((c) => c.source_type === 'docs').length,\n unknown: cards.filter((c) => c.source_type === 'unknown').length,\n independent_publishers: publishers.size,\n failed_fetches: failed,\n };\n}\n\nfunction buildEffectiveStatuses(resolutions: ContradictionResolution[] | undefined): Map<string, string> {\n const map = new Map<string, string>();\n if (!resolutions || resolutions.length === 0) return map;\n const sorted = [...resolutions].sort((a, b) => a.resolved_at.localeCompare(b.resolved_at));\n for (const r of sorted) map.set(r.contradiction_id, r.status);\n return map;\n}\n\nfunction isEffectivelyUnresolved(contradictionId: string, rawStatus: string, effectiveStatuses: Map<string, string>): boolean {\n const effective = effectiveStatuses.get(contradictionId);\n return effective !== undefined ? effective === 'unresolved' : rawStatus === 'unresolved';\n}\n\nfunction summarizeContradictionCounts(input: GateInput): ContradictionCounts {\n const all = input.contradictions;\n const effectiveStatuses = buildEffectiveStatuses(input.resolutions);\n const unresolved = all.filter((c) => isEffectivelyUnresolved(c.contradiction_id, c.status, effectiveStatuses));\n const blocking = unresolved.filter(\n (c) => c.severity === 'blocking' || c.severity === 'high',\n );\n const byType: Record<string, number> = {};\n for (const c of all) {\n byType[c.type] = (byType[c.type] ?? 0) + 1;\n }\n return {\n total: all.length,\n unresolved: unresolved.length,\n blocking: blocking.length,\n by_type: byType,\n };\n}\n\nfunction summarizeFreshness(input: GateInput): FreshnessSummary {\n const cfg = input.research.gates.freshness;\n const policy = input.research.freshness;\n const cards = input.sources;\n let stale = 0;\n let unknownDate = 0;\n for (const c of cards) {\n if (!c.published_at) {\n unknownDate += 1;\n continue;\n }\n if (policy.max_source_age_months === null) continue;\n const d = Date.parse(c.published_at);\n if (Number.isNaN(d)) {\n unknownDate += 1;\n continue;\n }\n const ageMonths = (Date.now() - d) / (1000 * 60 * 60 * 24 * 30.44);\n if (ageMonths > policy.max_source_age_months) stale += 1;\n }\n return {\n policy_required: policy.required,\n max_source_age_months: policy.max_source_age_months,\n stale_source_policy: cfg.stale_source_policy,\n stale_count: stale,\n unknown_date_count: unknownDate,\n };\n}\n\nfunction summarizeScopeIntegrity(input: GateInput): ScopeIntegritySummary {\n const cand = input.candidateClaims;\n const effectiveStatuses = buildEffectiveStatuses(input.resolutions);\n const overgen = input.contradictions.filter(\n (c) => c.type === 'overgeneralization_risk' && isEffectivelyUnresolved(c.contradiction_id, c.status, effectiveStatuses),\n );\n const blocking = overgen.filter(\n (c) => c.severity === 'blocking' || c.severity === 'high',\n );\n return {\n universal_claims: cand.filter((c) => c.scope === null).length,\n scoped_claims: cand.filter((c) => c.scope !== null).length,\n with_not_constraint: cand.filter((c) => c.not !== null).length,\n overgen_risks_total: overgen.length,\n overgen_risks_blocking: blocking.length,\n };\n}\n\nfunction deriveVerdict(results: GateCheckResult[]): {\n verdict: Verdict;\n synthesis_eligible: boolean;\n blocking_reasons: string[];\n} {\n const blocking = results.filter((r) => r.blocks_synthesis && (r.status === 'fail' || r.status === 'warn_with_waiver'));\n const fails = results.filter((r) => r.status === 'fail');\n const warns = results.filter((r) => r.status === 'warn' || r.status === 'warn_with_waiver');\n if (blocking.length > 0) {\n return {\n verdict: 'blocked',\n synthesis_eligible: false,\n blocking_reasons: blocking.map((r) => `${r.family}.${r.check}: ${r.detail}`),\n };\n }\n if (fails.length > 0) {\n return { verdict: 'fail', synthesis_eligible: true, blocking_reasons: [] };\n }\n if (warns.length > 0) {\n return { verdict: 'warn', synthesis_eligible: true, blocking_reasons: [] };\n }\n return { verdict: 'pass', synthesis_eligible: true, blocking_reasons: [] };\n}\n\nfunction buildNextActions(results: GateCheckResult[]): string[] {\n const actions: string[] = [];\n for (const r of results) {\n if (r.status === 'fail') {\n switch (r.family) {\n case 'source_floor':\n if (r.check === 'min_sources') actions.push('Run `research-os gather` with additional URLs to reach the minimum source count.');\n else if (r.check === 'min_independent_publishers') actions.push('Add sources from additional publishers to satisfy publisher diversity.');\n else if (r.check === 'primary_sources_required') actions.push('Add primary sources or grant a primary_source_waiver in research.yaml with a reason and compensating_controls.');\n break;\n case 'claim_integrity':\n if (r.check === 'no_orphan_claims') actions.push('Re-run gather for missing source_ids or remove orphan claims from claims.jsonl.');\n else if (r.check === 'fetch_receipt_anchored') actions.push('Re-run gather to produce fresh fetch receipts for the affected claims.');\n else if (r.check === 'source_hashes_present' || r.check === 'evidence_excerpt_present') actions.push('Re-run claim extract; affected claims are missing fields the schema would reject.');\n break;\n case 'scope_integrity':\n if (r.check === 'no_blocking_overgeneralization') actions.push('Reconcile blocking overgeneralization_risk contradictions, or mark them preserved_deliberately with documented rationale.');\n break;\n case 'contradiction':\n if (r.check === 'unresolved_contradictions_block_synthesis') actions.push('Resolve, preserve, or reject blocking contradictions before synthesis.');\n break;\n case 'freshness':\n if (r.check === 'no_stale_sources') actions.push('Replace stale sources with recent ones, or change pack freshness policy if intentional.');\n break;\n case 'waivers':\n actions.push('Fix the waiver entry in research.yaml.primary_source_waiver (reason + compensating_controls + pack policy must allow it).');\n break;\n case 'accepted_claim_floor':\n actions.push('Gather more sources, extract claims, and promote at least 3 claims from at least 2 distinct sources to accepted_for_synthesis via review. Waivers cannot bypass this floor.');\n break;\n default:\n break;\n }\n }\n }\n return Array.from(new Set(actions));\n}\n\nasync function loadResearchYaml(packPath: string): Promise<ResearchYaml> {\n const yamlPath = join(packPath, 'research.yaml');\n if (!existsSync(yamlPath)) throw new PackNotFoundError(packPath);\n const text = await readFile(yamlPath, 'utf8');\n return ResearchYamlSchema.parse(yamlParse(text));\n}\n\nasync function updateSectionStatus(\n packPath: string,\n sectionId: string,\n synthesisEligible: boolean,\n): Promise<void> {\n const yamlPath = join(packPath, 'research.yaml');\n const text = await readFile(yamlPath, 'utf8');\n const research = ResearchYamlSchema.parse(yamlParse(text));\n const idx = research.sections.findIndex((s) => s.id === sectionId);\n if (idx < 0) return;\n const current = research.sections[idx]!;\n // Only upgrade to gated when synthesis-eligible and not already past it.\n if (synthesisEligible) {\n const order = ['draft', 'gathering', 'gated', 'reviewed', 'frozen'] as const;\n const currentRank = order.indexOf(current.status);\n const gatedRank = order.indexOf('gated');\n if (currentRank < gatedRank) {\n research.sections[idx] = { ...current, status: 'gated' };\n await writeFile(yamlPath, yamlStringify(research, { lineWidth: 0 }), 'utf8');\n }\n }\n}\n\nexport async function gate(options: RunGateOptions): Promise<SectionGateResult> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n if (!existsSync(join(packPath, 'research.yaml'))) throw new PackNotFoundError(packPath);\n const sectionDir = join(packPath, 'sections', options.sectionId);\n if (!existsSync(sectionDir)) throw new SectionNotFoundError(options.sectionId);\n const research = await loadResearchYaml(packPath);\n const section = research.sections.find((s) => s.id === options.sectionId);\n if (!section) throw new SectionNotFoundError(options.sectionId);\n\n const claims = await readJsonl<Claim>(packPath, `sections/${options.sectionId}/claims.jsonl`, (r) => ClaimSchema.parse(r));\n const candidateClaims = claims.filter((c) => c.review_state === 'candidate');\n const sources = await readSourceCards(packPath);\n const receipts = await readJsonl<FetchReceipt>(packPath, 'evidence/fetch-log.jsonl', (r) => FetchReceiptSchema.parse(r));\n const contradictions = await readJsonl<Contradiction>(packPath, `sections/${options.sectionId}/contradictions.jsonl`, (r) => ContradictionSchema.parse(r));\n const claimReviews = await readJsonl<ClaimReview>(packPath, `sections/${options.sectionId}/claim-reviews.jsonl`, (r) => ClaimReviewSchema.parse(r));\n const resolutions = await readJsonl<ContradictionResolution>(packPath, `sections/${options.sectionId}/contradiction-resolutions.jsonl`, (r) => ContradictionResolutionSchema.parse(r));\n\n const input: GateInput = {\n research,\n section,\n claims,\n candidateClaims,\n sources,\n receipts,\n contradictions,\n claimReviews,\n resolutions,\n };\n\n const rawResults: GateCheckResult[] = [\n ...checkSourceFloor(input),\n ...checkClaimIntegrity(input),\n ...checkScopeIntegrity(input),\n ...checkFreshness(input),\n ...checkContradiction(input),\n ...checkSectionBudget(input),\n ...checkAcceptedClaimFloor(input),\n ];\n\n const { updatedResults, waivers_applied, waiver_validation_failures } = applyWaivers(input, rawResults);\n const finalResults = [...updatedResults, ...waiver_validation_failures];\n\n const failures = finalResults.filter((r) => r.status === 'fail');\n const warnings = finalResults.filter((r) => r.status === 'warn' || r.status === 'warn_with_waiver');\n const { verdict, synthesis_eligible, blocking_reasons } = deriveVerdict(finalResults);\n\n const result: SectionGateResult = SectionGateResultSchema.parse({\n section_id: options.sectionId,\n verdict,\n summary: buildSummary(verdict, synthesis_eligible, failures.length, warnings.length, waivers_applied.length),\n checked_at: new Date().toISOString(),\n synthesis_eligible,\n gate_results: finalResults,\n failures,\n warnings,\n waivers_applied,\n blocking_reasons,\n claim_counts: summarizeClaimCounts(input),\n source_counts: summarizeSourceCounts(input),\n contradiction_counts: summarizeContradictionCounts(input),\n freshness_summary: summarizeFreshness(input),\n scope_integrity_summary: summarizeScopeIntegrity(input),\n next_actions: buildNextActions(finalResults),\n });\n\n const auditsDir = join(packPath, 'audits');\n await mkdir(auditsDir, { recursive: true });\n await writeFile(\n join(auditsDir, `${options.sectionId}-gate.json`),\n JSON.stringify(result, null, 2),\n 'utf8',\n );\n await writeFile(\n join(auditsDir, `${options.sectionId}-gate.md`),\n renderGateMarkdown(result),\n 'utf8',\n );\n\n await updateSectionStatus(packPath, options.sectionId, synthesis_eligible);\n\n return result;\n}\n\nfunction buildSummary(\n verdict: Verdict,\n eligible: boolean,\n failureCount: number,\n warningCount: number,\n waiverCount: number,\n): string {\n const eligibility = eligible ? 'synthesis-eligible' : 'NOT synthesis-eligible';\n const failurePart = failureCount > 0 ? `${failureCount} failure(s)` : 'no failures';\n const warningPart = warningCount > 0 ? `${warningCount} warning(s)` : 'no warnings';\n const waiverPart = waiverCount > 0 ? `${waiverCount} waiver(s) applied` : 'no waivers';\n return `Verdict: ${verdict}. ${eligibility}. ${failurePart}; ${warningPart}; ${waiverPart}.`;\n}\n","export { gate } from './run.js';\nexport {\n checkSourceFloor,\n checkClaimIntegrity,\n checkScopeIntegrity,\n checkFreshness,\n checkContradiction,\n checkSectionBudget,\n applyWaivers,\n} from './checks/index.js';\nexport { renderGateMarkdown } from './markdown.js';\nexport {\n GateFamilySchema,\n GateCheckStatusSchema,\n VerdictSchema,\n GateCheckResultSchema,\n WaiverApplicationSchema,\n SectionGateResultSchema,\n} from './schema.js';\nexport type {\n GateFamily,\n GateCheckStatus,\n Verdict,\n GateCheckResult,\n WaiverApplication,\n ClaimCounts,\n SourceCounts,\n ContradictionCounts,\n FreshnessSummary,\n ScopeIntegritySummary,\n SectionGateResult,\n GateInput,\n RunGateOptions,\n} from './types.js';\n","// Review profile machinery. Each review run lives under a named profile so\n// A/B reviewer experiments don't silently overwrite the section's effective\n// review state. The \"active\" profile (recorded in\n// sections/<id>/review-active.json) is the one whose decisions canonical\n// consumers see; all other profiles are calibration evidence.\n//\n// Reads gracefully fall back when no profile machinery is set up — the\n// pre-profile dogfood pack continues to work because consumers still read\n// from canonical paths.\n\nimport { existsSync } from 'node:fs';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { z } from 'zod';\n\nexport const DEFAULT_PROFILE = 'default';\n\n// A reviewer-calibration snapshot the promoter recorded at the moment they\n// chose to trust this profile. Optional but strongly encouraged — gate/\n// audit/freeze can use this to explain (not just assert) why the active\n// review state is the active review state.\nexport const PromotionCalibrationSummarySchema = z.object({\n fixture: z.string().nullable().default(null),\n good_false_positive_rate: z.string().nullable().default(null),\n bad_any_flag_recall: z.string().nullable().default(null),\n strict_category_recall: z.string().nullable().default(null),\n unsupported_claim_recall: z.string().nullable().default(null),\n notes: z.string().nullable().default(null),\n});\n\nexport const ReviewActiveSchema = z.object({\n active_profile: z.string().min(1),\n promoted_at: z.string(),\n promoted_method: z.string(),\n promoted_reviewer: z.string(),\n // Free-text reason the profile was promoted. Recorded once at promotion\n // time; not derived from artifacts. Required.\n promotion_reason: z.string().min(8).default('promoted via review-promote without an explicit reason'),\n // Optional calibration evidence captured at promotion time so downstream\n // consumers can see WHY the reviewer was trusted.\n calibration_summary: PromotionCalibrationSummarySchema.nullable().default(null),\n});\n\nexport type PromotionCalibrationSummary = z.infer<typeof PromotionCalibrationSummarySchema>;\nexport type ReviewActive = z.infer<typeof ReviewActiveSchema>;\n\nexport function reviewActivePath(packPath: string, sectionId: string): string {\n return join(packPath, 'sections', sectionId, 'review-active.json');\n}\n\nexport function profileDir(packPath: string, sectionId: string, profile: string): string {\n return join(packPath, 'sections', sectionId, 'reviews', profile);\n}\n\nexport async function readActiveProfile(\n packPath: string,\n sectionId: string,\n): Promise<string> {\n const path = reviewActivePath(packPath, sectionId);\n if (!existsSync(path)) return DEFAULT_PROFILE;\n try {\n const parsed = ReviewActiveSchema.parse(JSON.parse(await readFile(path, 'utf8')));\n return parsed.active_profile;\n } catch {\n return DEFAULT_PROFILE;\n }\n}\n\nexport async function writeActiveProfile(\n packPath: string,\n sectionId: string,\n active: ReviewActive,\n): Promise<void> {\n const path = reviewActivePath(packPath, sectionId);\n await mkdir(join(packPath, 'sections', sectionId), { recursive: true });\n await writeFile(path, JSON.stringify(ReviewActiveSchema.parse(active), null, 2), 'utf8');\n}\n\nexport function isValidProfileName(name: string): boolean {\n return /^[a-z0-9][a-z0-9._-]{0,63}$/.test(name);\n}\n","import type { Claim } from '../../claims/schema.js';\nimport type { Excerpt } from '../../sources/excerpts/schema.js';\nimport type {\n DraftFinding,\n Reviewer,\n ReviewerInput,\n ReviewerResult,\n} from '../types.js';\n\nconst STUB_BRIEF_MARKER = 'This section has not been gathered yet';\nconst MIN_BRIEF_LENGTH_FOR_HIDDEN_SYNTHESIS = 600;\n\n// Same join-separator extract.ts uses when concatenating multi-id excerpts\n// into evidence_excerpt. Stays in sync deliberately.\nconst EVIDENCE_EXCERPT_JOIN = ' … ';\n\nfunction normalize(text: string): string {\n return text.replace(/<[^>]+>/g, ' ').replace(/\\s+/g, ' ').toLowerCase().trim();\n}\n\n// Legacy raw-text substring check, kept for claims that pre-date span-first\n// (evidence_excerpt_ids: []). New claims are validated via the deterministic\n// excerpt ledger in evidenceGroundedViaLedger below.\nfunction evidenceGroundedInRaw(claim: Claim, rawTextBySourceId: Map<string, string>): boolean {\n const excerpt = normalize(claim.evidence_excerpt);\n if (excerpt.length < 8) return false;\n for (const sid of claim.source_ids) {\n const raw = rawTextBySourceId.get(sid);\n if (!raw) continue;\n if (normalize(raw).includes(excerpt)) return true;\n }\n return false;\n}\n\ntype GroundingMode = 'span_first_ok' | 'span_first_fail' | 'legacy';\n\ninterface GroundingResult {\n mode: GroundingMode;\n reason: string;\n}\n\n// Span-first grounding check. The reviewer should NOT re-normalise raw text\n// and substring-search for a copied excerpt — that path produced false\n// positives (claim evidence text differs trivially from raw text after\n// HTML/whitespace normalisation). Instead, validate structurally:\n// 1. Every cited evidence_excerpt_id resolves in the source's ledger.\n// 2. The claim's evidence_excerpt equals the deterministic join of the\n// ledger texts (or a deterministic truncation prefix of that join).\n// Returns 'legacy' if the claim has no evidence_excerpt_ids — those predate\n// span-first and use the raw-text fallback.\nfunction evidenceGroundedViaLedger(\n claim: Claim,\n excerptsBySourceId: Map<string, Map<string, Excerpt>>,\n): GroundingResult {\n if (!claim.evidence_excerpt_ids || claim.evidence_excerpt_ids.length === 0) {\n return { mode: 'legacy', reason: 'pre-span-first claim (no evidence_excerpt_ids)' };\n }\n for (const sid of claim.source_ids) {\n const ledger = excerptsBySourceId.get(sid);\n if (!ledger) continue;\n const allFound = claim.evidence_excerpt_ids.every((id) => ledger.has(id));\n if (!allFound) {\n return {\n mode: 'span_first_fail',\n reason: `One or more evidence_excerpt_ids do not resolve in the ledger for ${sid}`,\n };\n }\n // Deterministic re-derivation of the expected evidence_excerpt.\n const seen = new Set<string>();\n const texts: string[] = [];\n for (const id of claim.evidence_excerpt_ids) {\n if (seen.has(id)) continue;\n seen.add(id);\n texts.push(ledger.get(id)!.text);\n }\n const expected = texts.join(EVIDENCE_EXCERPT_JOIN);\n const actual = claim.evidence_excerpt;\n if (actual === expected) {\n return { mode: 'span_first_ok', reason: 'evidence_excerpt matches the ledger join exactly' };\n }\n // Tolerate the truncation suffix extract.ts adds when the joined text\n // exceeds the per-claim cap.\n if (actual.endsWith(' …') && expected.startsWith(actual.slice(0, -2).trimEnd())) {\n return {\n mode: 'span_first_ok',\n reason: 'evidence_excerpt is a deterministic truncation of the ledger join',\n };\n }\n return {\n mode: 'span_first_fail',\n reason: `evidence_excerpt does not match the deterministic ledger join for ${sid}`,\n };\n }\n return {\n mode: 'span_first_fail',\n reason: 'no ledger available for any cited source',\n };\n}\n\nexport class HeuristicReviewer implements Reviewer {\n readonly name = 'heuristic' as const;\n\n async available(): Promise<boolean> {\n return true;\n }\n\n async review(input: ReviewerInput): Promise<ReviewerResult> {\n const drafts: DraftFinding[] = [];\n const cardIds = new Set(input.sources.map((c) => c.source_id));\n const okReceiptSourceIds = new Set(\n input.receipts.filter((r) => r.fetch_outcome === 'ok').map((r) => r.source_id),\n );\n\n for (const claim of input.candidateClaims) {\n // unsupported_claim — claim cites no source_id that resolves to a card+receipt\n const validCites = claim.source_ids.filter(\n (sid) => cardIds.has(sid) && okReceiptSourceIds.has(sid),\n );\n if (validCites.length === 0) {\n drafts.push({\n category: 'unsupported_claim',\n severity: 'block',\n summary: `Claim ${claim.claim_id} cites no source that resolves to both a source card and a successful fetch receipt.`,\n evidence: `Cited source_ids: ${claim.source_ids.join(', ') || '(none)'}`,\n required_action: 'Re-run gather for the cited sources, or remove the claim.',\n claim_ids: [claim.claim_id],\n source_ids: claim.source_ids,\n confidence: 'high',\n });\n }\n\n // ungrounded_excerpt — span-first grounding check.\n // - Span-first claims (evidence_excerpt_ids non-empty) are validated\n // structurally: every cited ID must resolve in the ledger AND the\n // claim's evidence_excerpt must equal the deterministic ledger join.\n // - Legacy claims (no excerpt IDs) fall back to the raw-text\n // substring check that was the original v0.1 anti-hallucination\n // guard. That path will be removed once all packs migrate.\n if (validCites.length > 0) {\n const grounding = evidenceGroundedViaLedger(claim, input.excerptsBySourceId);\n let ungrounded = false;\n let detail = '';\n if (grounding.mode === 'span_first_fail') {\n ungrounded = true;\n detail = grounding.reason;\n } else if (grounding.mode === 'legacy') {\n if (!evidenceGroundedInRaw(claim, input.rawTextBySourceId)) {\n ungrounded = true;\n detail = 'Legacy claim: evidence_excerpt is not a substring of any cited source raw text';\n }\n }\n if (ungrounded) {\n drafts.push({\n category: 'ungrounded_excerpt',\n severity: 'block',\n summary: `Claim ${claim.claim_id} fails the structural evidence check (${detail}).`,\n evidence: `Excerpt (truncated): ${claim.evidence_excerpt.slice(0, 200)}`,\n required_action: 'Re-extract the claim from the cited source, or remove it.',\n claim_ids: [claim.claim_id],\n source_ids: claim.source_ids,\n confidence: 'high',\n });\n }\n }\n\n // overgeneralized_claim / scope_widening — scope null with substantive asserts\n if (claim.scope === null && claim.asserts.length > 40) {\n drafts.push({\n category: 'overgeneralized_claim',\n severity: 'warn',\n summary: `Claim ${claim.claim_id} has scope=null with a substantive assertion. It cannot be treated as broad without scope-widening evidence.`,\n evidence: `Asserts: ${claim.asserts.slice(0, 200)}`,\n required_action: 'Add an explicit scope tag or restrict the claim to the source\\'s actual scope.',\n claim_ids: [claim.claim_id],\n source_ids: claim.source_ids,\n confidence: 'medium',\n });\n }\n\n // missing_not_constraint\n if (claim.not === null) {\n drafts.push({\n category: 'missing_not_constraint',\n severity: 'info',\n summary: `Claim ${claim.claim_id} has no 'not' constraint recorded.`,\n evidence: `Asserts: ${claim.asserts.slice(0, 160)}`,\n required_action: 'Consider adding a not-constraint to defend against overgeneralization downstream.',\n claim_ids: [claim.claim_id],\n source_ids: claim.source_ids,\n confidence: 'low',\n });\n }\n\n // source_quality_problem — claim with high confidence but weak source type\n const cards = input.sources.filter((c) => claim.source_ids.includes(c.source_id));\n const weakTypes = cards.filter((c) => c.source_type === 'forum' || c.source_type === 'unknown');\n if (claim.confidence === 'high' && weakTypes.length === cards.length && cards.length > 0) {\n drafts.push({\n category: 'source_quality_problem',\n severity: 'warn',\n summary: `Claim ${claim.claim_id} carries confidence=high but every cited source is forum/unknown quality.`,\n evidence: `Source types: ${cards.map((c) => c.source_type).join(', ')}`,\n required_action: 'Lower confidence or add a higher-quality corroborating source.',\n claim_ids: [claim.claim_id],\n source_ids: claim.source_ids,\n confidence: 'medium',\n });\n }\n\n // source_cluster_monopoly — every cited source from one publisher\n const publishers = new Set(\n cards.map((c) => c.publisher).filter((p): p is string => typeof p === 'string'),\n );\n if (cards.length > 0 && publishers.size <= 1 && claim.source_ids.length >= 2) {\n drafts.push({\n category: 'source_cluster_monopoly',\n severity: 'warn',\n summary: `Claim ${claim.claim_id} sources every cite from a single publisher.`,\n evidence: `Publishers: ${[...publishers].join(', ') || '(unknown)'}`,\n required_action: 'Add a citation from an independent publisher or downgrade the claim.',\n claim_ids: [claim.claim_id],\n source_ids: claim.source_ids,\n confidence: 'medium',\n });\n }\n\n // stale_claim — based on freshness policy\n if (input.research.freshness.required && input.research.freshness.max_source_age_months !== null) {\n const maxAge = input.research.freshness.max_source_age_months;\n for (const card of cards) {\n if (!card.published_at) continue;\n const d = Date.parse(card.published_at);\n if (Number.isNaN(d)) continue;\n const ageMonths = (Date.now() - d) / (1000 * 60 * 60 * 24 * 30.44);\n if (ageMonths > maxAge) {\n drafts.push({\n category: 'stale_claim',\n severity: 'warn',\n summary: `Claim ${claim.claim_id} cites a source older than the pack freshness policy (${maxAge} months).`,\n evidence: `Source ${card.source_id} published_at=${card.published_at}.`,\n required_action: 'Replace with a more recent source, or mark the section as not requiring freshness.',\n claim_ids: [claim.claim_id],\n source_ids: [card.source_id],\n confidence: 'medium',\n });\n break;\n }\n }\n }\n\n // unmapped_contradiction — claim is involved in an unresolved contradiction.\n // Check resolution ledger (latest-wins) before falling back to the raw status field.\n const resolvedContradictionIds = new Set<string>();\n if (input.resolutions && input.resolutions.length > 0) {\n const sorted = [...input.resolutions].sort((a, b) => a.resolved_at.localeCompare(b.resolved_at));\n const effectiveMap = new Map<string, string>();\n for (const r of sorted) effectiveMap.set(r.contradiction_id, r.status);\n for (const [cid, status] of effectiveMap) {\n if (status !== 'unresolved') resolvedContradictionIds.add(cid);\n }\n }\n const involved = input.contradictions.filter(\n (c) =>\n c.claim_ids.includes(claim.claim_id) &&\n c.status === 'unresolved' &&\n !resolvedContradictionIds.has(c.contradiction_id),\n );\n const blockingInvolved = involved.filter(\n (c) => c.severity === 'high' || c.severity === 'blocking',\n );\n if (blockingInvolved.length > 0) {\n drafts.push({\n category: 'unmapped_contradiction',\n severity: 'block',\n summary: `Claim ${claim.claim_id} is involved in ${blockingInvolved.length} unresolved high/blocking contradiction(s).`,\n evidence: `Contradiction IDs: ${blockingInvolved.map((c) => c.contradiction_id).join(', ')}`,\n required_action: 'Reconcile, preserve_deliberately, or reject the contradicting claim before synthesis.',\n claim_ids: [claim.claim_id],\n source_ids: claim.source_ids,\n confidence: 'high',\n });\n } else if (involved.length > 0) {\n drafts.push({\n category: 'unmapped_contradiction',\n severity: 'warn',\n summary: `Claim ${claim.claim_id} is involved in ${involved.length} unresolved low/medium-severity contradiction(s).`,\n evidence: `Contradiction IDs: ${involved.map((c) => c.contradiction_id).join(', ')}`,\n required_action: 'Resolve or note the contradiction before relying on the claim.',\n claim_ids: [claim.claim_id],\n source_ids: claim.source_ids,\n confidence: 'medium',\n });\n }\n }\n\n // section-level source_cluster_monopoly — every section source from a single publisher\n if (input.sources.length >= 2 && input.candidateClaims.length > 0) {\n const sectionPublishers = new Set(\n input.sources.map((c) => c.publisher).filter((p): p is string => typeof p === 'string'),\n );\n if (sectionPublishers.size === 1) {\n const [pub] = sectionPublishers;\n drafts.push({\n category: 'source_cluster_monopoly',\n severity: 'warn',\n summary: `Every source for this section traces to a single publisher (${pub}). Claims drawn from this section inherit a publisher-monopoly limitation.`,\n evidence: `Section sources: ${input.sources.length}; distinct publishers: 1 (${pub}).`,\n required_action: 'Add at least one source from an independent publisher before treating these claims as broadly corroborated.',\n claim_ids: input.candidateClaims.map((c) => c.claim_id),\n source_ids: input.sources.map((c) => c.source_id),\n confidence: 'high',\n });\n }\n }\n\n // claim_overproduction — span-first + paged extraction can yield dense\n // claim sets where one source dominates the section, or a cluster of\n // claims share near-identical asserts. We surface BOTH signals so the\n // reviewer can collapse before synthesis treats every grounded span as\n // equally decision-useful. This is structural — interpretive judgement\n // (which claims to keep) belongs to the LLM reviewer or the human.\n if (input.candidateClaims.length > 0) {\n const claimsBySrc = new Map<string, Claim[]>();\n for (const c of input.candidateClaims) {\n for (const sid of c.source_ids) {\n const arr = claimsBySrc.get(sid) ?? [];\n arr.push(c);\n claimsBySrc.set(sid, arr);\n }\n }\n const total = input.candidateClaims.length;\n // Density flag: any source contributing >= 30 claims, OR (when the\n // section has substantive volume — >= 10 total claims and >= 8 from\n // this source) >= 40% of the section's candidate claims.\n // Tiny sections (1-2 claims) never qualify — there's nothing to flag.\n const MIN_TOTAL_FOR_RATIO = 10;\n const MIN_PER_SOURCE_FOR_RATIO = 8;\n for (const [sid, claims] of claimsBySrc.entries()) {\n const ratio = claims.length / Math.max(1, total);\n const ratioFlag =\n total >= MIN_TOTAL_FOR_RATIO &&\n claims.length >= MIN_PER_SOURCE_FOR_RATIO &&\n ratio >= 0.4;\n if (claims.length >= 30 || ratioFlag) {\n const severity = claims.length >= 50 || (ratioFlag && ratio >= 0.6) ? 'block' : 'warn';\n drafts.push({\n category: 'claim_overproduction',\n severity,\n summary: `Source ${sid} contributes ${claims.length} of ${total} candidate claim(s) (${(ratio * 100).toFixed(0)}% of the section). Even if every claim is grounded, the cluster is likely synthesis noise.`,\n evidence: `Top source: ${sid}; claims=${claims.length}; share=${(ratio * 100).toFixed(0)}%.`,\n required_action:\n 'Collapse near-duplicate claims into a smaller set of decision-useful propositions before synthesis.',\n claim_ids: claims.map((c) => c.claim_id),\n source_ids: [sid],\n confidence: 'high',\n });\n }\n }\n // Near-duplicate clustering — group claims by normalised asserts. Any\n // cluster with >= 3 members raises a single finding spanning the cluster.\n const clusters = new Map<string, Claim[]>();\n for (const c of input.candidateClaims) {\n const key = c.asserts.toLowerCase().replace(/[^a-z0-9 ]+/g, ' ').replace(/\\s+/g, ' ').trim();\n const arr = clusters.get(key) ?? [];\n arr.push(c);\n clusters.set(key, arr);\n }\n for (const [, members] of clusters.entries()) {\n if (members.length >= 3) {\n drafts.push({\n category: 'claim_overproduction',\n severity: 'warn',\n summary: `${members.length} claims in this section share a normalised assertion. Likely extractor over-atomization.`,\n evidence: `Sample assert: \"${members[0]!.asserts.slice(0, 140)}\"`,\n required_action:\n 'Keep one representative claim and reject the duplicates, or merge them into a single claim with combined excerpt IDs.',\n claim_ids: members.map((c) => c.claim_id),\n source_ids: Array.from(new Set(members.flatMap((c) => c.source_ids))),\n confidence: 'medium',\n });\n }\n }\n }\n\n // hidden_synthesis — section brief.md has been edited beyond stub state\n if (input.briefText !== null) {\n const isStub = input.briefText.includes(STUB_BRIEF_MARKER);\n if (!isStub && input.briefText.length > MIN_BRIEF_LENGTH_FOR_HIDDEN_SYNTHESIS) {\n drafts.push({\n category: 'hidden_synthesis',\n severity: 'warn',\n summary: `Section brief.md has substantive prose. Verify every assertion in the brief traces to a candidate claim in claims.jsonl.`,\n evidence: `brief.md length: ${input.briefText.length} chars; candidate claims: ${input.candidateClaims.length}.`,\n required_action: 'Audit brief.md sentence-by-sentence against the claim ledger; flag any prose without a backing claim.',\n claim_ids: input.candidateClaims.map((c) => c.claim_id),\n source_ids: [],\n confidence: 'low',\n });\n }\n }\n\n return { ok: true, drafts, method: 'heuristic_field_and_grounding_checks' };\n }\n}\n","import { normalizeOllamaHost } from '../../sources/extractors/ollama-intern.js';\nimport type {\n DraftFinding,\n FindingCategory,\n FindingSeverity,\n Reviewer,\n ReviewerInput,\n ReviewerResult,\n} from '../types.js';\n\nconst DEFAULT_HOST = 'http://localhost:11434';\nconst DEFAULT_MODEL = 'hermes3:8b';\nconst DEFAULT_TIMEOUT_MS = 180_000;\n// Narrow-critic mode runs an aggressive prompt that often triggers extended\n// reasoning (qwen3 thinking, hermes longer chain-of-thought). 10-minute\n// budget per page so the critic can finish on small/mid GPUs.\nconst NARROW_CRITIC_TIMEOUT_MS = 600_000;\n\nconst GENERAL_SYSTEM_PROMPT = `You are an adversarial reviewer for a gated research pack.\n\nYou are given a list of candidate claims with their asserts/scope/not/evidence_excerpt and source IDs. Find INTEGRITY problems. You are NOT here to synthesize; you are here to attack.\n\nLook for:\n- overgeneralized_claim: claim widens beyond what the source supports\n- scope_widening: scope is broader than evidence justifies\n- definition_drift: terms used differently across claims (cite the conflicting claim_ids)\n- recommendation_exceeds_evidence: claim implies an action the source does not support\n- hidden_synthesis: claim asserts a conclusion not present in the cited source\n- temporal_mismatch: claim cites a source from a different time period than its asserts implies\n- claim_overproduction: a cluster of grounded but redundant/atomized claims from one source — collectively synthesis noise. Cite all claim_ids in the cluster on a single finding.\n- valid_but_low_value: this individual claim is grounded but is not synthesis-worthy — restates context, definitional boilerplate, trivia, or low-leverage detail. Cite ONE claim_id per finding.\n\nReturn ONE JSON object: {\"findings\": [...]}.\n\nFor each finding:\n{\n \"category\": one of the LLM-relevant categories above (use exact strings),\n \"severity\": \"info\" | \"warn\" | \"block\",\n \"summary\": ONE sentence,\n \"evidence\": short string referencing the conflicting parts,\n \"required_action\": ONE sentence,\n \"claim_ids\": array of claim_ids that EXIST in the input — do NOT invent IDs,\n \"source_ids\": array of source_ids cited by those claims,\n \"confidence\": \"low\" | \"medium\" | \"high\"\n}\n\nHard rules:\n- Cite ONLY claim_ids and source_ids that appear in the input. Findings with invented IDs are rejected.\n- Do not introduce new facts.\n- Do not synthesize or rewrite claims.\n- Do not assess \"correctness\" of the world; assess integrity of the claim against its source.\n- If you find no problems, return {\"findings\": []}. A clean review is a valid result.`;\n\n// Narrow critic prompt — runs as a SECOND PASS targeting four categories\n// with high precision the general reviewer tends to under-flag (especially\n// unsupported_claim, where calibration showed 0/3 recall on hermes3:8b).\n// This reviewer is deliberately aggressive: err on flagging.\nconst NARROW_CRITIC_SYSTEM_PROMPT = `You are a NARROW CRITIC for a research pack. Your only job is to attack four specific failure modes — be unforgiving.\n\nONLY look for these four categories (ignore everything else):\n- unsupported_claim: the asserts is not directly supported by the evidence_excerpt. If the evidence does not contain the specific concepts/numbers/terms in the asserts, that is unsupported_claim — even if the claim sounds plausible.\n- scope_widening: the asserts uses universal quantifiers (all, every, always, never, must, dominant) but the scope is narrow. Single-source generalisations are scope_widening by default.\n- missing_not_constraint: the asserts is substantive AND has no \\`not\\` boundary, AND the topic plausibly admits universalisation. Flag warn-level.\n- temporal_mismatch: the asserts implies a current/recent state but the scope mentions an old date or stale context.\n\nFor each finding return:\n{\n \"category\": one of the four categories above EXACTLY,\n \"severity\": \"warn\" | \"block\",\n \"summary\": ONE sentence,\n \"evidence\": short quote from asserts/scope/evidence_excerpt that signals the failure,\n \"required_action\": ONE sentence,\n \"claim_ids\": [exactly one claim_id from the input],\n \"source_ids\": [source_ids of that claim],\n \"confidence\": \"low\" | \"medium\" | \"high\"\n}\n\nHard rules:\n- Be unforgiving. If the evidence_excerpt does not directly support the asserts word-for-word, flag it as unsupported_claim.\n- If the asserts has \"all\", \"every\", \"always\", \"never\", \"dominant\", or \"must\" and the scope is narrow, flag scope_widening.\n- DO NOT flag any other category. The general reviewer handles those.\n- Cite ONLY claim_ids that appear in the input. Findings with invented IDs are rejected.\n- Return {\"findings\": []} if and only if every claim is genuinely clean across these four categories.\n\nReturn ONE JSON object: {\"findings\": [...]}.`;\n\nexport type ReviewerMode = 'general' | 'narrow_critic';\n\ninterface ChatResponse {\n message?: { content?: string };\n response?: string;\n}\n\nconst VALID_CATEGORIES: FindingCategory[] = [\n 'overgeneralized_claim',\n 'scope_widening',\n 'definition_drift',\n 'recommendation_exceeds_evidence',\n 'hidden_synthesis',\n 'temporal_mismatch',\n 'claim_overproduction',\n 'valid_but_low_value',\n // The reviewer prompt uses the LLM-relevant subset; heuristic handles the others.\n];\n\nconst VALID_SEVERITIES: FindingSeverity[] = ['info', 'warn', 'block'];\nconst VALID_CONFIDENCES = ['low', 'medium', 'high'] as const;\n\nfunction asEnum<T extends string>(value: unknown, allowed: readonly T[], fallback: T): T {\n return typeof value === 'string' && (allowed as readonly string[]).includes(value)\n ? (value as T)\n : fallback;\n}\n\nfunction asStringArray(v: unknown): string[] {\n return Array.isArray(v)\n ? v.filter((x): x is string => typeof x === 'string').map((s) => s.trim()).filter((s) => s.length > 0)\n : [];\n}\n\nexport interface OllamaReviewerConfig {\n host?: string;\n model?: string;\n timeoutMs?: number;\n // Number of claims per LLM window. Reviewer-side analogue of the\n // extractor's paging: keeps the prompt + response within the model's\n // effective context, and forces per-window claim_id validation so the\n // model can't cite IDs it didn't actually see.\n claimsPerWindow?: number;\n // 'general' (default) uses the broad multi-category prompt. 'narrow_critic'\n // uses the aggressive 4-category prompt designed for the second-pass\n // hardening run that targets unsupported_claim / scope_widening /\n // missing_not_constraint / temporal_mismatch.\n mode?: ReviewerMode;\n fetchImpl?: typeof fetch;\n}\n\nconst DEFAULT_CLAIMS_PER_WINDOW = 30;\n\n// Window an array into N-sized chunks.\nexport function pageClaimsForReview<T>(items: T[], windowSize: number): T[][] {\n if (items.length === 0) return [];\n const out: T[][] = [];\n for (let i = 0; i < items.length; i += windowSize) {\n out.push(items.slice(i, i + windowSize));\n }\n return out;\n}\n\nexport class OllamaInternReviewer implements Reviewer {\n readonly name = 'ollama-intern' as const;\n readonly mode: ReviewerMode;\n private readonly host: string;\n private readonly model: string;\n private readonly timeoutMs: number;\n private readonly claimsPerWindow: number;\n private readonly fetchImpl: typeof fetch;\n\n constructor(config: OllamaReviewerConfig = {}) {\n this.host = normalizeOllamaHost(config.host ?? process.env.OLLAMA_HOST ?? DEFAULT_HOST);\n this.model = config.model ?? process.env.OLLAMA_INTERN_MODEL ?? DEFAULT_MODEL;\n this.mode = config.mode ?? 'general';\n this.timeoutMs =\n config.timeoutMs ??\n (this.mode === 'narrow_critic' ? NARROW_CRITIC_TIMEOUT_MS : DEFAULT_TIMEOUT_MS);\n const envWindow = process.env.OLLAMA_INTERN_REVIEW_WINDOW;\n this.claimsPerWindow =\n config.claimsPerWindow ??\n (envWindow ? parseInt(envWindow, 10) || DEFAULT_CLAIMS_PER_WINDOW : DEFAULT_CLAIMS_PER_WINDOW);\n this.fetchImpl = config.fetchImpl ?? globalThis.fetch;\n }\n\n async available(): Promise<boolean> {\n try {\n const ctrl = new AbortController();\n const t = setTimeout(() => ctrl.abort(), 1500);\n const res = await this.fetchImpl(`${this.host}/api/tags`, { signal: ctrl.signal });\n clearTimeout(t);\n if (!res.ok) return false;\n const body = (await res.json()) as { models?: Array<{ name: string }> };\n const names = (body.models ?? []).map((m) => m.name);\n const family = this.model.split(':')[0] ?? this.model;\n return names.some((n) => n === this.model || n === family || n.startsWith(`${family}:`));\n } catch {\n return false;\n }\n }\n\n // Single-window LLM call. Per-window IDs are validated by the caller so a\n // window-1 finding can't cite a window-2 claim.\n private async reviewOnePage(\n windowClaims: ReviewerInput['candidateClaims'],\n sectionId: string,\n sectionPurpose: string,\n ): Promise<{ ok: true; drafts: DraftFinding[] } | { ok: false; error: string }> {\n const claimsBlock = windowClaims\n .map((c) =>\n [\n `Claim ${c.claim_id}:`,\n ` asserts: ${c.asserts}`,\n ` scope: ${c.scope ?? 'null'}`,\n ` not: ${c.not ?? 'null'}`,\n ` evidence_excerpt: ${c.evidence_excerpt}`,\n ` confidence: ${c.confidence}`,\n ` source_ids: ${c.source_ids.join(', ')}`,\n ].join('\\n'),\n )\n .join('\\n\\n');\n\n const userMsg = `Section: ${sectionId}\\nPurpose: ${sectionPurpose}\\n\\nCANDIDATE CLAIMS:\\n\\n${claimsBlock}`;\n\n const ctrl = new AbortController();\n const t = setTimeout(() => ctrl.abort(), this.timeoutMs);\n let body: ChatResponse;\n try {\n const res = await this.fetchImpl(`${this.host}/api/chat`, {\n method: 'POST',\n signal: ctrl.signal,\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n model: this.model,\n stream: false,\n format: 'json',\n // Ollama defaults num_ctx to 4096 regardless of the model's\n // native window; review prompts with 20+ claims exceed that and\n // get silently truncated, which drops claim_ids and confuses the\n // model. Explicitly request 8K so paged windows fit cleanly.\n options: { num_ctx: 8192 },\n messages: [\n {\n role: 'system',\n content:\n this.mode === 'narrow_critic'\n ? NARROW_CRITIC_SYSTEM_PROMPT\n : GENERAL_SYSTEM_PROMPT,\n },\n { role: 'user', content: userMsg },\n ],\n }),\n });\n if (!res.ok) return { ok: false, error: `Ollama HTTP ${res.status}` };\n body = (await res.json()) as ChatResponse;\n } catch (err) {\n return { ok: false, error: err instanceof Error ? err.message : 'Ollama request failed' };\n } finally {\n clearTimeout(t);\n }\n\n const text = body.message?.content ?? body.response ?? '';\n let parsed: { findings?: unknown };\n try {\n parsed = JSON.parse(text) as { findings?: unknown };\n } catch {\n return { ok: false, error: 'Ollama response was not valid JSON' };\n }\n if (!Array.isArray(parsed.findings)) {\n return { ok: false, error: 'Ollama response did not contain a findings array' };\n }\n\n const drafts: DraftFinding[] = [];\n for (const raw of parsed.findings) {\n if (!raw || typeof raw !== 'object') continue;\n const r = raw as Record<string, unknown>;\n const category = asEnum<FindingCategory>(r.category, VALID_CATEGORIES, 'overgeneralized_claim');\n if (!VALID_CATEGORIES.includes(r.category as FindingCategory)) continue;\n const summary = typeof r.summary === 'string' && r.summary.trim().length > 0 ? r.summary.trim() : null;\n if (!summary) continue;\n drafts.push({\n category,\n severity: asEnum<FindingSeverity>(r.severity, VALID_SEVERITIES, 'warn'),\n summary,\n evidence: typeof r.evidence === 'string' ? r.evidence.trim() : '',\n required_action: typeof r.required_action === 'string' ? r.required_action.trim() : '',\n claim_ids: asStringArray(r.claim_ids),\n source_ids: asStringArray(r.source_ids),\n confidence: asEnum(r.confidence, VALID_CONFIDENCES, 'low'),\n });\n }\n return { ok: true, drafts };\n }\n\n async review(input: ReviewerInput): Promise<ReviewerResult> {\n if (input.candidateClaims.length === 0) {\n return { ok: true, drafts: [], method: 'ollama_intern_adversarial_review' };\n }\n\n const windows = pageClaimsForReview(input.candidateClaims, this.claimsPerWindow);\n const allDrafts: DraftFinding[] = [];\n const pageErrors: string[] = [];\n let pagesOk = 0;\n let rejectedCrossWindow = 0;\n\n for (const windowClaims of windows) {\n const validIds = new Set(windowClaims.map((c) => c.claim_id));\n const page = await this.reviewOnePage(\n windowClaims,\n input.section.id,\n input.section.purpose,\n );\n if (!page.ok) {\n pageErrors.push(page.error);\n continue;\n }\n pagesOk += 1;\n // Per-window claim_id validation: the model only saw `windowClaims`,\n // so any cited ID outside that set is a cross-window hallucination.\n // We trim invalid IDs and drop the finding entirely if no valid IDs\n // remain.\n for (const draft of page.drafts) {\n const kept = draft.claim_ids.filter((id) => validIds.has(id));\n if (kept.length === 0) {\n rejectedCrossWindow += 1;\n continue;\n }\n if (kept.length !== draft.claim_ids.length) rejectedCrossWindow += 1;\n allDrafts.push({ ...draft, claim_ids: kept });\n }\n }\n\n if (pagesOk === 0) {\n return {\n ok: false,\n error:\n pageErrors.length === 1\n ? pageErrors[0]!\n : `all ${windows.length} review pages failed (first: ${pageErrors[0] ?? 'unknown'})`,\n };\n }\n\n // Dedup findings across windows by (category, sorted claim_ids, summary\n // prefix). Adjacent windows can produce parallel findings about the same\n // claim cluster.\n const seen = new Set<string>();\n const drafts: DraftFinding[] = [];\n for (const d of allDrafts) {\n const key = `${d.category}|${[...d.claim_ids].sort().join(',')}|${d.summary.toLowerCase().slice(0, 80)}`;\n if (seen.has(key)) continue;\n seen.add(key);\n drafts.push(d);\n }\n\n const modeTag = this.mode === 'narrow_critic' ? '_narrow_critic' : '';\n const method =\n windows.length > 1\n ? `ollama_intern_adversarial_review_paged${modeTag}`\n : `ollama_intern_adversarial_review${modeTag}`;\n return { ok: true, drafts, method, rejected_ungrounded: rejectedCrossWindow };\n }\n}\n","import type { Reviewer } from '../types.js';\nimport { HeuristicReviewer } from './heuristic.js';\nimport { OllamaInternReviewer } from './ollama-intern.js';\n\nexport { HeuristicReviewer } from './heuristic.js';\nexport { OllamaInternReviewer } from './ollama-intern.js';\n\nexport function defaultReviewers(): Reviewer[] {\n return [new OllamaInternReviewer(), new HeuristicReviewer()];\n}\n\nexport async function pickReviewer(reviewers: Reviewer[]): Promise<Reviewer> {\n for (const r of reviewers) {\n if (await r.available()) return r;\n }\n throw new Error(\n 'No reviewer available. The HeuristicReviewer should always be available — this indicates a bug.',\n );\n}\n","import type { Claim } from '../claims/schema.js';\nimport type { SectionScopedWaiver } from '../intake/schema.js';\nimport type { ClaimReview, ReviewFinding } from './schema.js';\nimport type { ReviewDecision, ReviewerName } from './types.js';\n\nconst BLOCK_TO_DECISION: Record<string, ReviewDecision> = {\n ungrounded_excerpt: 'rejected',\n unsupported_claim: 'rejected',\n unmapped_contradiction: 'needs_contradiction_mapping',\n recommendation_exceeds_evidence: 'rejected',\n hidden_synthesis: 'needs_human_review',\n temporal_mismatch: 'needs_source_repair',\n definition_drift: 'needs_source_repair',\n scope_widening: 'needs_scope_repair',\n overgeneralized_claim: 'needs_scope_repair',\n source_quality_problem: 'needs_source_repair',\n source_cluster_monopoly: 'needs_source_repair',\n stale_claim: 'needs_source_repair',\n // Block-level overproduction means the cluster is redundant enough that the\n // reviewer demands human-led collapse before synthesis.\n claim_overproduction: 'needs_human_review',\n // Block-level low-value: explicitly excluded from synthesis. The claim is\n // grounded, but the reviewer is firm that it doesn't earn a slot.\n valid_but_low_value: 'rejected',\n};\n\nconst WARN_TO_DECISION: Record<string, ReviewDecision> = {\n overgeneralized_claim: 'needs_scope_repair',\n scope_widening: 'needs_scope_repair',\n source_quality_problem: 'needs_source_repair',\n source_cluster_monopoly: 'needs_source_repair',\n stale_claim: 'needs_source_repair',\n unmapped_contradiction: 'needs_contradiction_mapping',\n hidden_synthesis: 'needs_human_review',\n recommendation_exceeds_evidence: 'needs_human_review',\n // Warn-level overproduction routes to human review too — the claim itself\n // may be fine; the reviewer is signalling the cluster is synthesis noise.\n claim_overproduction: 'needs_human_review',\n // Warn-level low-value: borderline. Send to human review rather than auto\n // rejecting; the human decides whether to keep on the ledger or exclude.\n valid_but_low_value: 'needs_human_review',\n};\n\nconst DECISION_PRIORITY: ReviewDecision[] = [\n 'rejected',\n 'needs_contradiction_mapping',\n 'needs_source_repair',\n 'needs_scope_repair',\n 'needs_human_review',\n 'accepted_for_synthesis',\n];\n\nfunction pickHighestPriority(decisions: ReviewDecision[]): ReviewDecision {\n for (const d of DECISION_PRIORITY) {\n if (decisions.includes(d)) return d;\n }\n return 'accepted_for_synthesis';\n}\n\nexport function deriveClaimReviews(args: {\n claims: Claim[];\n findings: ReviewFinding[];\n reviewer: ReviewerName;\n reviewMethod: string;\n // v0.3.1+: section-scoped waivers active for this section. When a\n // min_independent_publishers waiver is present, the source_cluster_monopoly\n // finding remains in the ledger as a visible caveat but does NOT, by itself,\n // route per-claim decisions to needs_source_repair. Other source-quality\n // findings (per-claim source_quality_problem, scope_widening, etc.) continue\n // to apply normally — the waiver only neutralises the section-wide monopoly\n // signal that operators have explicitly disclosed and accepted.\n activeSectionWaivers?: SectionScopedWaiver[];\n}): ClaimReview[] {\n const { claims, findings, reviewer, reviewMethod, activeSectionWaivers } = args;\n const reviews: ClaimReview[] = [];\n const now = new Date().toISOString();\n\n // A section-scoped min_independent_publishers waiver neutralises the\n // section-wide source_cluster_monopoly signal at the per-claim\n // decision-routing layer. The finding remains in the ledger; only its\n // contribution to the decision is suppressed.\n const monopolyWaived =\n Array.isArray(activeSectionWaivers) &&\n activeSectionWaivers.some((w) => w.scope === 'min_independent_publishers');\n\n const isWaivedFinding = (f: ReviewFinding): boolean =>\n monopolyWaived && f.category === 'source_cluster_monopoly';\n\n for (const claim of claims) {\n const claimFindings = findings.filter((f) => f.claim_ids.includes(claim.claim_id));\n if (claimFindings.length === 0) {\n reviews.push({\n claim_id: claim.claim_id,\n decision: 'accepted_for_synthesis',\n reason: 'No findings recorded for this claim by the current reviewer.',\n finding_ids: [],\n reviewer,\n review_method: reviewMethod,\n created_at: now,\n });\n continue;\n }\n\n let decisions: ReviewDecision[] = [];\n for (const f of claimFindings) {\n if (isWaivedFinding(f)) continue;\n if (f.severity === 'block') {\n decisions.push(BLOCK_TO_DECISION[f.category] ?? 'rejected');\n } else if (f.severity === 'warn') {\n const d = WARN_TO_DECISION[f.category];\n if (d) decisions.push(d);\n }\n }\n if (decisions.length === 0) decisions.push('accepted_for_synthesis');\n\n // Conservative merge: a claim flagged ONLY by the narrow critic (and\n // no general / heuristic reviewer corroborated it) gets soft pressure,\n // not auto-rejection. The narrow critic's role is to surface risk; the\n // final reject must be backed by the general pass or a heuristic\n // structural check. This prevents a false-positive-prone critic from\n // killing claims unilaterally.\n const isCritic = (f: ReviewFinding): boolean =>\n typeof f.review_method === 'string' && f.review_method.endsWith('_narrow_critic');\n const onlyCritic =\n claimFindings.length > 0 && claimFindings.every(isCritic);\n if (onlyCritic) {\n decisions = decisions.map((d) =>\n d === 'rejected' ? 'needs_human_review' : d,\n );\n }\n\n const decision = pickHighestPriority(decisions);\n const reasonParts = claimFindings\n .filter((f) => f.severity !== 'info')\n .map((f) =>\n isWaivedFinding(f)\n ? `${f.category} (${f.severity}, waived)`\n : `${f.category} (${f.severity})`,\n );\n const reason =\n reasonParts.length > 0\n ? `Findings: ${reasonParts.join('; ')}.`\n : 'Only info-level findings; accepted.';\n\n reviews.push({\n claim_id: claim.claim_id,\n decision,\n reason,\n finding_ids: claimFindings.map((f) => f.finding_id),\n reviewer,\n review_method: reviewMethod,\n created_at: now,\n });\n }\n\n return reviews;\n}\n","import type { ReviewSnapshot } from './schema.js';\n\nconst SEVERITY_GLYPH: Record<string, string> = {\n info: '[INFO]',\n warn: '[WARN]',\n block: '[BLOCK]',\n};\n\nconst DECISION_GLYPH: Record<string, string> = {\n accepted_for_synthesis: '[ACCEPTED]',\n rejected: '[REJECTED]',\n needs_scope_repair: '[NEEDS-SCOPE-REPAIR]',\n needs_source_repair: '[NEEDS-SOURCE-REPAIR]',\n needs_contradiction_mapping: '[NEEDS-CONTRADICTION-MAPPING]',\n needs_human_review: '[NEEDS-HUMAN-REVIEW]',\n};\n\nexport function renderReviewMarkdown(snapshot: ReviewSnapshot): string {\n const lines: string[] = [];\n lines.push(`# Adversarial Review: ${snapshot.section_id}`);\n lines.push('');\n lines.push(`**Reviewer:** ${snapshot.reviewer} (${snapshot.review_method})`);\n lines.push(`**Reviewed at:** ${snapshot.reviewed_at}`);\n lines.push(`**Candidate claims:** ${snapshot.candidate_claims}`);\n lines.push(`**Findings:** ${snapshot.findings.length} (block: ${snapshot.severity_counts.block ?? 0}, warn: ${snapshot.severity_counts.warn ?? 0}, info: ${snapshot.severity_counts.info ?? 0})`);\n lines.push(`**LLM findings rejected (ungrounded):** ${snapshot.llm_findings_rejected_ungrounded}`);\n lines.push('');\n\n lines.push('> Adversarial review judges research integrity. It does not synthesize, rewrite source truth, or erase extraction history. Decisions below are review truth — claims.jsonl is unchanged.');\n lines.push('');\n\n lines.push('## Effective decisions');\n lines.push('');\n const decisions = snapshot.decision_counts;\n for (const d of [\n 'rejected',\n 'needs_contradiction_mapping',\n 'needs_source_repair',\n 'needs_scope_repair',\n 'needs_human_review',\n 'accepted_for_synthesis',\n ]) {\n const n = decisions[d as keyof typeof decisions] ?? 0;\n if (n > 0) lines.push(`- ${DECISION_GLYPH[d] ?? d}: ${n}`);\n }\n if (snapshot.findings.length === 0) {\n lines.push('');\n lines.push('No findings produced. A clean review is not proof of completeness — it means the configured reviewer found nothing of integrity concern.');\n }\n lines.push('');\n\n if (snapshot.findings.length > 0) {\n lines.push('## Findings');\n lines.push('');\n for (const f of snapshot.findings) {\n const glyph = SEVERITY_GLYPH[f.severity] ?? `[${f.severity.toUpperCase()}]`;\n lines.push(`### ${glyph} ${f.category} (${f.finding_id})`);\n lines.push('');\n lines.push(f.summary);\n lines.push('');\n lines.push(`- **Claim IDs:** ${f.claim_ids.map((c) => `\\`${c}\\``).join(', ') || '(none)'}`);\n lines.push(`- **Source IDs:** ${f.source_ids.map((s) => `\\`${s}\\``).join(', ') || '(none)'}`);\n lines.push(`- **Required action:** ${f.required_action || '(unspecified)'}`);\n lines.push(`- **Reviewer:** ${f.reviewer} (${f.review_method})`);\n lines.push(`- **Confidence:** ${f.confidence}`);\n if (f.evidence) lines.push(`- **Evidence:** ${f.evidence}`);\n lines.push('');\n }\n }\n\n if (snapshot.claim_reviews.length > 0) {\n lines.push('## Claim review decisions');\n lines.push('');\n for (const r of snapshot.claim_reviews) {\n const glyph = DECISION_GLYPH[r.decision] ?? `[${r.decision.toUpperCase()}]`;\n lines.push(`### ${glyph} \\`${r.claim_id}\\``);\n lines.push('');\n lines.push(`${r.reason}`);\n if (r.finding_ids.length > 0) {\n lines.push('');\n lines.push(`Cites findings: ${r.finding_ids.map((id) => `\\`${id}\\``).join(', ')}.`);\n }\n lines.push('');\n }\n }\n\n return lines.join('\\n');\n}\n","import { createHash } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { appendFile, mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { join, resolve } from 'node:path';\nimport { parse as yamlParse, stringify as yamlStringify } from 'yaml';\n\nimport { PackNotFoundError, SectionNotFoundError } from '../errors.js';\nimport { ResearchYamlSchema, type ResearchYaml, type Section } from '../intake/schema.js';\nimport { ClaimSchema, type Claim } from '../claims/schema.js';\nimport { ContradictionSchema, type Contradiction } from '../contradictions/schema.js';\nimport { ContradictionResolutionSchema, type ContradictionResolution } from '../contradictions/resolution-schema.js';\nimport {\n FetchReceiptSchema,\n SourceCardSchema,\n type FetchReceipt,\n type SourceCard,\n} from '../sources/schema.js';\nimport { ExcerptSchema, type Excerpt } from '../sources/excerpts/schema.js';\nimport { ledgerPathFor } from '../sources/excerpts/ledger.js';\nimport { SectionGateResultSchema, type SectionGateResult } from '../gates/schema.js';\n\nimport {\n DEFAULT_PROFILE,\n profileDir,\n readActiveProfile,\n} from './profiles.js';\n\nimport {\n defaultReviewers,\n pickReviewer,\n} from './reviewers/index.js';\nimport { deriveClaimReviews } from './decision.js';\nimport { renderReviewMarkdown } from './markdown.js';\nimport {\n ClaimReviewSchema,\n ReviewFindingSchema,\n ReviewSnapshotSchema,\n type ClaimReview,\n type ReviewFinding,\n type ReviewSnapshot,\n} from './schema.js';\nimport type {\n DraftFinding,\n FindingSeverity,\n ReviewDecision,\n ReviewerName,\n RunReviewOptions,\n RunReviewSummary,\n} from './types.js';\n\nasync function readJsonl<T>(\n packPath: string,\n rel: string,\n parse: (raw: unknown) => T,\n): Promise<T[]> {\n const path = join(packPath, rel);\n if (!existsSync(path)) return [];\n const text = await readFile(path, 'utf8');\n const out: T[] = [];\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n out.push(parse(JSON.parse(line)));\n }\n return out;\n}\n\nasync function readSourceCards(packPath: string): Promise<SourceCard[]> {\n const dir = join(packPath, 'evidence', 'source-cards');\n if (!existsSync(dir)) return [];\n const { readdir } = await import('node:fs/promises');\n const entries = await readdir(dir);\n const cards: SourceCard[] = [];\n for (const entry of entries) {\n if (!entry.endsWith('.json')) continue;\n const text = await readFile(join(dir, entry), 'utf8');\n cards.push(SourceCardSchema.parse(JSON.parse(text)));\n }\n return cards;\n}\n\nasync function readGateResult(\n packPath: string,\n sectionId: string,\n): Promise<SectionGateResult | null> {\n const path = join(packPath, 'audits', `${sectionId}-gate.json`);\n if (!existsSync(path)) return null;\n const text = await readFile(path, 'utf8');\n return SectionGateResultSchema.parse(JSON.parse(text));\n}\n\nasync function readBriefText(\n packPath: string,\n sectionId: string,\n): Promise<string | null> {\n const path = join(packPath, 'sections', sectionId, 'brief.md');\n if (!existsSync(path)) return null;\n return readFile(path, 'utf8');\n}\n\nasync function readRawTextBySource(\n packPath: string,\n receipts: FetchReceipt[],\n): Promise<Map<string, string>> {\n const map = new Map<string, string>();\n for (const r of receipts) {\n if (r.fetch_outcome !== 'ok' || !r.raw_text_path) continue;\n const path = join(packPath, r.raw_text_path);\n if (!existsSync(path)) continue;\n if (map.has(r.source_id)) continue;\n map.set(r.source_id, await readFile(path, 'utf8'));\n }\n return map;\n}\n\n// Load span-first excerpt ledgers for every source cited by the section's\n// claims. Reviewers use this for structural grounding checks instead of\n// re-normalising raw text.\nasync function readExcerptsBySource(\n packPath: string,\n claims: Claim[],\n): Promise<Map<string, Map<string, Excerpt>>> {\n const out = new Map<string, Map<string, Excerpt>>();\n const sourceIds = new Set<string>();\n for (const c of claims) for (const sid of c.source_ids) sourceIds.add(sid);\n for (const sid of sourceIds) {\n const path = ledgerPathFor(packPath, sid);\n if (!existsSync(path)) continue;\n const text = await readFile(path, 'utf8');\n const index = new Map<string, Excerpt>();\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n const e = ExcerptSchema.parse(JSON.parse(line));\n index.set(e.excerpt_id, e);\n } catch {\n /* skip malformed line */\n }\n }\n if (index.size > 0) out.set(sid, index);\n }\n return out;\n}\n\nfunction makeFindingId(args: {\n sectionId: string;\n category: string;\n claimIds: string[];\n reviewer: ReviewerName;\n}): string {\n const sortedClaimIds = [...args.claimIds].sort().join(',');\n const hash = createHash('sha256')\n .update(`${args.sectionId}|${args.category}|${sortedClaimIds}|${args.reviewer}`)\n .digest('hex')\n .slice(0, 12);\n return `fnd_${hash}`;\n}\n\nfunction isValidReference(\n draft: DraftFinding,\n knownClaimIds: Set<string>,\n knownSourceIds: Set<string>,\n): boolean {\n if (draft.claim_ids.length === 0) return false;\n for (const cid of draft.claim_ids) {\n if (!knownClaimIds.has(cid)) return false;\n }\n for (const sid of draft.source_ids) {\n if (!knownSourceIds.has(sid)) return false;\n }\n return true;\n}\n\nfunction buildFinding(args: {\n draft: DraftFinding;\n sectionId: string;\n reviewer: ReviewerName;\n reviewMethod: string;\n}): ReviewFinding {\n const { draft, sectionId, reviewer, reviewMethod } = args;\n return ReviewFindingSchema.parse({\n finding_id: makeFindingId({\n sectionId,\n category: draft.category,\n claimIds: draft.claim_ids,\n reviewer,\n }),\n section_id: sectionId,\n claim_ids: draft.claim_ids,\n source_ids: draft.source_ids,\n category: draft.category,\n severity: draft.severity,\n summary: draft.summary,\n evidence: draft.evidence,\n required_action: draft.required_action,\n reviewer,\n review_method: reviewMethod,\n confidence: draft.confidence,\n created_at: new Date().toISOString(),\n });\n}\n\nasync function loadResearchYaml(packPath: string): Promise<ResearchYaml> {\n const yamlPath = join(packPath, 'research.yaml');\n if (!existsSync(yamlPath)) throw new PackNotFoundError(packPath);\n const text = await readFile(yamlPath, 'utf8');\n return ResearchYamlSchema.parse(yamlParse(text));\n}\n\nasync function maybePromoteToReviewed(\n packPath: string,\n sectionId: string,\n allAccepted: boolean,\n): Promise<boolean> {\n if (!allAccepted) return false;\n const yamlPath = join(packPath, 'research.yaml');\n const text = await readFile(yamlPath, 'utf8');\n const research = ResearchYamlSchema.parse(yamlParse(text));\n const idx = research.sections.findIndex((s) => s.id === sectionId);\n if (idx < 0) return false;\n const current = research.sections[idx]!;\n if (current.status !== 'gated') return false;\n research.sections[idx] = { ...current, status: 'reviewed' };\n await writeFile(yamlPath, yamlStringify(research, { lineWidth: 0 }), 'utf8');\n return true;\n}\n\nexport async function review(options: RunReviewOptions): Promise<RunReviewSummary> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n if (!existsSync(join(packPath, 'research.yaml'))) throw new PackNotFoundError(packPath);\n const sectionDir = join(packPath, 'sections', options.sectionId);\n if (!existsSync(sectionDir)) throw new SectionNotFoundError(options.sectionId);\n\n const research = await loadResearchYaml(packPath);\n const section: Section | undefined = research.sections.find((s) => s.id === options.sectionId);\n if (!section) throw new SectionNotFoundError(options.sectionId);\n\n const claims = await readJsonl<Claim>(packPath, `sections/${options.sectionId}/claims.jsonl`, (r) => ClaimSchema.parse(r));\n let candidateClaims = claims.filter((c) => c.review_state === 'candidate');\n if (options.triagedOnly) {\n const { readTriagedClaimIds } = await import('../triage/run.js');\n const allowed = await readTriagedClaimIds(packPath, options.sectionId);\n candidateClaims = candidateClaims.filter((c) => allowed.has(c.claim_id));\n }\n const sources = await readSourceCards(packPath);\n const receipts = await readJsonl<FetchReceipt>(packPath, 'evidence/fetch-log.jsonl', (r) => FetchReceiptSchema.parse(r));\n const contradictions = await readJsonl<Contradiction>(packPath, `sections/${options.sectionId}/contradictions.jsonl`, (r) => ContradictionSchema.parse(r));\n const resolutions = await readJsonl<ContradictionResolution>(packPath, `sections/${options.sectionId}/contradiction-resolutions.jsonl`, (r) => ContradictionResolutionSchema.parse(r));\n const gateResult = await readGateResult(packPath, options.sectionId);\n const rawTextBySourceId = await readRawTextBySource(packPath, receipts);\n const excerptsBySourceId = await readExcerptsBySource(packPath, claims);\n const briefText = await readBriefText(packPath, options.sectionId);\n\n const reviewers = options.reviewers ?? defaultReviewers();\n\n // Multi-pass: run every available reviewer and merge findings. The classic\n // shape is general LLM + narrow-critic LLM + heuristic — each catches a\n // different failure mode, and the merger is append-only with dedup.\n if (options.multiPass) {\n return runMultiPassReview({\n packPath,\n options,\n reviewers,\n research,\n section,\n claims,\n candidateClaims,\n sources,\n receipts,\n contradictions,\n resolutions,\n gateResult,\n rawTextBySourceId,\n excerptsBySourceId,\n briefText,\n });\n }\n\n const reviewer = await pickReviewer(reviewers);\n\n const result = await reviewer.review({\n research,\n section,\n candidateClaims,\n sources,\n receipts,\n contradictions,\n resolutions,\n excerptsBySourceId,\n gateResult,\n rawTextBySourceId,\n briefText,\n });\n\n if (!result.ok) {\n // Reviewer-level failure (e.g. Ollama HTTP error). Fall back to heuristic if available.\n const heuristic = reviewers.find((r) => r.name === 'heuristic');\n if (!heuristic || heuristic === reviewer) {\n throw new Error(`Reviewer \"${reviewer.name}\" failed and no fallback available: ${result.error}`);\n }\n return reviewWithSpecificReviewer({\n packPath,\n options,\n reviewer: heuristic,\n research,\n section,\n claims,\n candidateClaims,\n sources,\n receipts,\n contradictions,\n resolutions,\n gateResult,\n rawTextBySourceId,\n excerptsBySourceId,\n briefText,\n });\n }\n\n const knownClaimIds = new Set(claims.map((c) => c.claim_id));\n const knownSourceIds = new Set(sources.map((s) => s.source_id));\n let llmFindingsRejected = 0;\n const acceptedDrafts: DraftFinding[] = [];\n for (const d of result.drafts) {\n if (reviewer.name === 'ollama-intern' && !isValidReference(d, knownClaimIds, knownSourceIds)) {\n llmFindingsRejected += 1;\n continue;\n }\n acceptedDrafts.push(d);\n }\n\n return finalizeReview({\n packPath,\n sectionId: options.sectionId,\n reviewer: reviewer.name,\n reviewMethod: result.method,\n candidateClaims,\n drafts: acceptedDrafts,\n llmFindingsRejected,\n profile: options.profile ?? DEFAULT_PROFILE,\n research,\n });\n}\n\ninterface ReviewWithSpecificReviewerArgs {\n packPath: string;\n options: RunReviewOptions;\n reviewer: ReturnType<typeof pickReviewer> extends Promise<infer T> ? T : never;\n research: ResearchYaml;\n section: Section;\n claims: Claim[];\n candidateClaims: Claim[];\n sources: SourceCard[];\n receipts: FetchReceipt[];\n contradictions: Contradiction[];\n resolutions?: ContradictionResolution[];\n gateResult: SectionGateResult | null;\n rawTextBySourceId: Map<string, string>;\n excerptsBySourceId: Map<string, Map<string, Excerpt>>;\n briefText: string | null;\n}\n\ninterface MultiPassArgs extends Omit<ReviewWithSpecificReviewerArgs, 'reviewer'> {\n reviewers: ReadonlyArray<\n ReturnType<typeof pickReviewer> extends Promise<infer T> ? T : never\n >;\n}\n\n// Run every available reviewer in sequence, merging findings into one\n// append-only ledger. Dedup by (claim_ids sorted, category, summary prefix).\n// The merged \"method\" tag concatenates each reviewer's reported method so\n// downstream consumers can see exactly which passes contributed.\nasync function runMultiPassReview(args: MultiPassArgs): Promise<RunReviewSummary> {\n const knownClaimIds = new Set(args.claims.map((c) => c.claim_id));\n const knownSourceIds = new Set(args.sources.map((s) => s.source_id));\n\n const allDrafts: DraftFinding[] = [];\n const methods: string[] = [];\n const failedReviewers: string[] = [];\n let llmFindingsRejected = 0;\n let pickedReviewerName: ReviewerName = 'heuristic';\n\n for (const reviewer of args.reviewers) {\n if (!(await reviewer.available())) continue;\n const result = await reviewer.review({\n research: args.research,\n section: args.section,\n candidateClaims: args.candidateClaims,\n sources: args.sources,\n receipts: args.receipts,\n contradictions: args.contradictions,\n resolutions: args.resolutions,\n excerptsBySourceId: args.excerptsBySourceId,\n gateResult: args.gateResult,\n rawTextBySourceId: args.rawTextBySourceId,\n briefText: args.briefText,\n });\n if (!result.ok) {\n failedReviewers.push(`${reviewer.name}:${result.error}`);\n continue;\n }\n methods.push(result.method);\n if (result.rejected_ungrounded) llmFindingsRejected += result.rejected_ungrounded;\n // The reviewer \"name\" recorded on the section is the one that contributed\n // the most findings — used for the snapshot's reviewer field. Default to\n // heuristic; let any LLM pass override.\n if (reviewer.name === 'ollama-intern') pickedReviewerName = 'ollama-intern';\n for (const d of result.drafts) {\n if (\n reviewer.name === 'ollama-intern' &&\n !isValidReference(d, knownClaimIds, knownSourceIds)\n ) {\n llmFindingsRejected += 1;\n continue;\n }\n allDrafts.push(d);\n }\n }\n\n if (allDrafts.length === 0 && failedReviewers.length === args.reviewers.length) {\n throw new Error(\n `Multi-pass review: every reviewer failed. ${failedReviewers.join(' | ')}`,\n );\n }\n\n // Dedup findings by (sorted claim_ids, category, summary prefix). Two\n // reviewers can flag the same problem; the section ledger should record it\n // once, not twice.\n const seen = new Set<string>();\n const merged: DraftFinding[] = [];\n for (const d of allDrafts) {\n const key = `${d.category}|${[...d.claim_ids].sort().join(',')}|${d.summary.toLowerCase().slice(0, 80)}`;\n if (seen.has(key)) continue;\n seen.add(key);\n merged.push(d);\n }\n\n return finalizeReview({\n packPath: args.packPath,\n sectionId: args.options.sectionId,\n reviewer: pickedReviewerName,\n reviewMethod: methods.length > 0 ? `multi_pass(${methods.join(' + ')})` : 'multi_pass(empty)',\n candidateClaims: args.candidateClaims,\n drafts: merged,\n llmFindingsRejected,\n profile: args.options.profile ?? DEFAULT_PROFILE,\n research: args.research,\n });\n}\n\nasync function reviewWithSpecificReviewer(args: ReviewWithSpecificReviewerArgs): Promise<RunReviewSummary> {\n const result = await args.reviewer.review({\n research: args.research,\n section: args.section,\n candidateClaims: args.candidateClaims,\n sources: args.sources,\n receipts: args.receipts,\n contradictions: args.contradictions,\n resolutions: args.resolutions,\n gateResult: args.gateResult,\n rawTextBySourceId: args.rawTextBySourceId,\n excerptsBySourceId: args.excerptsBySourceId,\n briefText: args.briefText,\n });\n if (!result.ok) {\n throw new Error(`Fallback reviewer \"${args.reviewer.name}\" also failed: ${result.error}`);\n }\n return finalizeReview({\n packPath: args.packPath,\n sectionId: args.options.sectionId,\n reviewer: args.reviewer.name,\n reviewMethod: result.method,\n candidateClaims: args.candidateClaims,\n drafts: result.drafts,\n llmFindingsRejected: 0,\n profile: args.options.profile ?? DEFAULT_PROFILE,\n research: args.research,\n });\n}\n\ninterface FinalizeArgs {\n packPath: string;\n sectionId: string;\n reviewer: ReviewerName;\n reviewMethod: string;\n candidateClaims: Claim[];\n drafts: DraftFinding[];\n llmFindingsRejected: number;\n profile: string;\n // v0.3.1+: research context for resolving active section-scoped waivers.\n // Filtered against args.sectionId before passing to deriveClaimReviews.\n research: ResearchYaml;\n}\n\nasync function finalizeReview(args: FinalizeArgs): Promise<RunReviewSummary> {\n const findings: ReviewFinding[] = args.drafts.map((d) =>\n buildFinding({\n draft: d,\n sectionId: args.sectionId,\n reviewer: args.reviewer,\n reviewMethod: args.reviewMethod,\n }),\n );\n // Dedup by finding_id within this run\n const seen = new Set<string>();\n const dedupedFindings: ReviewFinding[] = [];\n let dedupedCount = 0;\n for (const f of findings) {\n if (seen.has(f.finding_id)) {\n dedupedCount += 1;\n continue;\n }\n seen.add(f.finding_id);\n dedupedFindings.push(f);\n }\n\n const activeSectionWaivers = args.research.primary_source_waiver.section_waivers.filter(\n (w) => w.section_id === args.sectionId,\n );\n\n const claimReviews: ClaimReview[] = deriveClaimReviews({\n claims: args.candidateClaims,\n findings: dedupedFindings,\n reviewer: args.reviewer,\n reviewMethod: args.reviewMethod,\n activeSectionWaivers,\n });\n\n const decisionCounts: Record<ReviewDecision, number> = {\n accepted_for_synthesis: 0,\n rejected: 0,\n needs_scope_repair: 0,\n needs_source_repair: 0,\n needs_contradiction_mapping: 0,\n needs_human_review: 0,\n };\n for (const r of claimReviews) decisionCounts[r.decision] += 1;\n\n const severityCounts: Record<FindingSeverity, number> = { info: 0, warn: 0, block: 0 };\n for (const f of dedupedFindings) severityCounts[f.severity] += 1;\n\n const allAccepted =\n args.candidateClaims.length > 0 &&\n claimReviews.every((r) => r.decision === 'accepted_for_synthesis');\n // Only promote section status when this run is on the active profile —\n // calibration / A/B runs must never touch section state.\n const activeProfileForPromote = await readActiveProfile(args.packPath, args.sectionId);\n const promoteEligible =\n args.profile === activeProfileForPromote ||\n (activeProfileForPromote === DEFAULT_PROFILE && args.profile === DEFAULT_PROFILE);\n const promoted = promoteEligible\n ? await maybePromoteToReviewed(args.packPath, args.sectionId, allAccepted)\n : false;\n\n const snapshot: ReviewSnapshot = ReviewSnapshotSchema.parse({\n section_id: args.sectionId,\n reviewer: args.reviewer,\n review_method: args.reviewMethod,\n reviewed_at: new Date().toISOString(),\n candidate_claims: args.candidateClaims.length,\n findings: dedupedFindings,\n claim_reviews: claimReviews,\n decision_counts: decisionCounts,\n severity_counts: severityCounts,\n llm_findings_rejected_ungrounded: args.llmFindingsRejected,\n promoted_to_reviewed: promoted,\n });\n\n // ALWAYS write the profile-scoped artifacts: even non-active runs leave a\n // full record under sections/<id>/reviews/<profile>/ for calibration.\n const profDir = profileDir(args.packPath, args.sectionId, args.profile);\n await mkdir(profDir, { recursive: true });\n await writeFile(join(profDir, 'review.json'), JSON.stringify(snapshot, null, 2), 'utf8');\n await writeFile(join(profDir, 'review.md'), renderReviewMarkdown(snapshot), 'utf8');\n const profileFindingsPath = join(profDir, 'findings.jsonl');\n for (const f of dedupedFindings) {\n await appendFile(profileFindingsPath, JSON.stringify(f) + '\\n', 'utf8');\n }\n const profileReviewsPath = join(profDir, 'claim-reviews.jsonl');\n for (const r of claimReviews) {\n await appendFile(profileReviewsPath, JSON.stringify(ClaimReviewSchema.parse(r)) + '\\n', 'utf8');\n }\n\n // Mirror to canonical paths ONLY when this profile is the active one (or\n // there is no active profile and we are running the implicit default).\n // This is what stops A/B experiments from corrupting the section's\n // effective review state.\n const activeProfile = await readActiveProfile(args.packPath, args.sectionId);\n const isActive = args.profile === activeProfile || (activeProfile === DEFAULT_PROFILE && args.profile === DEFAULT_PROFILE);\n if (isActive) {\n const auditsDir = join(args.packPath, 'audits');\n await mkdir(auditsDir, { recursive: true });\n await writeFile(\n join(auditsDir, `${args.sectionId}-review.json`),\n JSON.stringify(snapshot, null, 2),\n 'utf8',\n );\n await writeFile(\n join(auditsDir, `${args.sectionId}-review.md`),\n renderReviewMarkdown(snapshot),\n 'utf8',\n );\n const findingsPath = join(auditsDir, `${args.sectionId}-findings.jsonl`);\n for (const f of dedupedFindings) {\n await appendFile(findingsPath, JSON.stringify(f) + '\\n', 'utf8');\n }\n const reviewsPath = join(args.packPath, 'sections', args.sectionId, 'claim-reviews.jsonl');\n for (const r of claimReviews) {\n await appendFile(reviewsPath, JSON.stringify(ClaimReviewSchema.parse(r)) + '\\n', 'utf8');\n }\n }\n\n return {\n sectionId: args.sectionId,\n reviewer: args.reviewer,\n reviewMethod: args.reviewMethod,\n candidateClaims: args.candidateClaims.length,\n findingsAdded: dedupedFindings.length,\n findingsDeduped: dedupedCount,\n llmFindingsRejected: args.llmFindingsRejected,\n decisions: decisionCounts,\n blockingFindings: dedupedFindings.filter((f) => f.severity === 'block').length,\n promotedToReviewed: promoted,\n };\n}\n","import { existsSync } from 'node:fs';\nimport { copyFile, mkdir, readFile, writeFile, appendFile } from 'node:fs/promises';\nimport { join, resolve } from 'node:path';\nimport { parse as yamlParse, stringify as yamlStringify } from 'yaml';\n\nimport { PackNotFoundError, SectionNotFoundError } from '../errors.js';\nimport { ResearchYamlSchema } from '../intake/schema.js';\nimport {\n DEFAULT_PROFILE,\n isValidProfileName,\n profileDir,\n reviewActivePath,\n writeActiveProfile,\n type PromotionCalibrationSummary,\n} from './profiles.js';\nimport { ReviewSnapshotSchema } from './schema.js';\nimport { renderReviewMarkdown } from './markdown.js';\n\nexport interface PromoteOptions {\n sectionId: string;\n packPath?: string;\n profile: string;\n // Free-text rationale recorded on review-active.json. Strongly encouraged\n // — explains WHY this profile became section truth, not just which one.\n promotionReason?: string;\n // Optional calibration evidence captured at promotion time. The profile/\n // promote layer is provenance-first: future gate/audit/freeze can show\n // not just \"this is active\" but \"this was trusted because <numbers>\".\n calibrationSummary?: PromotionCalibrationSummary | null;\n // When true, also bump section status from gated → reviewed if every claim\n // in the promoted profile is accepted_for_synthesis.\n promoteSectionStatus?: boolean;\n now?: () => Date;\n}\n\nexport interface PromoteResult {\n packPath: string;\n sectionId: string;\n profile: string;\n promoted_at: string;\n promoted_method: string;\n promoted_reviewer: string;\n canonical_files_updated: string[];\n section_status_bumped: boolean;\n}\n\n// Promote a review profile: copy its artifacts to the canonical paths\n// (audits/<id>-review.{json,md}, audits/<id>-findings.jsonl,\n// sections/<id>/claim-reviews.jsonl) and write\n// sections/<id>/review-active.json. Until promoted, a profile is\n// calibration evidence; after, it is section truth.\nexport async function promote(options: PromoteOptions): Promise<PromoteResult> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n if (!existsSync(join(packPath, 'research.yaml'))) throw new PackNotFoundError(packPath);\n if (!existsSync(join(packPath, 'sections', options.sectionId)))\n throw new SectionNotFoundError(options.sectionId);\n if (!isValidProfileName(options.profile)) {\n throw new Error(\n `Invalid profile name \"${options.profile}\". Use a kebab/snake-case slug.`,\n );\n }\n const dir = profileDir(packPath, options.sectionId, options.profile);\n const reviewJsonPath = join(dir, 'review.json');\n if (!existsSync(reviewJsonPath)) {\n throw new Error(\n `Profile \"${options.profile}\" not found at ${dir}. Run \\`research-os review --profile ${options.profile}\\` first.`,\n );\n }\n\n // Load the profile's snapshot to discover reviewer/method for the receipt.\n const snapshot = ReviewSnapshotSchema.parse(\n JSON.parse(await readFile(reviewJsonPath, 'utf8')),\n );\n\n // Copy review.json + review.md to canonical audits/.\n const auditsDir = join(packPath, 'audits');\n await mkdir(auditsDir, { recursive: true });\n const canonicalReviewJson = join(auditsDir, `${options.sectionId}-review.json`);\n const canonicalReviewMd = join(auditsDir, `${options.sectionId}-review.md`);\n await copyFile(reviewJsonPath, canonicalReviewJson);\n await writeFile(canonicalReviewMd, renderReviewMarkdown(snapshot), 'utf8');\n\n // The findings.jsonl and claim-reviews.jsonl ledgers are append-only on\n // canonical. To make this profile's decisions effective, we re-append\n // every record from the profile so they are the LATEST writes.\n const canonicalFindings = join(auditsDir, `${options.sectionId}-findings.jsonl`);\n const profileFindings = join(dir, 'findings.jsonl');\n const writtenFindings: string[] = [];\n if (existsSync(profileFindings)) {\n const text = await readFile(profileFindings, 'utf8');\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n await appendFile(canonicalFindings, line + '\\n', 'utf8');\n writtenFindings.push(line);\n }\n }\n const canonicalReviews = join(packPath, 'sections', options.sectionId, 'claim-reviews.jsonl');\n const profileReviews = join(dir, 'claim-reviews.jsonl');\n if (existsSync(profileReviews)) {\n const text = await readFile(profileReviews, 'utf8');\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n await appendFile(canonicalReviews, line + '\\n', 'utf8');\n }\n }\n\n // Mark this profile as active. Carry promotion provenance so downstream\n // consumers can explain why the reviewer is trusted, not just point at\n // which one ran.\n const stamp = (options.now ?? (() => new Date()))();\n await writeActiveProfile(packPath, options.sectionId, {\n active_profile: options.profile,\n promoted_at: stamp.toISOString(),\n promoted_method: snapshot.review_method,\n promoted_reviewer: snapshot.reviewer,\n promotion_reason:\n options.promotionReason && options.promotionReason.trim().length >= 8\n ? options.promotionReason.trim()\n : `promoted from sections/${options.sectionId}/reviews/${options.profile}/`,\n calibration_summary: options.calibrationSummary ?? null,\n });\n\n let sectionStatusBumped = false;\n if (options.promoteSectionStatus) {\n const yamlPath = join(packPath, 'research.yaml');\n const research = ResearchYamlSchema.parse(yamlParse(await readFile(yamlPath, 'utf8')));\n const idx = research.sections.findIndex((s) => s.id === options.sectionId);\n if (idx >= 0 && research.sections[idx]!.status === 'gated') {\n const allAccepted =\n snapshot.candidate_claims > 0 &&\n snapshot.claim_reviews.every((r) => r.decision === 'accepted_for_synthesis');\n if (allAccepted) {\n research.sections[idx] = { ...research.sections[idx]!, status: 'reviewed' };\n await writeFile(yamlPath, yamlStringify(research, { lineWidth: 0 }), 'utf8');\n sectionStatusBumped = true;\n }\n }\n }\n\n return {\n packPath,\n sectionId: options.sectionId,\n profile: options.profile,\n promoted_at: stamp.toISOString(),\n promoted_method: snapshot.review_method,\n promoted_reviewer: snapshot.reviewer,\n canonical_files_updated: [\n canonicalReviewJson,\n canonicalReviewMd,\n canonicalReviews,\n canonicalFindings,\n reviewActivePath(packPath, options.sectionId),\n ],\n section_status_bumped: sectionStatusBumped,\n };\n}\n\n// Convenience for callers: `default` is implicitly the active profile when\n// review-active.json doesn't exist. Callers can use this to special-case\n// pre-profile packs.\nexport const PROMOTE_DEFAULT_PROFILE = DEFAULT_PROFILE;\n","export { review } from './run.js';\nexport {\n HeuristicReviewer,\n OllamaInternReviewer,\n defaultReviewers,\n pickReviewer,\n} from './reviewers/index.js';\nexport { promote, type PromoteOptions, type PromoteResult } from './promote.js';\nexport {\n DEFAULT_PROFILE,\n ReviewActiveSchema,\n type ReviewActive,\n readActiveProfile,\n writeActiveProfile,\n profileDir,\n reviewActivePath,\n isValidProfileName,\n} from './profiles.js';\nexport { deriveClaimReviews } from './decision.js';\nexport { renderReviewMarkdown } from './markdown.js';\nexport {\n FindingCategorySchema,\n FindingSeveritySchema,\n ReviewerNameSchema,\n ReviewDecisionSchema,\n ReviewConfidenceSchema,\n ReviewFindingSchema,\n ClaimReviewSchema,\n ReviewSnapshotSchema,\n type ReviewFinding,\n type ClaimReview,\n type ReviewSnapshot,\n} from './schema.js';\nexport type {\n FindingCategory,\n FindingSeverity,\n ReviewerName,\n ReviewDecision,\n DraftFinding,\n ReviewerResult,\n ReviewerInput,\n Reviewer,\n RunReviewOptions,\n RunReviewSummary,\n} from './types.js';\n","export const SCHEMA_VERSION = 1;\n\nexport const DDL_STATEMENTS: string[] = [\n `CREATE TABLE IF NOT EXISTS meta (\n key TEXT PRIMARY KEY,\n value TEXT NOT NULL\n )`,\n\n `CREATE TABLE IF NOT EXISTS artifacts (\n artifact_id TEXT PRIMARY KEY,\n artifact_type TEXT NOT NULL,\n section_id TEXT,\n path TEXT NOT NULL,\n sha256 TEXT,\n bytes INTEGER,\n indexed_at TEXT NOT NULL\n )`,\n\n `CREATE TABLE IF NOT EXISTS sections (\n section_id TEXT PRIMARY KEY,\n purpose TEXT,\n status TEXT,\n max_time_minutes INTEGER,\n min_sources INTEGER,\n primary_sources_required INTEGER,\n contradictions_required INTEGER,\n indexed_at TEXT NOT NULL\n )`,\n\n `CREATE TABLE IF NOT EXISTS sources (\n source_id TEXT PRIMARY KEY,\n section_id TEXT,\n url TEXT,\n publisher TEXT,\n source_type TEXT,\n relevance TEXT,\n asserts TEXT,\n scope TEXT,\n not_field TEXT,\n fetched_at TEXT,\n published_at TEXT,\n artifact_path TEXT NOT NULL,\n indexed_at TEXT NOT NULL\n )`,\n\n `CREATE TABLE IF NOT EXISTS claims (\n claim_id TEXT PRIMARY KEY,\n section_id TEXT NOT NULL,\n source_ids_json TEXT NOT NULL,\n asserts TEXT NOT NULL,\n scope TEXT,\n not_field TEXT,\n evidence_excerpt TEXT NOT NULL,\n confidence TEXT,\n extractor TEXT,\n extraction_method TEXT,\n review_state TEXT,\n artifact_path TEXT NOT NULL,\n indexed_at TEXT NOT NULL\n )`,\n\n `CREATE TABLE IF NOT EXISTS contradictions (\n contradiction_id TEXT PRIMARY KEY,\n section_id TEXT NOT NULL,\n type TEXT,\n severity TEXT,\n status TEXT,\n overlap_assessment TEXT,\n claim_ids_json TEXT NOT NULL,\n source_ids_json TEXT NOT NULL,\n summary TEXT,\n detector TEXT,\n artifact_path TEXT NOT NULL,\n indexed_at TEXT NOT NULL\n )`,\n\n `CREATE TABLE IF NOT EXISTS review_findings (\n finding_id TEXT PRIMARY KEY,\n section_id TEXT NOT NULL,\n category TEXT,\n severity TEXT,\n claim_ids_json TEXT NOT NULL,\n source_ids_json TEXT NOT NULL,\n summary TEXT,\n required_action TEXT,\n reviewer TEXT,\n artifact_path TEXT NOT NULL,\n indexed_at TEXT NOT NULL\n )`,\n\n `CREATE TABLE IF NOT EXISTS claim_reviews (\n rowid_pk INTEGER PRIMARY KEY AUTOINCREMENT,\n claim_id TEXT NOT NULL,\n section_id TEXT NOT NULL,\n decision TEXT,\n reason TEXT,\n reviewer TEXT,\n created_at TEXT,\n artifact_path TEXT NOT NULL,\n indexed_at TEXT NOT NULL\n )`,\n\n `CREATE TABLE IF NOT EXISTS gate_results (\n section_id TEXT PRIMARY KEY,\n verdict TEXT,\n synthesis_eligible INTEGER,\n failures_json TEXT,\n warnings_json TEXT,\n blocking_reasons_json TEXT,\n waivers_json TEXT,\n next_actions_json TEXT,\n artifact_path TEXT NOT NULL,\n checked_at TEXT,\n indexed_at TEXT NOT NULL\n )`,\n\n `CREATE TABLE IF NOT EXISTS fetch_receipts (\n receipt_id TEXT PRIMARY KEY,\n source_id TEXT,\n section_id TEXT,\n status INTEGER,\n fetch_outcome TEXT,\n content_type TEXT,\n sha256 TEXT,\n fetched_at TEXT,\n raw_text_path TEXT,\n artifact_path TEXT NOT NULL,\n indexed_at TEXT NOT NULL\n )`,\n\n `CREATE VIRTUAL TABLE IF NOT EXISTS facts_fts USING fts5(\n record_type UNINDEXED,\n record_id UNINDEXED,\n section_id UNINDEXED,\n artifact_path UNINDEXED,\n text,\n prefix='2 3 4'\n )`,\n\n `CREATE INDEX IF NOT EXISTS idx_sources_section ON sources(section_id)`,\n `CREATE INDEX IF NOT EXISTS idx_claims_section ON claims(section_id)`,\n `CREATE INDEX IF NOT EXISTS idx_contradictions_section ON contradictions(section_id)`,\n `CREATE INDEX IF NOT EXISTS idx_findings_section ON review_findings(section_id)`,\n `CREATE INDEX IF NOT EXISTS idx_reviews_claim ON claim_reviews(claim_id)`,\n `CREATE INDEX IF NOT EXISTS idx_receipts_source ON fetch_receipts(source_id)`,\n];\n\nexport function applySchema(db: import('better-sqlite3').Database): void {\n db.exec('PRAGMA journal_mode = WAL;');\n db.exec('PRAGMA foreign_keys = ON;');\n for (const ddl of DDL_STATEMENTS) {\n db.exec(ddl);\n }\n const setMeta = db.prepare('INSERT OR REPLACE INTO meta(key, value) VALUES (?, ?)');\n setMeta.run('schema_version', String(SCHEMA_VERSION));\n}\n","import { mkdirSync, writeFileSync, existsSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport Database from 'better-sqlite3';\n\nimport { applySchema } from './schema.js';\n\nexport interface OpenDbOptions {\n packPath: string;\n readonly?: boolean;\n}\n\nexport function indexDbPath(packPath: string): string {\n return join(packPath, '.research-os', 'index.sqlite');\n}\n\nfunction ensureGitIgnore(packPath: string): void {\n const dir = join(packPath, '.research-os');\n const gi = join(dir, '.gitignore');\n if (!existsSync(gi)) {\n mkdirSync(dir, { recursive: true });\n writeFileSync(gi, '*\\n', 'utf8');\n }\n}\n\nexport function openIndexDb(opts: OpenDbOptions): Database.Database {\n const dbPath = indexDbPath(opts.packPath);\n if (!opts.readonly) {\n mkdirSync(dirname(dbPath), { recursive: true });\n ensureGitIgnore(opts.packPath);\n }\n const db = new Database(dbPath, { readonly: opts.readonly ?? false, fileMustExist: opts.readonly ?? false });\n if (!opts.readonly) applySchema(db);\n return db;\n}\n","import { existsSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { join, resolve, relative } from 'node:path';\nimport { createHash } from 'node:crypto';\nimport { parse as yamlParse } from 'yaml';\nimport type Database from 'better-sqlite3';\n\nimport { PackNotFoundError, SectionNotFoundError } from '../errors.js';\nimport { ResearchYamlSchema, type ResearchYaml } from '../intake/schema.js';\nimport { ClaimSchema, type Claim } from '../claims/schema.js';\nimport { ContradictionSchema, type Contradiction } from '../contradictions/schema.js';\nimport {\n FetchReceiptSchema,\n SourceCardSchema,\n type FetchReceipt,\n type SourceCard,\n} from '../sources/schema.js';\nimport {\n SectionGateResultSchema,\n type SectionGateResult,\n} from '../gates/schema.js';\nimport {\n ClaimReviewSchema,\n ReviewFindingSchema,\n type ClaimReview,\n type ReviewFinding,\n} from '../review/schema.js';\n\nimport { openIndexDb, indexDbPath } from './db.js';\nimport type { IndexBuildOptions, IndexBuildSummary } from './types.js';\n\nfunction relPath(packPath: string, abs: string): string {\n return relative(packPath, abs).split('\\\\').join('/');\n}\n\nasync function tryReadJsonl<T>(\n packPath: string,\n rel: string,\n parse: (raw: unknown) => T,\n): Promise<T[]> {\n const path = join(packPath, rel);\n if (!existsSync(path)) return [];\n const text = await readFile(path, 'utf8');\n const out: T[] = [];\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n out.push(parse(JSON.parse(line)));\n }\n return out;\n}\n\nasync function readSourceCards(packPath: string): Promise<SourceCard[]> {\n const dir = join(packPath, 'evidence', 'source-cards');\n if (!existsSync(dir)) return [];\n const { readdir } = await import('node:fs/promises');\n const entries = await readdir(dir);\n const cards: SourceCard[] = [];\n for (const entry of entries) {\n if (!entry.endsWith('.json')) continue;\n const text = await readFile(join(dir, entry), 'utf8');\n cards.push(SourceCardSchema.parse(JSON.parse(text)));\n }\n return cards;\n}\n\nasync function readGateResult(packPath: string, sectionId: string): Promise<SectionGateResult | null> {\n const path = join(packPath, 'audits', `${sectionId}-gate.json`);\n if (!existsSync(path)) return null;\n const text = await readFile(path, 'utf8');\n return SectionGateResultSchema.parse(JSON.parse(text));\n}\n\n\nfunction fileSha256(text: string): string {\n return createHash('sha256').update(text).digest('hex');\n}\n\nasync function indexSection(args: {\n db: Database.Database;\n packPath: string;\n research: ResearchYaml;\n sectionId: string;\n now: string;\n counts: IndexBuildSummary;\n}): Promise<void> {\n const { db, packPath, research, sectionId, now, counts } = args;\n\n const section = research.sections.find((s) => s.id === sectionId);\n if (!section) throw new SectionNotFoundError(sectionId);\n const sectionDir = join(packPath, 'sections', sectionId);\n if (!existsSync(sectionDir)) throw new SectionNotFoundError(sectionId);\n\n // Clear all existing rows for this section so re-index is clean\n db.prepare('DELETE FROM sources WHERE section_id = ?').run(sectionId);\n db.prepare('DELETE FROM claims WHERE section_id = ?').run(sectionId);\n db.prepare('DELETE FROM contradictions WHERE section_id = ?').run(sectionId);\n db.prepare('DELETE FROM review_findings WHERE section_id = ?').run(sectionId);\n db.prepare('DELETE FROM claim_reviews WHERE section_id = ?').run(sectionId);\n db.prepare('DELETE FROM gate_results WHERE section_id = ?').run(sectionId);\n db.prepare('DELETE FROM fetch_receipts WHERE section_id = ?').run(sectionId);\n db.prepare('DELETE FROM artifacts WHERE section_id = ?').run(sectionId);\n db.prepare('DELETE FROM facts_fts WHERE section_id = ?').run(sectionId);\n\n // Section row\n db.prepare(\n `INSERT OR REPLACE INTO sections(section_id, purpose, status, max_time_minutes,\n min_sources, primary_sources_required, contradictions_required, indexed_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,\n ).run(\n section.id,\n section.purpose,\n section.status,\n section.max_time_minutes,\n section.min_sources,\n section.primary_sources_required,\n section.contradictions_required ? 1 : 0,\n now,\n );\n\n const insertArtifact = db.prepare(\n `INSERT OR REPLACE INTO artifacts(artifact_id, artifact_type, section_id, path, sha256, bytes, indexed_at)\n VALUES (?, ?, ?, ?, ?, ?, ?)`,\n );\n const insertFts = db.prepare(\n `INSERT INTO facts_fts(record_type, record_id, section_id, artifact_path, text)\n VALUES (?, ?, ?, ?, ?)`,\n );\n const recordArtifact = (artifactType: string, rel: string, content: string | null): void => {\n const sha = content === null ? null : fileSha256(content);\n insertArtifact.run(`${sectionId}:${artifactType}`, artifactType, sectionId, rel, sha, content === null ? null : Buffer.byteLength(content, 'utf8'), now);\n counts.artifacts += 1;\n };\n\n // Sources (cards) — only those tagged for this section\n const allCards = await readSourceCards(packPath);\n const sectionSourceIds = new Set<string>();\n const sourcesJsonlPath = join(sectionDir, 'sources.jsonl');\n if (existsSync(sourcesJsonlPath)) {\n const text = await readFile(sourcesJsonlPath, 'utf8');\n recordArtifact('sources_jsonl', relPath(packPath, sourcesJsonlPath), text);\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n const entry = JSON.parse(line) as { source_id?: string };\n if (typeof entry.source_id === 'string') sectionSourceIds.add(entry.source_id);\n }\n }\n for (const card of allCards) {\n if (!sectionSourceIds.has(card.source_id) && card.section_id !== sectionId) continue;\n const cardPath = relPath(packPath, join(packPath, 'evidence', 'source-cards', `${card.source_id}.json`));\n db.prepare(\n `INSERT OR REPLACE INTO sources(\n source_id, section_id, url, publisher, source_type, relevance,\n asserts, scope, not_field, fetched_at, published_at, artifact_path, indexed_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n ).run(\n card.source_id,\n sectionId,\n card.url,\n card.publisher,\n card.source_type,\n card.relevance,\n card.asserts,\n card.scope,\n card.not,\n card.fetched_at,\n card.published_at,\n cardPath,\n now,\n );\n counts.sources += 1;\n const text = `${card.title}\\n${card.asserts}\\n${card.scope ?? ''}\\n${card.not ?? ''}\\n${card.key_points.join('\\n')}`;\n insertFts.run('source', card.source_id, sectionId, cardPath, text);\n }\n\n // Claims\n const claims = await tryReadJsonl<Claim>(\n packPath,\n `sections/${sectionId}/claims.jsonl`,\n (r) => ClaimSchema.parse(r),\n );\n const claimsArtifact = relPath(packPath, join(sectionDir, 'claims.jsonl'));\n if (existsSync(join(sectionDir, 'claims.jsonl'))) {\n const text = await readFile(join(sectionDir, 'claims.jsonl'), 'utf8');\n recordArtifact('claims_jsonl', claimsArtifact, text);\n }\n for (const claim of claims) {\n db.prepare(\n `INSERT OR REPLACE INTO claims(\n claim_id, section_id, source_ids_json, asserts, scope, not_field,\n evidence_excerpt, confidence, extractor, extraction_method, review_state,\n artifact_path, indexed_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n ).run(\n claim.claim_id,\n sectionId,\n JSON.stringify(claim.source_ids),\n claim.asserts,\n claim.scope,\n claim.not,\n claim.evidence_excerpt,\n claim.confidence,\n claim.extractor,\n claim.extraction_method,\n claim.review_state,\n claimsArtifact,\n now,\n );\n counts.claims += 1;\n const ftsText = `${claim.asserts}\\n${claim.scope ?? ''}\\n${claim.not ?? ''}\\n${claim.evidence_excerpt}`;\n insertFts.run('claim', claim.claim_id, sectionId, claimsArtifact, ftsText);\n }\n\n // Contradictions\n const contradictions = await tryReadJsonl<Contradiction>(\n packPath,\n `sections/${sectionId}/contradictions.jsonl`,\n (r) => ContradictionSchema.parse(r),\n );\n const contradictionsArtifact = relPath(packPath, join(sectionDir, 'contradictions.jsonl'));\n if (existsSync(join(sectionDir, 'contradictions.jsonl'))) {\n const text = await readFile(join(sectionDir, 'contradictions.jsonl'), 'utf8');\n recordArtifact('contradictions_jsonl', contradictionsArtifact, text);\n }\n for (const c of contradictions) {\n db.prepare(\n `INSERT OR REPLACE INTO contradictions(\n contradiction_id, section_id, type, severity, status, overlap_assessment,\n claim_ids_json, source_ids_json, summary, detector, artifact_path, indexed_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n ).run(\n c.contradiction_id,\n sectionId,\n c.type,\n c.severity,\n c.status,\n c.overlap_assessment,\n JSON.stringify(c.claim_ids),\n JSON.stringify(c.source_ids),\n c.summary,\n c.detector,\n contradictionsArtifact,\n now,\n );\n counts.contradictions += 1;\n const ftsText = `${c.summary}\\n${c.scope_analysis}\\n${c.evidence}\\n${c.type}\\n${c.severity}`;\n insertFts.run('contradiction', c.contradiction_id, sectionId, contradictionsArtifact, ftsText);\n }\n\n // Review findings\n const findings = await tryReadJsonl<ReviewFinding>(\n packPath,\n `audits/${sectionId}-findings.jsonl`,\n (r) => ReviewFindingSchema.parse(r),\n );\n const findingsArtifact = relPath(packPath, join(packPath, 'audits', `${sectionId}-findings.jsonl`));\n const findingsAbs = join(packPath, 'audits', `${sectionId}-findings.jsonl`);\n if (existsSync(findingsAbs)) {\n const text = await readFile(findingsAbs, 'utf8');\n recordArtifact('findings_jsonl', findingsArtifact, text);\n }\n // Dedup findings by ID since the ledger is append-only — keep the latest occurrence\n const findingById = new Map<string, ReviewFinding>();\n for (const f of findings) findingById.set(f.finding_id, f);\n for (const f of findingById.values()) {\n db.prepare(\n `INSERT OR REPLACE INTO review_findings(\n finding_id, section_id, category, severity, claim_ids_json, source_ids_json,\n summary, required_action, reviewer, artifact_path, indexed_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n ).run(\n f.finding_id,\n sectionId,\n f.category,\n f.severity,\n JSON.stringify(f.claim_ids),\n JSON.stringify(f.source_ids),\n f.summary,\n f.required_action,\n f.reviewer,\n findingsArtifact,\n now,\n );\n counts.reviewFindings += 1;\n const ftsText = `${f.category}\\n${f.severity}\\n${f.summary}\\n${f.required_action}\\n${f.evidence}`;\n insertFts.run('review_finding', f.finding_id, sectionId, findingsArtifact, ftsText);\n }\n\n // Claim reviews (append-only ledger — every entry is preserved)\n const reviews = await tryReadJsonl<ClaimReview>(\n packPath,\n `sections/${sectionId}/claim-reviews.jsonl`,\n (r) => ClaimReviewSchema.parse(r),\n );\n const reviewsArtifact = relPath(packPath, join(sectionDir, 'claim-reviews.jsonl'));\n const reviewsAbs = join(sectionDir, 'claim-reviews.jsonl');\n if (existsSync(reviewsAbs)) {\n const text = await readFile(reviewsAbs, 'utf8');\n recordArtifact('claim_reviews_jsonl', reviewsArtifact, text);\n }\n for (const r of reviews) {\n db.prepare(\n `INSERT INTO claim_reviews(\n claim_id, section_id, decision, reason, reviewer, created_at, artifact_path, indexed_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,\n ).run(\n r.claim_id,\n sectionId,\n r.decision,\n r.reason,\n r.reviewer,\n r.created_at,\n reviewsArtifact,\n now,\n );\n counts.claimReviews += 1;\n const ftsText = `${r.decision}\\n${r.reason}`;\n insertFts.run('claim_review', `${r.claim_id}@${r.created_at}`, sectionId, reviewsArtifact, ftsText);\n }\n\n // Gate result\n const gate = await readGateResult(packPath, sectionId);\n if (gate) {\n const gateArtifact = relPath(packPath, join(packPath, 'audits', `${sectionId}-gate.json`));\n const gateText = await readFile(join(packPath, 'audits', `${sectionId}-gate.json`), 'utf8');\n recordArtifact('gate_json', gateArtifact, gateText);\n db.prepare(\n `INSERT OR REPLACE INTO gate_results(\n section_id, verdict, synthesis_eligible,\n failures_json, warnings_json, blocking_reasons_json, waivers_json, next_actions_json,\n artifact_path, checked_at, indexed_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n ).run(\n gate.section_id,\n gate.verdict,\n gate.synthesis_eligible ? 1 : 0,\n JSON.stringify(gate.failures),\n JSON.stringify(gate.warnings),\n JSON.stringify(gate.blocking_reasons),\n JSON.stringify(gate.waivers_applied),\n JSON.stringify(gate.next_actions),\n gateArtifact,\n gate.checked_at,\n now,\n );\n counts.gateResults += 1;\n const ftsText = `${gate.verdict}\\n${gate.summary}\\n${gate.blocking_reasons.join('\\n')}\\n${gate.next_actions.join('\\n')}`;\n insertFts.run('gate_result', sectionId, sectionId, gateArtifact, ftsText);\n }\n\n // Fetch receipts (filtered to this section by section_id field)\n const allReceipts = await tryReadJsonl<FetchReceipt>(\n packPath,\n 'evidence/fetch-log.jsonl',\n (r) => FetchReceiptSchema.parse(r),\n );\n const fetchLogAbs = join(packPath, 'evidence', 'fetch-log.jsonl');\n if (existsSync(fetchLogAbs)) {\n const text = await readFile(fetchLogAbs, 'utf8');\n recordArtifact('fetch_log_jsonl', relPath(packPath, fetchLogAbs), text);\n }\n for (const receipt of allReceipts.filter((r) => r.section_id === sectionId)) {\n db.prepare(\n `INSERT OR REPLACE INTO fetch_receipts(\n receipt_id, source_id, section_id, status, fetch_outcome, content_type,\n sha256, fetched_at, raw_text_path, artifact_path, indexed_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n ).run(\n receipt.receipt_id,\n receipt.source_id,\n receipt.section_id,\n receipt.status,\n receipt.fetch_outcome,\n receipt.content_type,\n receipt.sha256,\n receipt.fetched_at,\n receipt.raw_text_path,\n relPath(packPath, fetchLogAbs),\n now,\n );\n counts.fetchReceipts += 1;\n const ftsText = `${receipt.fetch_outcome} ${receipt.requested_url} ${receipt.title ?? ''} ${receipt.fetch_error ?? ''}`;\n insertFts.run('fetch_receipt', receipt.receipt_id, sectionId, relPath(packPath, fetchLogAbs), ftsText);\n }\n}\n\nconst ROLLUP_FILES: Array<{ filename: string; recordType: 'pack_audit' | 'audit_rollup'; recordId: string }> = [\n { filename: 'pack-audit.json', recordType: 'pack_audit', recordId: 'pack_audit' },\n { filename: 'orphan-claims.json', recordType: 'audit_rollup', recordId: 'orphan-claims' },\n { filename: 'stale-sources.json', recordType: 'audit_rollup', recordId: 'stale-sources' },\n { filename: 'weak-sources.json', recordType: 'audit_rollup', recordId: 'weak-sources' },\n { filename: 'unresolved-contradictions.json', recordType: 'audit_rollup', recordId: 'unresolved-contradictions' },\n { filename: 'scope-widening-risks.json', recordType: 'audit_rollup', recordId: 'scope-widening-risks' },\n { filename: 'source-diversity-gaps.json', recordType: 'audit_rollup', recordId: 'source-diversity-gaps' },\n { filename: 'synthesis-readiness.json', recordType: 'audit_rollup', recordId: 'synthesis-readiness' },\n];\n\nasync function indexPackAuditRollups(\n db: Database.Database,\n packPath: string,\n _now: string,\n): Promise<void> {\n const insertFts = db.prepare(\n `INSERT INTO facts_fts(record_type, record_id, section_id, artifact_path, text)\n VALUES (?, ?, ?, ?, ?)`,\n );\n // Clear any prior rollup entries first (each record_id is unique per type)\n for (const f of ROLLUP_FILES) {\n db.prepare(`DELETE FROM facts_fts WHERE record_type = ? AND record_id = ?`).run(f.recordType, f.recordId);\n }\n for (const f of ROLLUP_FILES) {\n const abs = join(packPath, 'audits', f.filename);\n if (!existsSync(abs)) continue;\n const text = await readFile(abs, 'utf8');\n insertFts.run(\n f.recordType,\n f.recordId,\n null,\n `audits/${f.filename}`,\n text.slice(0, 24_000),\n );\n }\n}\n\nexport async function build(options: IndexBuildOptions): Promise<IndexBuildSummary> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n if (!existsSync(join(packPath, 'research.yaml'))) throw new PackNotFoundError(packPath);\n const research = ResearchYamlSchema.parse(yamlParse(await readFile(join(packPath, 'research.yaml'), 'utf8')));\n\n const targets: string[] = options.sectionId\n ? [options.sectionId]\n : options.all\n ? research.sections.map((s) => s.id)\n : research.sections.map((s) => s.id);\n\n if (targets.length === 0) {\n throw new Error('No sections to index. Add at least one section to the pack.');\n }\n\n const db = openIndexDb({ packPath });\n const now = new Date().toISOString();\n const counts: IndexBuildSummary = {\n packPath,\n dbPath: indexDbPath(packPath),\n sectionsIndexed: 0,\n sources: 0,\n claims: 0,\n contradictions: 0,\n reviewFindings: 0,\n claimReviews: 0,\n gateResults: 0,\n fetchReceipts: 0,\n artifacts: 0,\n };\n\n try {\n for (const sid of targets) {\n await indexSection({ db, packPath, research, sectionId: sid, now, counts });\n counts.sectionsIndexed += 1;\n }\n await indexPackAuditRollups(db, packPath, now);\n } finally {\n db.close();\n }\n\n return counts;\n}\n","import { existsSync } from 'node:fs';\nimport { resolve } from 'node:path';\n\nimport { PackNotFoundError } from '../errors.js';\nimport { openIndexDb, indexDbPath } from './db.js';\nimport type { IndexQueryOptions, IndexQuerySummary, QueryHit, RecordType } from './types.js';\n\nexport class IndexNotBuiltError extends Error {\n constructor(public readonly dbPath: string) {\n super(\n `No index found at ${dbPath}. Run 'research-os index --all' to build it before querying.`,\n );\n this.name = 'IndexNotBuiltError';\n }\n}\n\nfunction escapeFtsTerm(term: string): string {\n // Quote each word and OR them together so common phrasing works.\n // For simplicity: wrap the entire term in quotes if it contains spaces,\n // otherwise pass through. FTS5 prefix queries supported via *.\n const trimmed = term.trim();\n if (!trimmed) return '\"\"';\n // If user already provided FTS syntax characters, pass through. Otherwise quote.\n if (/[\" *^()-]/.test(trimmed)) return trimmed;\n return `\"${trimmed.replace(/\"/g, '\"\"')}\"`;\n}\n\nexport function query(options: IndexQueryOptions): IndexQuerySummary {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n const dbPath = indexDbPath(packPath);\n if (!existsSync(packPath)) throw new PackNotFoundError(packPath);\n if (!existsSync(dbPath)) throw new IndexNotBuiltError(dbPath);\n\n const db = openIndexDb({ packPath, readonly: true });\n const limit = options.limit ?? 25;\n const ftsTerm = escapeFtsTerm(options.term);\n\n let stmt;\n let rows: Array<{\n record_type: string;\n record_id: string;\n section_id: string | null;\n artifact_path: string;\n snippet: string;\n rank: number;\n }>;\n try {\n if (options.recordType) {\n stmt = db.prepare(\n `SELECT record_type, record_id, section_id, artifact_path,\n snippet(facts_fts, 4, '<mark>', '</mark>', '...', 30) AS snippet,\n rank\n FROM facts_fts\n WHERE facts_fts MATCH ?\n AND record_type = ?\n ORDER BY rank\n LIMIT ?`,\n );\n rows = stmt.all(ftsTerm, options.recordType, limit) as typeof rows;\n } else {\n stmt = db.prepare(\n `SELECT record_type, record_id, section_id, artifact_path,\n snippet(facts_fts, 4, '<mark>', '</mark>', '...', 30) AS snippet,\n rank\n FROM facts_fts\n WHERE facts_fts MATCH ?\n ORDER BY rank\n LIMIT ?`,\n );\n rows = stmt.all(ftsTerm, limit) as typeof rows;\n }\n } finally {\n db.close();\n }\n\n const hits: QueryHit[] = rows.map((r) => ({\n record_type: r.record_type as RecordType,\n record_id: r.record_id,\n section_id: r.section_id,\n artifact_path: r.artifact_path,\n snippet: r.snippet,\n rank: r.rank,\n }));\n\n const grouped: Record<string, QueryHit[]> = {};\n for (const h of hits) {\n if (!grouped[h.record_type]) grouped[h.record_type] = [];\n grouped[h.record_type]!.push(h);\n }\n\n return {\n term: options.term,\n totalHits: hits.length,\n hits,\n groupedByType: grouped,\n };\n}\n","import { existsSync } from 'node:fs';\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join, resolve } from 'node:path';\n\nimport { PackNotFoundError } from '../errors.js';\nimport { openIndexDb, indexDbPath } from './db.js';\nimport { IndexNotBuiltError } from './query.js';\nimport type { ExportOptions, ExportSummary } from './types.js';\n\ninterface FactRow {\n fact_type: string;\n id: string;\n section_id: string | null;\n text: string;\n artifact_path: string;\n metadata: Record<string, unknown>;\n pack_origin: string;\n exported_at: string;\n}\n\nexport async function exportRepoKnowledge(options: ExportOptions): Promise<ExportSummary> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n if (!existsSync(packPath)) throw new PackNotFoundError(packPath);\n const dbPath = indexDbPath(packPath);\n if (!existsSync(dbPath)) throw new IndexNotBuiltError(dbPath);\n\n const outPath = options.outPath\n ? resolve(options.outPath)\n : join(packPath, 'evidence', 'repo-knowledge', 'research-os-facts.jsonl');\n await mkdir(dirname(outPath), { recursive: true });\n\n const db = openIndexDb({ packPath, readonly: true });\n const now = new Date().toISOString();\n const facts: FactRow[] = [];\n const byType: Record<string, number> = {};\n const incr = (t: string): void => {\n byType[t] = (byType[t] ?? 0) + 1;\n };\n\n try {\n const sources = db\n .prepare(`SELECT * FROM sources`)\n .all() as Array<Record<string, unknown>>;\n for (const r of sources) {\n facts.push({\n fact_type: 'research_os.source',\n id: String(r.source_id),\n section_id: r.section_id as string | null,\n text: [r.asserts, r.scope, r.not_field].filter(Boolean).join(' '),\n artifact_path: String(r.artifact_path),\n metadata: {\n url: r.url,\n publisher: r.publisher,\n source_type: r.source_type,\n relevance: r.relevance,\n fetched_at: r.fetched_at,\n published_at: r.published_at,\n },\n pack_origin: packPath,\n exported_at: now,\n });\n incr('research_os.source');\n }\n\n const claims = db\n .prepare(`SELECT * FROM claims`)\n .all() as Array<Record<string, unknown>>;\n for (const r of claims) {\n facts.push({\n fact_type: 'research_os.claim',\n id: String(r.claim_id),\n section_id: r.section_id as string,\n text: [r.asserts, r.scope, r.not_field, r.evidence_excerpt].filter(Boolean).join(' '),\n artifact_path: String(r.artifact_path),\n metadata: {\n source_ids: JSON.parse(String(r.source_ids_json)),\n confidence: r.confidence,\n extractor: r.extractor,\n extraction_method: r.extraction_method,\n review_state: r.review_state,\n },\n pack_origin: packPath,\n exported_at: now,\n });\n incr('research_os.claim');\n }\n\n const contradictions = db\n .prepare(`SELECT * FROM contradictions`)\n .all() as Array<Record<string, unknown>>;\n for (const r of contradictions) {\n facts.push({\n fact_type: 'research_os.contradiction',\n id: String(r.contradiction_id),\n section_id: r.section_id as string,\n text: String(r.summary ?? ''),\n artifact_path: String(r.artifact_path),\n metadata: {\n type: r.type,\n severity: r.severity,\n status: r.status,\n overlap_assessment: r.overlap_assessment,\n claim_ids: JSON.parse(String(r.claim_ids_json)),\n source_ids: JSON.parse(String(r.source_ids_json)),\n detector: r.detector,\n },\n pack_origin: packPath,\n exported_at: now,\n });\n incr('research_os.contradiction');\n }\n\n const findings = db\n .prepare(`SELECT * FROM review_findings`)\n .all() as Array<Record<string, unknown>>;\n for (const r of findings) {\n facts.push({\n fact_type: 'research_os.review_finding',\n id: String(r.finding_id),\n section_id: r.section_id as string,\n text: [r.summary, r.required_action].filter(Boolean).join(' '),\n artifact_path: String(r.artifact_path),\n metadata: {\n category: r.category,\n severity: r.severity,\n claim_ids: JSON.parse(String(r.claim_ids_json)),\n source_ids: JSON.parse(String(r.source_ids_json)),\n reviewer: r.reviewer,\n },\n pack_origin: packPath,\n exported_at: now,\n });\n incr('research_os.review_finding');\n }\n\n const gates = db\n .prepare(`SELECT * FROM gate_results`)\n .all() as Array<Record<string, unknown>>;\n for (const r of gates) {\n facts.push({\n fact_type: 'research_os.gate_result',\n id: String(r.section_id),\n section_id: r.section_id as string,\n text: `${r.verdict} ${(JSON.parse(String(r.blocking_reasons_json)) as string[]).join(' ')}`,\n artifact_path: String(r.artifact_path),\n metadata: {\n verdict: r.verdict,\n synthesis_eligible: r.synthesis_eligible === 1,\n checked_at: r.checked_at,\n blocking_reasons: JSON.parse(String(r.blocking_reasons_json)),\n waivers: JSON.parse(String(r.waivers_json)),\n next_actions: JSON.parse(String(r.next_actions_json)),\n },\n pack_origin: packPath,\n exported_at: now,\n });\n incr('research_os.gate_result');\n }\n } finally {\n db.close();\n }\n\n const text = facts.map((f) => JSON.stringify(f)).join('\\n') + (facts.length > 0 ? '\\n' : '');\n await writeFile(outPath, text, 'utf8');\n\n return {\n outPath,\n factCount: facts.length,\n byType,\n };\n}\n","import { resolve } from 'node:path';\n\nimport { exportRepoKnowledge } from './export.js';\nimport type { SyncOptions, SyncSummary } from './types.js';\n\ninterface RepoKnowledgeShape {\n ingestFacts?: (args: {\n facts: unknown[];\n namespace?: string;\n }) => Promise<{ count: number }> | { count: number };\n}\n\nasync function loadRepoKnowledge(): Promise<RepoKnowledgeShape | null> {\n // Optional peer dependency; resolved dynamically at runtime so the package\n // does not need to be installed for the rest of research-os to work.\n const pkgName = '@mcptoolshop/repo-knowledge';\n try {\n const mod = (await import(/* @vite-ignore */ pkgName).catch(() => null)) as\n | RepoKnowledgeShape\n | null;\n return mod;\n } catch {\n return null;\n }\n}\n\nexport async function syncRepoKnowledge(options: SyncOptions): Promise<SyncSummary> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n const rk = await loadRepoKnowledge();\n if (!rk || typeof rk.ingestFacts !== 'function') {\n return {\n attempted: false,\n ok: false,\n reason:\n '@mcptoolshop/repo-knowledge not available locally. Sync skipped — pack remains self-contained. Use `research-os index export-repo-knowledge` for a portable export instead.',\n factsSynced: 0,\n };\n }\n\n const exportResult = await exportRepoKnowledge({ packPath });\n // Re-read the JSONL we just wrote so repo-knowledge ingests the same canonical fact stream\n const { readFile } = await import('node:fs/promises');\n const text = await readFile(exportResult.outPath, 'utf8');\n const facts = text\n .split(/\\r?\\n/)\n .filter((l) => l.trim().length > 0)\n .map((l) => JSON.parse(l));\n\n try {\n const r = await rk.ingestFacts({ facts, namespace: 'research-os' });\n return {\n attempted: true,\n ok: true,\n reason: 'ingested via @mcptoolshop/repo-knowledge.ingestFacts',\n factsSynced: r.count ?? facts.length,\n };\n } catch (err) {\n return {\n attempted: true,\n ok: false,\n reason: err instanceof Error ? err.message : 'unknown ingest error',\n factsSynced: 0,\n };\n }\n}\n","export { build } from './build.js';\nexport { query, IndexNotBuiltError } from './query.js';\nexport { exportRepoKnowledge } from './export.js';\nexport { syncRepoKnowledge } from './sync.js';\nexport { openIndexDb, indexDbPath } from './db.js';\nexport { applySchema, SCHEMA_VERSION } from './schema.js';\nexport type {\n IndexBuildOptions,\n IndexBuildSummary,\n IndexQueryOptions,\n IndexQuerySummary,\n QueryHit,\n RecordType,\n ExportOptions,\n ExportSummary,\n SyncOptions,\n SyncSummary,\n} from './types.js';\n","import { z } from 'zod';\n\nexport const ClaimSynthesisDispositionStatusSchema = z.enum([\n 'parked_not_for_synthesis',\n 'preserved_for_human_note',\n 'needs_human_review_excluded',\n 'out_of_bounds_regression_fixture',\n]);\n\nexport const ClaimSynthesisDispositionSchema = z.object({\n claim_id: z.string().min(1),\n section_id: z.string().min(1),\n status: ClaimSynthesisDispositionStatusSchema,\n reason: z.string().min(4),\n decided_by: z.string().min(1),\n authorized_by: z.string().min(1),\n source: z.string().min(1),\n created_at: z.string().min(1),\n});\n\nexport type ClaimSynthesisDisposition = z.infer<typeof ClaimSynthesisDispositionSchema>;\nexport type ClaimSynthesisDispositionStatus = z.infer<typeof ClaimSynthesisDispositionStatusSchema>;\n","import { createHash } from 'node:crypto';\n\nimport type { ResearchYaml } from '../intake/schema.js';\nimport type { Claim } from '../claims/schema.js';\nimport type { ClaimReview } from '../review/schema.js';\nimport type { Contradiction } from '../contradictions/schema.js';\nimport type { ContradictionResolution } from '../contradictions/resolution-schema.js';\nimport type { ClaimSynthesisDisposition } from '../dispositions/schema.js';\nimport type { SectionGateResult } from '../gates/schema.js';\n\nimport type {\n CoworkHandoffPayload,\n HandoffMode,\n IndexStatus,\n ProvenanceSummary,\n ReviewDecisionCount,\n SectionState,\n WaiverEntry,\n} from './types.js';\n\nexport interface DeriveInput {\n research: ResearchYaml;\n perSection: Map<\n string,\n {\n gate: SectionGateResult | null;\n candidateClaims: Claim[];\n claimReviews: ClaimReview[];\n contradictions: Contradiction[];\n resolutions?: ContradictionResolution[];\n dispositions?: ClaimSynthesisDisposition[];\n }\n >;\n indexStatus: IndexStatus;\n generatedAt: string;\n warnings: string[];\n}\n\nexport const FORBIDDEN_ACTIONS_ALWAYS = [\n 'Mutate sections/<id>/claims.jsonl directly — it is extraction truth (append-only via research-os tools)',\n 'Mutate evidence/source-cards/*.json or evidence/fetch-log.jsonl — these are fetched-truth artifacts',\n 'Mutate audits/*-gate.json or audits/*-review.json — these are immutable audit snapshots',\n 'Cite a source_id that is not present in evidence/source-cards/',\n 'Cite a claim_id that is not present in sections/<id>/claims.jsonl',\n 'Treat a claim with scope=null as broadly applicable — null-scope means scope-undetermined, not scope-universal',\n 'Widen the scope of a claim beyond what the source explicitly supports',\n 'Flatten an unresolved contradiction; preserve it deliberately or route it through claim-reviews',\n 'Write final synthesis prose unless mode == synthesis_ready',\n 'Reconcile contradictions silently — use research-os contradict map / research-os review with explicit decisions',\n];\n\nconst ALLOWED_WRITE_BASE = [\n 'handoffs/cowork-options.md',\n 'handoffs/cowork-notes.md',\n];\n\nconst ALLOWED_WRITE_REPAIR = [\n ...ALLOWED_WRITE_BASE,\n 'sections/<id>/open_questions.md',\n 'sections/<id>/brief.md (working notes only — final brief lands at synthesis time)',\n 'audits/<id>-cowork-repair-notes.md',\n];\n\nconst ALLOWED_WRITE_SYNTHESIS = [\n ...ALLOWED_WRITE_BASE,\n 'synthesis/cross-section-map.md',\n 'synthesis/decision-brief.md',\n 'synthesis/final-report.md',\n 'synthesis/working-report.md',\n 'sections/<id>/brief.md (final form, drawing from accepted claims only)',\n];\n\nfunction packId(research: ResearchYaml): string {\n const fingerprint = `${research.topic}|${research.created_at}`;\n return createHash('sha256').update(fingerprint).digest('hex').slice(0, 12);\n}\n\nfunction latestDecisionByClaim(reviews: ClaimReview[]): Map<string, ClaimReview> {\n const map = new Map<string, ClaimReview>();\n for (const r of reviews) {\n const existing = map.get(r.claim_id);\n if (!existing || r.created_at > existing.created_at) {\n map.set(r.claim_id, r);\n }\n }\n return map;\n}\n\nfunction buildEffectiveStatuses(resolutions: ContradictionResolution[]): Map<string, string> {\n const sorted = [...resolutions].sort((a, b) => a.resolved_at.localeCompare(b.resolved_at));\n const map = new Map<string, string>();\n for (const r of sorted) map.set(r.contradiction_id, r.status);\n return map;\n}\n\nfunction buildEffectiveDispositions(\n dispositions: ClaimSynthesisDisposition[],\n decisionByClaim: Map<string, ClaimReview>,\n warnings: string[],\n): Map<string, string> {\n const map = new Map<string, string>();\n if (dispositions.length === 0) return map;\n const sorted = [...dispositions].sort((a, b) => a.created_at.localeCompare(b.created_at));\n for (const d of sorted) {\n const review = decisionByClaim.get(d.claim_id);\n if (review?.decision === 'accepted_for_synthesis') {\n warnings.push(\n `invalid disposition: claim ${d.claim_id} has accepted_for_synthesis review but a disposition entry was found — layer separation violated`,\n );\n continue;\n }\n map.set(d.claim_id, d.status);\n }\n return map;\n}\n\nfunction buildSectionState(args: {\n sectionId: string;\n research: ResearchYaml;\n gate: SectionGateResult | null;\n candidateClaims: Claim[];\n claimReviews: ClaimReview[];\n contradictions: Contradiction[];\n resolutions?: ContradictionResolution[];\n dispositions?: ClaimSynthesisDisposition[];\n warnings: string[];\n}): SectionState {\n const { sectionId, research, gate, candidateClaims, claimReviews, contradictions, resolutions = [], dispositions = [], warnings } = args;\n const sectionMeta = research.sections.find((s) => s.id === sectionId);\n const purpose = sectionMeta?.purpose ?? '';\n const status = sectionMeta?.status ?? 'unknown';\n\n const decisionByClaim = latestDecisionByClaim(claimReviews);\n const effectiveDispositions = buildEffectiveDispositions(dispositions, decisionByClaim, warnings);\n\n const accepted: string[] = [];\n const repair: string[] = [];\n const rejected: string[] = [];\n const dispositioned: string[] = [];\n for (const c of candidateClaims) {\n const d = decisionByClaim.get(c.claim_id);\n if (!d) continue;\n if (d.decision === 'accepted_for_synthesis') {\n accepted.push(c.claim_id);\n } else if (d.decision === 'rejected') {\n rejected.push(c.claim_id);\n } else if (effectiveDispositions.has(c.claim_id)) {\n dispositioned.push(c.claim_id);\n } else {\n repair.push(c.claim_id);\n }\n }\n\n const effectiveStatuses = buildEffectiveStatuses(resolutions);\n const unresolved = contradictions.filter((c) => {\n const effective = effectiveStatuses.get(c.contradiction_id);\n return effective !== undefined ? effective === 'unresolved' : c.status === 'unresolved';\n });\n const blocking = unresolved.filter(\n (c) => c.severity === 'high' || c.severity === 'blocking',\n );\n\n const reviewedClaimIds = new Set(decisionByClaim.keys());\n const triageParkedCount = candidateClaims.filter((c) => !reviewedClaimIds.has(c.claim_id)).length;\n\n const dispositionedBreakdown = {\n parked_not_for_synthesis: 0,\n preserved_for_human_note: 0,\n needs_human_review_excluded: 0,\n out_of_bounds_regression_fixture: 0,\n };\n for (const cid of dispositioned) {\n const s = effectiveDispositions.get(cid);\n if (s === 'parked_not_for_synthesis') dispositionedBreakdown.parked_not_for_synthesis++;\n else if (s === 'preserved_for_human_note') dispositionedBreakdown.preserved_for_human_note++;\n else if (s === 'needs_human_review_excluded') dispositionedBreakdown.needs_human_review_excluded++;\n else if (s === 'out_of_bounds_regression_fixture') dispositionedBreakdown.out_of_bounds_regression_fixture++;\n }\n\n const overrideAcceptedCount = Array.from(decisionByClaim.values()).filter(\n (r) => r.decision === 'accepted_for_synthesis' && r.review_method.includes('operator_override'),\n ).length;\n\n const waiversActive = gate?.waivers_applied.map((w) => `${w.family}:${w.check}`) ?? [];\n\n const provenanceSummary: ProvenanceSummary = {\n accepted_count: accepted.length,\n rejected_count: rejected.length,\n triage_parked_count: triageParkedCount,\n needs_review_undispositioned_count: repair.length,\n dispositioned_count: dispositioned.length,\n dispositioned_breakdown: dispositionedBreakdown,\n active_repair_blockers: repair.length,\n active_unresolved_contradictions: unresolved.length,\n waivers_active: waiversActive,\n overrides_applied_count: overrideAcceptedCount,\n };\n\n return {\n section_id: sectionId,\n purpose,\n status,\n has_gate_run: !!gate,\n has_review_run: claimReviews.length > 0,\n gate_verdict: gate?.verdict ?? null,\n synthesis_eligible: gate?.synthesis_eligible ?? false,\n accepted_claim_ids: accepted,\n repair_claim_ids: repair,\n rejected_claim_ids: rejected,\n dispositioned_claim_ids: dispositioned,\n candidate_claims_total: candidateClaims.length,\n unresolved_contradiction_ids: unresolved.map((c) => c.contradiction_id),\n blocking_reasons: gate?.blocking_reasons ?? [],\n active_blockers: gate?.blocking_reasons ?? [],\n blocking_contradictions_unresolved: blocking.length,\n provenance_summary: provenanceSummary,\n };\n}\n\nfunction collectWaivers(\n research: ResearchYaml,\n perSection: DeriveInput['perSection'],\n): WaiverEntry[] {\n const waivers: WaiverEntry[] = [];\n const w = research.primary_source_waiver;\n if (w.status === 'granted') {\n waivers.push({\n scope: 'pack',\n family: 'source_floor',\n reason: w.reason ?? '',\n compensating_controls: w.compensating_controls ?? [],\n applied_to: 'primary_sources_required',\n });\n }\n for (const [sid, data] of perSection) {\n const gate = data.gate;\n if (!gate) continue;\n for (const wa of gate.waivers_applied) {\n waivers.push({\n scope: 'gate',\n family: wa.family,\n reason: wa.reason,\n compensating_controls: wa.compensating_controls,\n applied_to: `${sid}.${wa.check}`,\n });\n }\n }\n return waivers;\n}\n\nfunction determineMode(\n sections: SectionState[],\n waivers: WaiverEntry[],\n warnings: string[],\n): HandoffMode {\n const hasMalformed = warnings.some((w) => /malformed|invalid|parse/i.test(w));\n const invalidWaivers = waivers.some(\n (w) => w.reason.trim().length === 0 || w.compensating_controls.length === 0,\n );\n const blockingContradictions = sections.some(\n (s) => s.blocking_contradictions_unresolved > 0,\n );\n\n if (hasMalformed || invalidWaivers || blockingContradictions) {\n return 'human_review_required';\n }\n\n const allReady = sections.every(\n (s) =>\n s.has_gate_run &&\n s.synthesis_eligible &&\n s.has_review_run &&\n s.candidate_claims_total > 0 &&\n s.active_blockers.length === 0 &&\n s.unresolved_contradiction_ids.length === 0,\n );\n\n if (allReady && sections.length > 0) return 'synthesis_ready';\n return 'repair_required';\n}\n\nfunction buildRecommendedNextActions(\n sections: SectionState[],\n mode: HandoffMode,\n): string[] {\n const actions: string[] = [];\n if (mode === 'synthesis_ready') {\n actions.push('Run `research-os query \"<term>\"` to navigate the indexed evidence base before drafting synthesis.');\n actions.push('Draft `synthesis/cross-section-map.md` listing how accepted claims relate across sections (no new facts).');\n actions.push('Draft `synthesis/decision-brief.md` for the pack\\'s `decision` field, citing only accepted_claim_ids.');\n actions.push('When done, suggest the user run `research-os index build --all` and `research-os cowork handoff` to refresh the runtime contract.');\n return actions;\n }\n if (mode === 'human_review_required') {\n actions.push('Stop and surface the human-review-required reasons to the operator.');\n actions.push('Prepare options in `handoffs/cowork-options.md` — do not decide.');\n return actions;\n }\n // repair_required\n for (const s of sections) {\n if (!s.has_gate_run) {\n actions.push(`Run \\`research-os gate ${s.section_id}\\` (no gate result on file yet).`);\n continue;\n }\n if (!s.synthesis_eligible) {\n for (const r of s.blocking_reasons) {\n actions.push(`[${s.section_id}] address blocking gate failure: ${r}`);\n }\n if (s.blocking_reasons.length === 0) {\n actions.push(`[${s.section_id}] gate verdict ${s.gate_verdict ?? 'unknown'} but synthesis is not eligible — re-run \\`research-os gate ${s.section_id}\\` and review the audits.`);\n }\n }\n if (!s.has_review_run && s.candidate_claims_total > 0) {\n actions.push(`Run \\`research-os review ${s.section_id}\\` (no review on file yet).`);\n }\n if (s.repair_claim_ids.length > 0) {\n actions.push(`[${s.section_id}] ${s.repair_claim_ids.length} claim(s) need repair per latest review — re-run gather/extract for affected sources, then re-run review.`);\n }\n if (s.unresolved_contradiction_ids.length > 0) {\n actions.push(`[${s.section_id}] resolve, preserve, or reject ${s.unresolved_contradiction_ids.length} unresolved contradiction(s).`);\n }\n }\n if (actions.length === 0) {\n actions.push('No specific repair actions identified, but mode=repair_required — re-run `research-os gate --all` and `research-os review --all` to refresh state.');\n }\n return actions;\n}\n\nexport function derive(input: DeriveInput): CoworkHandoffPayload {\n const sections: SectionState[] = [];\n const acceptedAll: string[] = [];\n const repairAll: string[] = [];\n const blockedAll: string[] = [];\n const dispositionedAll: string[] = [];\n const unresolvedContradictionsAll: string[] = [];\n const gateVerdicts: CoworkHandoffPayload['gate_verdicts'] = [];\n const reviewDecisionCounts: ReviewDecisionCount[] = [];\n\n for (const sectionMeta of input.research.sections) {\n const data = input.perSection.get(sectionMeta.id) ?? {\n gate: null,\n candidateClaims: [],\n claimReviews: [],\n contradictions: [],\n };\n const state = buildSectionState({\n sectionId: sectionMeta.id,\n research: input.research,\n gate: data.gate,\n candidateClaims: data.candidateClaims,\n claimReviews: data.claimReviews,\n contradictions: data.contradictions,\n resolutions: data.resolutions,\n dispositions: data.dispositions,\n warnings: input.warnings,\n });\n sections.push(state);\n acceptedAll.push(...state.accepted_claim_ids);\n repairAll.push(...state.repair_claim_ids);\n blockedAll.push(...state.rejected_claim_ids);\n dispositionedAll.push(...state.dispositioned_claim_ids);\n unresolvedContradictionsAll.push(...state.unresolved_contradiction_ids);\n\n if (data.gate) {\n gateVerdicts.push({\n section_id: sectionMeta.id,\n verdict: data.gate.verdict,\n synthesis_eligible: data.gate.synthesis_eligible,\n });\n }\n\n const decisionTally: Record<string, number> = {};\n const latest = latestDecisionByClaim(data.claimReviews);\n for (const r of latest.values()) {\n decisionTally[r.decision] = (decisionTally[r.decision] ?? 0) + 1;\n }\n for (const [decision, count] of Object.entries(decisionTally)) {\n reviewDecisionCounts.push({ section_id: sectionMeta.id, decision, count });\n }\n }\n\n const waivers = collectWaivers(input.research, input.perSection);\n const mode = determineMode(sections, waivers, input.warnings);\n const synthesisAllowed = mode === 'synthesis_ready';\n\n const allowedWritePaths = mode === 'synthesis_ready'\n ? ALLOWED_WRITE_SYNTHESIS\n : mode === 'human_review_required'\n ? ALLOWED_WRITE_BASE\n : ALLOWED_WRITE_REPAIR;\n\n const summary = (() => {\n const ready = sections.filter((s) => s.synthesis_eligible).length;\n const blocked = sections.length - ready;\n return `Pack mode=${mode}; ${sections.length} section(s) total, ${ready} synthesis-eligible, ${blocked} blocked or unrun. ${acceptedAll.length} accepted claim(s); ${repairAll.length} need repair; ${dispositionedAll.length} dispositioned; ${blockedAll.length} rejected; ${unresolvedContradictionsAll.length} unresolved contradiction(s); ${waivers.length} waiver(s).`;\n })();\n\n return {\n pack_id: packId(input.research),\n pack_topic: input.research.topic,\n generated_at: input.generatedAt,\n mode,\n synthesis_allowed: synthesisAllowed,\n summary,\n sections,\n accepted_claim_ids: acceptedAll,\n repair_claim_ids: repairAll,\n blocked_claim_ids: blockedAll,\n dispositioned_claim_ids: dispositionedAll,\n unresolved_contradiction_ids: unresolvedContradictionsAll,\n waivers,\n gate_verdicts: gateVerdicts,\n review_decisions: reviewDecisionCounts,\n recommended_next_actions: buildRecommendedNextActions(sections, mode),\n allowed_write_paths: allowedWritePaths,\n forbidden_actions: FORBIDDEN_ACTIONS_ALWAYS,\n index_status: input.indexStatus,\n warnings: input.warnings,\n };\n}\n","import { z } from 'zod';\n\nexport const HandoffModeSchema = z.enum([\n 'repair_required',\n 'synthesis_ready',\n 'human_review_required',\n]);\n\nexport const IndexStatusSchema = z.enum(['present', 'missing']);\n\nexport const ProvenanceSummarySchema = z.object({\n accepted_count: z.number().int().nonnegative(),\n rejected_count: z.number().int().nonnegative(),\n triage_parked_count: z.number().int().nonnegative(),\n needs_review_undispositioned_count: z.number().int().nonnegative(),\n dispositioned_count: z.number().int().nonnegative(),\n dispositioned_breakdown: z.object({\n parked_not_for_synthesis: z.number().int().nonnegative(),\n preserved_for_human_note: z.number().int().nonnegative(),\n needs_human_review_excluded: z.number().int().nonnegative(),\n out_of_bounds_regression_fixture: z.number().int().nonnegative(),\n }),\n active_repair_blockers: z.number().int().nonnegative(),\n active_unresolved_contradictions: z.number().int().nonnegative(),\n waivers_active: z.array(z.string()),\n overrides_applied_count: z.number().int().nonnegative(),\n});\n\nexport const SectionStateSchema = z.object({\n section_id: z.string().regex(/^[0-9]{2}-[a-z0-9-]+$/),\n purpose: z.string(),\n status: z.string(),\n has_gate_run: z.boolean(),\n has_review_run: z.boolean(),\n gate_verdict: z.string().nullable(),\n synthesis_eligible: z.boolean(),\n accepted_claim_ids: z.array(z.string()),\n repair_claim_ids: z.array(z.string()),\n rejected_claim_ids: z.array(z.string()),\n dispositioned_claim_ids: z.array(z.string()).default([]),\n candidate_claims_total: z.number().int().nonnegative(),\n unresolved_contradiction_ids: z.array(z.string()),\n blocking_reasons: z.array(z.string()),\n active_blockers: z.array(z.string()).default([]),\n blocking_contradictions_unresolved: z.number().int().nonnegative(),\n provenance_summary: ProvenanceSummarySchema.optional(),\n});\n\nexport const WaiverEntrySchema = z.object({\n scope: z.enum(['pack', 'gate']),\n family: z.string(),\n reason: z.string(),\n compensating_controls: z.array(z.string()),\n applied_to: z.string(),\n});\n\nexport const GateVerdictEntrySchema = z.object({\n section_id: z.string(),\n verdict: z.string(),\n synthesis_eligible: z.boolean(),\n});\n\nexport const ReviewDecisionCountSchema = z.object({\n section_id: z.string(),\n decision: z.string(),\n count: z.number().int().nonnegative(),\n});\n\nexport const CoworkHandoffPayloadSchema = z.object({\n pack_id: z.string(),\n pack_topic: z.string(),\n generated_at: z.string(),\n mode: HandoffModeSchema,\n synthesis_allowed: z.boolean(),\n summary: z.string(),\n sections: z.array(SectionStateSchema),\n accepted_claim_ids: z.array(z.string()),\n repair_claim_ids: z.array(z.string()),\n blocked_claim_ids: z.array(z.string()),\n dispositioned_claim_ids: z.array(z.string()).default([]),\n unresolved_contradiction_ids: z.array(z.string()),\n waivers: z.array(WaiverEntrySchema),\n gate_verdicts: z.array(GateVerdictEntrySchema),\n review_decisions: z.array(ReviewDecisionCountSchema),\n recommended_next_actions: z.array(z.string()),\n allowed_write_paths: z.array(z.string()),\n forbidden_actions: z.array(z.string()),\n index_status: IndexStatusSchema,\n warnings: z.array(z.string()),\n});\n\nexport type CoworkHandoffPayload = z.infer<typeof CoworkHandoffPayloadSchema>;\n","import type { CoworkHandoffPayload, HandoffMode } from './types.js';\n\nconst MODE_GLYPH: Record<HandoffMode, string> = {\n repair_required: '[REPAIR REQUIRED]',\n synthesis_ready: '[SYNTHESIS READY]',\n human_review_required: '[HUMAN REVIEW REQUIRED]',\n};\n\nconst MODE_NARRATIVE: Record<HandoffMode, string> = {\n repair_required:\n 'The pack is not ready for synthesis. At least one section is blocked, has unrun gates/review, or has claims that need repair. Your job is to gather more sources, repair scope/source issues, re-run gates and review, and document open questions. **You may not write final synthesis prose in this mode.**',\n synthesis_ready:\n 'Required sections are synthesis-eligible, accepted claims exist, no unwaived blocking contradictions remain. You may perform cross-section synthesis using accepted claim_ids only. You may not introduce new facts or cite outside the source ledger.',\n human_review_required:\n 'The pack contains unresolved waivers, blocking contradictions, malformed artifacts, or ambiguous review states. Stop. Prepare options for the operator in `handoffs/cowork-options.md`. **You may not decide on these issues yourself.**',\n};\n\nconst MODE_ALLOWED: Record<HandoffMode, string[]> = {\n repair_required: [\n 'Run `research-os gather <section> --url ...` to add sources where the source-floor gate is failing.',\n 'Run `research-os claim extract <section>` after adding sources.',\n 'Run `research-os contradict map <section>` and `research-os review <section>` to refresh tension and review state.',\n 'Re-run `research-os gate <section>` to determine if synthesis-eligibility has been earned.',\n 'Re-run `research-os index build --all` and `research-os cowork handoff` to refresh the runtime contract.',\n 'Write working notes to `handoffs/cowork-notes.md` and per-section `open_questions.md`.',\n ],\n synthesis_ready: [\n 'Reason across sections to draft `synthesis/cross-section-map.md`.',\n 'Produce `synthesis/decision-brief.md` answering the pack\\'s `decision` field, citing only accepted_claim_ids.',\n 'Draft `synthesis/final-report.md` if (and only if) the decision brief is honest about unresolved tensions.',\n 'Use `research-os query \"<term>\"` to retrieve grounded artifacts; never paraphrase past the indexed evidence.',\n ],\n human_review_required: [\n 'Read the pack state below.',\n 'Surface the unresolved issues to the operator in `handoffs/cowork-options.md` with proposed options, no decisions.',\n 'Stop after the options document is written.',\n ],\n};\n\nexport function renderCoworkMaster(payload: CoworkHandoffPayload): string {\n const lines: string[] = [];\n lines.push(`# Cowork Handoff: ${payload.pack_topic}`);\n lines.push('');\n lines.push(`**Pack ID:** \\`${payload.pack_id}\\``);\n lines.push(`**Mode:** ${MODE_GLYPH[payload.mode]} ${payload.mode}`);\n lines.push(`**Synthesis allowed:** ${payload.synthesis_allowed ? 'yes' : 'no'}`);\n lines.push(`**Generated:** ${payload.generated_at}`);\n lines.push(`**Index:** ${payload.index_status}`);\n lines.push('');\n lines.push(`> ${payload.summary}`);\n lines.push('');\n\n lines.push('## Operating mode');\n lines.push('');\n lines.push(MODE_NARRATIVE[payload.mode]);\n lines.push('');\n\n lines.push('## What you may do');\n lines.push('');\n for (const a of MODE_ALLOWED[payload.mode]) lines.push(`- ${a}`);\n lines.push('');\n\n lines.push('## What you may not do (always — these are pack invariants)');\n lines.push('');\n for (const a of payload.forbidden_actions) lines.push(`- ${a}`);\n lines.push('');\n\n lines.push('## Pack state');\n lines.push('');\n if (payload.sections.length === 0) {\n lines.push('No sections in this pack.');\n } else {\n lines.push('| Section | Status | Gate verdict | Synthesis-eligible | Candidate claims | Accepted | Need repair | Rejected | Unresolved contradictions |');\n lines.push('|---|---|---|---|---|---|---|---|---|');\n for (const s of payload.sections) {\n lines.push(\n `| \\`${s.section_id}\\` | ${s.status} | ${s.gate_verdict ?? '—'} | ${s.synthesis_eligible ? 'yes' : 'no'} | ${s.candidate_claims_total} | ${s.accepted_claim_ids.length} | ${s.repair_claim_ids.length} | ${s.rejected_claim_ids.length} | ${s.unresolved_contradiction_ids.length} |`,\n );\n }\n }\n lines.push('');\n\n lines.push('### Accepted claims (synthesis-ready)');\n lines.push('');\n if (payload.accepted_claim_ids.length === 0) {\n lines.push('_No claims have been accepted for synthesis. Synthesis is not allowed in this handoff._');\n } else {\n for (const cid of payload.accepted_claim_ids) lines.push(`- \\`${cid}\\``);\n }\n lines.push('');\n\n lines.push('### Claims needing repair');\n lines.push('');\n if (payload.repair_claim_ids.length === 0) {\n lines.push('_None._');\n } else {\n for (const cid of payload.repair_claim_ids) lines.push(`- \\`${cid}\\``);\n }\n lines.push('');\n\n lines.push('### Rejected claims');\n lines.push('');\n if (payload.blocked_claim_ids.length === 0) {\n lines.push('_None._');\n } else {\n for (const cid of payload.blocked_claim_ids) lines.push(`- \\`${cid}\\``);\n }\n lines.push('');\n\n lines.push('### Unresolved contradictions');\n lines.push('');\n if (payload.unresolved_contradiction_ids.length === 0) {\n lines.push('_None._');\n } else {\n for (const id of payload.unresolved_contradiction_ids) lines.push(`- \\`${id}\\``);\n }\n lines.push('');\n\n lines.push('### Active waivers');\n lines.push('');\n if (payload.waivers.length === 0) {\n lines.push('_None._');\n } else {\n for (const w of payload.waivers) {\n lines.push(`- **${w.scope}.${w.family}** applied to \\`${w.applied_to}\\``);\n lines.push(` - Reason: ${w.reason || '_(empty — INVALID)_'}`);\n if (w.compensating_controls.length === 0) {\n lines.push(` - Compensating controls: _(none — INVALID)_`);\n } else {\n for (const c of w.compensating_controls) lines.push(` - Compensating: ${c}`);\n }\n }\n }\n lines.push('');\n\n lines.push('## Recommended next actions');\n lines.push('');\n if (payload.recommended_next_actions.length === 0) {\n lines.push('_(none recommended)_');\n } else {\n let i = 1;\n for (const a of payload.recommended_next_actions) {\n lines.push(`${i}. ${a}`);\n i += 1;\n }\n }\n lines.push('');\n\n lines.push('## Allowed write paths');\n lines.push('');\n for (const p of payload.allowed_write_paths) lines.push(`- \\`${p}\\``);\n lines.push('');\n\n lines.push('## Useful index queries');\n lines.push('');\n lines.push('- `research-os query \"source_floor\"` — surface gate failures grounded in audit JSON.');\n lines.push('- `research-os query \"source_cluster_monopoly\"` — find publisher-monopoly findings and the claims they touch.');\n lines.push('- `research-os query \"candidate\" --type claim` — list candidate claims that haven\\'t been accepted yet.');\n lines.push('- `research-os query \"blocked\" --type gate_result` — every gate that blocks synthesis.');\n lines.push('- `research-os query \"<term>\"` — full-text search; every hit points to a canonical artifact path.');\n lines.push('');\n\n lines.push('## Stop conditions');\n lines.push('');\n if (payload.mode === 'synthesis_ready') {\n lines.push('- Final synthesis artifacts written to `synthesis/`.');\n } else if (payload.mode === 'human_review_required') {\n lines.push('- `handoffs/cowork-options.md` written with proposed options for operator review.');\n } else {\n lines.push('- All blocked sections become synthesis-eligible OR mode flips to `human_review_required`.');\n lines.push('- Repair budget for the pack is exhausted (re-run handoff to confirm).');\n }\n lines.push('- Pack-level `max_runtime_minutes` (in `research.yaml`) is exhausted — surface partial state honestly.');\n lines.push('');\n\n lines.push('## Final instruction');\n lines.push('');\n lines.push('Do not introduce unsupported claims. Preserve unresolved contradictions. Do not widen scope beyond the source-tagged scope. Cite only `claim_id` and `source_id` values that already exist in this pack. The pack is the source of authority — this handoff is a layout step, not new truth.');\n lines.push('');\n\n if (payload.warnings.length > 0) {\n lines.push('## Warnings (from handoff generation)');\n lines.push('');\n for (const w of payload.warnings) lines.push(`- ${w}`);\n lines.push('');\n }\n\n return lines.join('\\n');\n}\n","import { existsSync } from 'node:fs';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { join, resolve } from 'node:path';\nimport { parse as yamlParse } from 'yaml';\n\nimport { PackNotFoundError } from '../errors.js';\nimport { ResearchYamlSchema, type ResearchYaml } from '../intake/schema.js';\nimport { ClaimSchema, type Claim } from '../claims/schema.js';\nimport { ContradictionSchema, type Contradiction } from '../contradictions/schema.js';\nimport { ContradictionResolutionSchema, type ContradictionResolution } from '../contradictions/resolution-schema.js';\nimport { ClaimSynthesisDispositionSchema, type ClaimSynthesisDisposition } from '../dispositions/schema.js';\nimport { SectionGateResultSchema, type SectionGateResult } from '../gates/schema.js';\nimport { ClaimReviewSchema, type ClaimReview } from '../review/schema.js';\nimport { indexDbPath } from '../indexer/db.js';\n\nimport { derive, type DeriveInput } from './derive.js';\nimport { CoworkHandoffPayloadSchema } from './schema.js';\nimport { renderCoworkMaster } from './markdown.js';\nimport type { HandoffOptions, HandoffSummary } from './types.js';\n\nasync function loadResearchYaml(packPath: string): Promise<ResearchYaml> {\n const yamlPath = join(packPath, 'research.yaml');\n if (!existsSync(yamlPath)) throw new PackNotFoundError(packPath);\n const text = await readFile(yamlPath, 'utf8');\n return ResearchYamlSchema.parse(yamlParse(text));\n}\n\nasync function readJsonl<T>(\n path: string,\n parse: (raw: unknown) => T,\n warnings: string[],\n): Promise<T[]> {\n if (!existsSync(path)) return [];\n const text = await readFile(path, 'utf8');\n const out: T[] = [];\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n out.push(parse(JSON.parse(line)));\n } catch (err) {\n const msg = err instanceof Error ? err.message : 'parse error';\n warnings.push(`malformed line in ${path}: ${msg}`);\n }\n }\n return out;\n}\n\nasync function readGate(\n packPath: string,\n sectionId: string,\n warnings: string[],\n): Promise<SectionGateResult | null> {\n const path = join(packPath, 'audits', `${sectionId}-gate.json`);\n if (!existsSync(path)) return null;\n try {\n const text = await readFile(path, 'utf8');\n return SectionGateResultSchema.parse(JSON.parse(text));\n } catch (err) {\n warnings.push(`malformed gate result at audits/${sectionId}-gate.json: ${err instanceof Error ? err.message : err}`);\n return null;\n }\n}\n\nexport async function handoff(options: HandoffOptions): Promise<HandoffSummary> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n const research = await loadResearchYaml(packPath);\n const warnings: string[] = [];\n\n const perSection: DeriveInput['perSection'] = new Map();\n for (const section of research.sections) {\n const sid = section.id;\n const claims = await readJsonl<Claim>(\n join(packPath, 'sections', sid, 'claims.jsonl'),\n (r) => ClaimSchema.parse(r),\n warnings,\n );\n const candidateClaims = claims.filter((c) => c.review_state === 'candidate');\n const claimReviews = await readJsonl<ClaimReview>(\n join(packPath, 'sections', sid, 'claim-reviews.jsonl'),\n (r) => ClaimReviewSchema.parse(r),\n warnings,\n );\n const contradictions = await readJsonl<Contradiction>(\n join(packPath, 'sections', sid, 'contradictions.jsonl'),\n (r) => ContradictionSchema.parse(r),\n warnings,\n );\n const resolutions = await readJsonl<ContradictionResolution>(\n join(packPath, 'sections', sid, 'contradiction-resolutions.jsonl'),\n (r) => ContradictionResolutionSchema.parse(r),\n warnings,\n );\n const dispositions = await readJsonl<ClaimSynthesisDisposition>(\n join(packPath, 'sections', sid, 'claim-synthesis-dispositions.jsonl'),\n (r) => ClaimSynthesisDispositionSchema.parse(r),\n warnings,\n );\n const gate = await readGate(packPath, sid, warnings);\n perSection.set(sid, { gate, candidateClaims, claimReviews, contradictions, resolutions, dispositions });\n }\n\n const indexExists = existsSync(indexDbPath(packPath));\n if (!indexExists) {\n warnings.push(\n 'Pack-local index missing at .research-os/index.sqlite — Cowork can still operate from canonical artifacts, but `research-os query` will refuse until you run `research-os index build --all`.',\n );\n }\n\n const generatedAt = new Date().toISOString();\n const payload = CoworkHandoffPayloadSchema.parse(\n derive({\n research,\n perSection,\n indexStatus: indexExists ? 'present' : 'missing',\n generatedAt,\n warnings,\n }),\n );\n\n const handoffsDir = join(packPath, 'handoffs');\n await mkdir(handoffsDir, { recursive: true });\n const jsonPath = join(handoffsDir, 'cowork-handoff.json');\n const mdPath = join(handoffsDir, 'cowork-master.md');\n await writeFile(jsonPath, JSON.stringify(payload, null, 2), 'utf8');\n await writeFile(mdPath, renderCoworkMaster(payload), 'utf8');\n\n return {\n packId: payload.pack_id,\n packTopic: payload.pack_topic,\n mode: payload.mode,\n synthesisAllowed: payload.synthesis_allowed,\n jsonPath,\n markdownPath: mdPath,\n warnings,\n acceptedCount: payload.accepted_claim_ids.length,\n repairCount: payload.repair_claim_ids.length,\n blockedCount: payload.blocked_claim_ids.length,\n };\n}\n","export { handoff } from './run.js';\nexport { derive, FORBIDDEN_ACTIONS_ALWAYS } from './derive.js';\nexport { renderCoworkMaster } from './markdown.js';\nexport {\n HandoffModeSchema,\n IndexStatusSchema,\n SectionStateSchema,\n WaiverEntrySchema,\n GateVerdictEntrySchema,\n ReviewDecisionCountSchema,\n CoworkHandoffPayloadSchema,\n} from './schema.js';\nexport type {\n HandoffMode,\n IndexStatus,\n SectionState,\n WaiverEntry,\n GateVerdictEntry,\n ReviewDecisionCount,\n CoworkHandoffPayload,\n HandoffOptions,\n HandoffSummary,\n} from './types.js';\n","import { createHash } from 'node:crypto';\n\nimport type { Claim } from '../claims/schema.js';\nimport type { ClaimReview } from '../review/schema.js';\nimport type { Contradiction } from '../contradictions/schema.js';\nimport type { SourceCard } from '../sources/schema.js';\nimport type { ResearchYaml } from '../intake/schema.js';\nimport type { CoworkHandoffPayload } from '../cowork/schema.js';\nimport { jaccardSimilarity } from '../contradictions/scope.js';\n\nimport type {\n AllowedSynthesisInput,\n ClaimCluster,\n CrossSectionContradictionRef,\n CrossSectionMap,\n ForbiddenInput,\n ScopeOverlap,\n SectionAcceptedSummary,\n SharedSource,\n WaiverDependency,\n} from './types.js';\n\nconst SCOPE_OVERLAP_THRESHOLD = 0.3;\n\nexport interface DeriveMapInput {\n research: ResearchYaml;\n handoff: CoworkHandoffPayload;\n claimsBySection: Map<string, Claim[]>;\n reviewsBySection: Map<string, ClaimReview[]>;\n contradictionsBySection: Map<string, Contradiction[]>;\n sources: SourceCard[];\n generatedAt: string;\n}\n\nfunction latestDecisionByClaim(reviews: ClaimReview[]): Map<string, ClaimReview> {\n const map = new Map<string, ClaimReview>();\n for (const r of reviews) {\n const existing = map.get(r.claim_id);\n if (!existing || r.created_at > existing.created_at) {\n map.set(r.claim_id, r);\n }\n }\n return map;\n}\n\nfunction clusterClaimsBySharedSources(claims: Claim[]): ClaimCluster[] {\n const parent = new Map<string, string>();\n const find = (a: string): string => {\n let root = a;\n while (parent.get(root) && parent.get(root) !== root) {\n root = parent.get(root)!;\n }\n if (!parent.has(root)) parent.set(root, root);\n return root;\n };\n const union = (a: string, b: string): void => {\n const ra = find(a);\n const rb = find(b);\n if (ra !== rb) parent.set(ra, rb);\n };\n\n for (const c of claims) parent.set(c.claim_id, c.claim_id);\n\n for (let i = 0; i < claims.length; i += 1) {\n for (let j = i + 1; j < claims.length; j += 1) {\n const shared = claims[i]!.source_ids.filter((s) => claims[j]!.source_ids.includes(s));\n if (shared.length > 0) union(claims[i]!.claim_id, claims[j]!.claim_id);\n }\n }\n\n const groups = new Map<string, Claim[]>();\n for (const c of claims) {\n const root = find(c.claim_id);\n if (!groups.has(root)) groups.set(root, []);\n groups.get(root)!.push(c);\n }\n\n const clusters: ClaimCluster[] = [];\n for (const [, members] of groups) {\n if (members.length === 0) continue;\n const sharedSet = new Set<string>();\n for (let i = 0; i < members.length; i += 1) {\n for (let j = i + 1; j < members.length; j += 1) {\n for (const sid of members[i]!.source_ids) {\n if (members[j]!.source_ids.includes(sid)) sharedSet.add(sid);\n }\n }\n }\n const memberIds = members.map((m) => m.claim_id).sort();\n const sections = Array.from(new Set(members.map((m) => m.section_id))).sort();\n const clusterId = `cls_${createHash('sha256').update(memberIds.join('|')).digest('hex').slice(0, 12)}`;\n clusters.push({\n cluster_id: clusterId,\n shared_source_ids: Array.from(sharedSet).sort(),\n member_claim_ids: memberIds,\n spans_sections: sections,\n });\n }\n return clusters;\n}\n\nfunction buildSharedSources(\n acceptedClaims: Claim[],\n sources: SourceCard[],\n): SharedSource[] {\n const usage = new Map<string, { claims: Set<string>; sections: Set<string> }>();\n for (const c of acceptedClaims) {\n for (const sid of c.source_ids) {\n if (!usage.has(sid)) {\n usage.set(sid, { claims: new Set(), sections: new Set() });\n }\n usage.get(sid)!.claims.add(c.claim_id);\n usage.get(sid)!.sections.add(c.section_id);\n }\n }\n const out: SharedSource[] = [];\n for (const [sid, { claims: cs, sections: secs }] of usage) {\n if (cs.size < 2 && secs.size < 2) continue;\n const card = sources.find((s) => s.source_id === sid);\n out.push({\n source_id: sid,\n publisher: card?.publisher ?? null,\n source_type: card?.source_type ?? 'unknown',\n used_by_claim_ids: Array.from(cs).sort(),\n spans_sections: Array.from(secs).sort(),\n });\n }\n return out;\n}\n\nfunction buildScopeOverlaps(acceptedClaims: Claim[]): ScopeOverlap[] {\n const out: ScopeOverlap[] = [];\n for (let i = 0; i < acceptedClaims.length; i += 1) {\n for (let j = i + 1; j < acceptedClaims.length; j += 1) {\n const a = acceptedClaims[i]!;\n const b = acceptedClaims[j]!;\n if (a.scope === null || b.scope === null) continue;\n const sim = jaccardSimilarity(a.scope, b.scope);\n if (sim < SCOPE_OVERLAP_THRESHOLD) continue;\n const crossSection = a.section_id !== b.section_id;\n const warning = crossSection\n ? `Cross-section scope overlap (jaccard=${sim.toFixed(2)}). Synthesis must not silently merge these claims; cite each separately and note their scope.`\n : `In-section scope overlap (jaccard=${sim.toFixed(2)}). Synthesis must keep each claim's scope tag intact.`;\n out.push({\n claim_a: a.claim_id,\n claim_b: b.claim_id,\n scope_a: a.scope,\n scope_b: b.scope,\n jaccard: Number(sim.toFixed(4)),\n cross_section: crossSection,\n warning,\n });\n }\n }\n return out;\n}\n\nfunction buildCrossSectionContradictions(\n byClaim: Map<string, string>,\n contradictionsBySection: Map<string, Contradiction[]>,\n): CrossSectionContradictionRef[] {\n const out: CrossSectionContradictionRef[] = [];\n for (const list of contradictionsBySection.values()) {\n for (const c of list) {\n const sections = new Set<string>();\n for (const cid of c.claim_ids) {\n const sec = byClaim.get(cid);\n if (sec) sections.add(sec);\n }\n if (sections.size <= 1) continue;\n out.push({\n contradiction_id: c.contradiction_id,\n claim_ids: c.claim_ids,\n sections: Array.from(sections).sort(),\n type: c.type,\n severity: c.severity,\n status: c.status,\n });\n }\n }\n return out;\n}\n\nfunction buildWaiverDependencies(handoff: CoworkHandoffPayload): WaiverDependency[] {\n return handoff.waivers.map((w) => ({\n scope: w.scope,\n family: w.family,\n reason: w.reason,\n compensating_controls: w.compensating_controls,\n applied_to: w.applied_to,\n must_disclose_in: 'both' as const,\n }));\n}\n\nfunction buildSectionsSummary(\n research: ResearchYaml,\n handoff: CoworkHandoffPayload,\n): SectionAcceptedSummary[] {\n return research.sections.map((s) => {\n const handoffSection = handoff.sections.find((hs) => hs.section_id === s.id);\n const accepted = handoffSection?.accepted_claim_ids ?? [];\n let excludedReason: string | null = null;\n if (handoffSection) {\n if (!handoffSection.synthesis_eligible) {\n excludedReason = `Section gate verdict ${handoffSection.gate_verdict ?? 'unknown'}; synthesis-eligible=false.`;\n } else if (accepted.length === 0) {\n excludedReason = 'No claims accepted for synthesis in this section.';\n }\n } else {\n excludedReason = 'No handoff entry for this section.';\n }\n return {\n section_id: s.id,\n purpose: s.purpose,\n status: s.status,\n accepted_claim_ids: accepted,\n excluded_reason: excludedReason,\n };\n });\n}\n\nexport function deriveCrossSectionMap(input: DeriveMapInput): CrossSectionMap {\n const acceptedSet = new Set(input.handoff.accepted_claim_ids);\n const acceptedClaims: Claim[] = [];\n const claimToSection = new Map<string, string>();\n for (const [sectionId, claims] of input.claimsBySection) {\n for (const c of claims) {\n claimToSection.set(c.claim_id, sectionId);\n if (acceptedSet.has(c.claim_id)) acceptedClaims.push(c);\n }\n }\n\n const claimClusters = clusterClaimsBySharedSources(acceptedClaims);\n const sharedSources = buildSharedSources(acceptedClaims, input.sources);\n const scopeOverlaps = buildScopeOverlaps(acceptedClaims);\n const crossSectionContradictions = buildCrossSectionContradictions(\n claimToSection,\n input.contradictionsBySection,\n );\n\n const allowedInputs: AllowedSynthesisInput[] = acceptedClaims.map((c) => ({\n claim_id: c.claim_id,\n section_id: c.section_id,\n artifact_path: `sections/${c.section_id}/claims.jsonl`,\n asserts: c.asserts,\n scope: c.scope,\n not: c.not,\n source_ids: c.source_ids,\n }));\n\n const forbidden: ForbiddenInput[] = [];\n for (const [sectionId, claims] of input.claimsBySection) {\n const reviews = input.reviewsBySection.get(sectionId) ?? [];\n const latest = latestDecisionByClaim(reviews);\n for (const c of claims) {\n if (acceptedSet.has(c.claim_id)) continue;\n const decision = latest.get(c.claim_id)?.decision ?? 'no_review';\n forbidden.push({\n claim_id: c.claim_id,\n section_id: sectionId,\n decision,\n reason:\n decision === 'rejected'\n ? 'Claim rejected by adversarial review.'\n : decision === 'no_review'\n ? 'Claim has no review decision; cannot be cited in synthesis.'\n : `Claim status is \"${decision}\"; only accepted_for_synthesis claims may enter synthesis.`,\n });\n }\n }\n\n return {\n pack_id: input.handoff.pack_id,\n pack_topic: input.research.topic,\n pack_decision: input.research.decision,\n generated_at: input.generatedAt,\n accepted_claim_ids: input.handoff.accepted_claim_ids,\n sections: buildSectionsSummary(input.research, input.handoff),\n claim_clusters: claimClusters,\n shared_sources: sharedSources,\n scope_overlaps: scopeOverlaps,\n cross_section_contradictions: crossSectionContradictions,\n waiver_dependencies: buildWaiverDependencies(input.handoff),\n open_questions: [],\n allowed_synthesis_inputs: allowedInputs,\n forbidden_inputs: forbidden,\n };\n}\n","import { z } from 'zod';\n\nexport const SectionAcceptedSummarySchema = z.object({\n section_id: z.string().regex(/^[0-9]{2}-[a-z0-9-]+$/),\n purpose: z.string(),\n status: z.string(),\n accepted_claim_ids: z.array(z.string()),\n excluded_reason: z.string().nullable(),\n});\n\nexport const ClaimClusterSchema = z.object({\n cluster_id: z.string(),\n shared_source_ids: z.array(z.string()),\n member_claim_ids: z.array(z.string()).min(1),\n spans_sections: z.array(z.string()),\n});\n\nexport const SharedSourceSchema = z.object({\n source_id: z.string(),\n publisher: z.string().nullable(),\n source_type: z.string(),\n used_by_claim_ids: z.array(z.string()),\n spans_sections: z.array(z.string()),\n});\n\nexport const ScopeOverlapSchema = z.object({\n claim_a: z.string(),\n claim_b: z.string(),\n scope_a: z.string().nullable(),\n scope_b: z.string().nullable(),\n jaccard: z.number().min(0).max(1),\n cross_section: z.boolean(),\n warning: z.string(),\n});\n\nexport const CrossSectionContradictionRefSchema = z.object({\n contradiction_id: z.string(),\n claim_ids: z.array(z.string()),\n sections: z.array(z.string()),\n type: z.string(),\n severity: z.string(),\n status: z.string(),\n});\n\nexport const WaiverDependencySchema = z.object({\n scope: z.enum(['pack', 'gate']),\n family: z.string(),\n reason: z.string(),\n compensating_controls: z.array(z.string()),\n applied_to: z.string(),\n must_disclose_in: z.enum(['decision-brief.md', 'final-report.md', 'both']),\n});\n\nexport const AllowedSynthesisInputSchema = z.object({\n claim_id: z.string(),\n section_id: z.string(),\n artifact_path: z.string(),\n asserts: z.string(),\n scope: z.string().nullable(),\n not: z.string().nullable(),\n source_ids: z.array(z.string()),\n});\n\nexport const ForbiddenInputSchema = z.object({\n claim_id: z.string(),\n section_id: z.string(),\n decision: z.string(),\n reason: z.string(),\n});\n\nexport const CrossSectionMapSchema = z.object({\n pack_id: z.string(),\n pack_topic: z.string(),\n pack_decision: z.string(),\n generated_at: z.string(),\n accepted_claim_ids: z.array(z.string()),\n sections: z.array(SectionAcceptedSummarySchema),\n claim_clusters: z.array(ClaimClusterSchema),\n shared_sources: z.array(SharedSourceSchema),\n scope_overlaps: z.array(ScopeOverlapSchema),\n cross_section_contradictions: z.array(CrossSectionContradictionRefSchema),\n waiver_dependencies: z.array(WaiverDependencySchema),\n open_questions: z.array(z.string()),\n allowed_synthesis_inputs: z.array(AllowedSynthesisInputSchema),\n forbidden_inputs: z.array(ForbiddenInputSchema),\n});\n\nexport type CrossSectionMap = z.infer<typeof CrossSectionMapSchema>;\n","import type { CrossSectionMap } from './types.js';\n\nexport function renderCrossSectionMapMarkdown(map: CrossSectionMap): string {\n const lines: string[] = [];\n lines.push(`# Cross-Section Map: ${map.pack_topic}`);\n lines.push('');\n lines.push(`**Pack ID:** \\`${map.pack_id}\\``);\n lines.push(`**Pack decision:** ${map.pack_decision || '_(no decision recorded in research.yaml)_'}`);\n lines.push(`**Generated:** ${map.generated_at}`);\n lines.push(`**Accepted claims:** ${map.accepted_claim_ids.length}`);\n lines.push('');\n lines.push(\n '> This map points at canonical artifacts. It does not synthesize. It does not infer across claims. Use it as a routing layer when drafting `decision-brief.md` and `working-report.md`. The pack is the source of authority.',\n );\n lines.push('');\n\n lines.push('## Accepted claims by section');\n lines.push('');\n for (const s of map.sections) {\n if (s.accepted_claim_ids.length === 0) {\n lines.push(`### \\`${s.section_id}\\` — excluded`);\n lines.push('');\n lines.push(`- **Purpose:** ${s.purpose}`);\n lines.push(`- **Status:** ${s.status}`);\n lines.push(`- **Excluded reason:** ${s.excluded_reason ?? '_(no reason recorded)_'}`);\n lines.push('');\n } else {\n lines.push(`### \\`${s.section_id}\\` — ${s.accepted_claim_ids.length} accepted claim(s)`);\n lines.push('');\n lines.push(`- **Purpose:** ${s.purpose}`);\n lines.push(`- **Status:** ${s.status}`);\n lines.push('- **Accepted claims:**');\n for (const cid of s.accepted_claim_ids) {\n lines.push(` - \\`${cid}\\``);\n }\n lines.push('');\n }\n }\n\n lines.push('## Shared source relationships');\n lines.push('');\n if (map.shared_sources.length === 0) {\n lines.push('_No sources are shared across multiple accepted claims or sections._');\n } else {\n for (const s of map.shared_sources) {\n lines.push(`- \\`${s.source_id}\\` (publisher: ${s.publisher ?? 'unknown'}, type: ${s.source_type})`);\n lines.push(` - Used by: ${s.used_by_claim_ids.map((c) => `\\`${c}\\``).join(', ')}`);\n lines.push(` - Spans sections: ${s.spans_sections.map((s) => `\\`${s}\\``).join(', ')}`);\n }\n }\n lines.push('');\n\n lines.push('## Claim clusters (shared sources within an accepted set)');\n lines.push('');\n if (map.claim_clusters.length === 0) {\n lines.push('_No clusters detected._');\n } else {\n for (const c of map.claim_clusters) {\n lines.push(`### Cluster \\`${c.cluster_id}\\``);\n lines.push('');\n lines.push(`- **Members:** ${c.member_claim_ids.map((m) => `\\`${m}\\``).join(', ')}`);\n lines.push(`- **Spans sections:** ${c.spans_sections.map((s) => `\\`${s}\\``).join(', ')}`);\n lines.push(`- **Shared source IDs:** ${c.shared_source_ids.length === 0 ? '(singleton)' : c.shared_source_ids.map((s) => `\\`${s}\\``).join(', ')}`);\n lines.push('');\n }\n }\n\n lines.push('## Scope overlap warnings');\n lines.push('');\n if (map.scope_overlaps.length === 0) {\n lines.push('_No scope overlaps above the configured threshold._');\n } else {\n for (const o of map.scope_overlaps) {\n lines.push(`- \\`${o.claim_a}\\` ↔ \\`${o.claim_b}\\` (jaccard ${o.jaccard}, ${o.cross_section ? 'cross-section' : 'in-section'})`);\n lines.push(` - Scope A: ${o.scope_a}`);\n lines.push(` - Scope B: ${o.scope_b}`);\n lines.push(` - Warning: ${o.warning}`);\n }\n }\n lines.push('');\n\n lines.push('## Cross-section contradictions (must be preserved)');\n lines.push('');\n if (map.cross_section_contradictions.length === 0) {\n lines.push('_None recorded._');\n } else {\n for (const c of map.cross_section_contradictions) {\n lines.push(`- \\`${c.contradiction_id}\\` — type: ${c.type}, severity: ${c.severity}, status: ${c.status}`);\n lines.push(` - Claims: ${c.claim_ids.map((id) => `\\`${id}\\``).join(', ')}`);\n lines.push(` - Sections: ${c.sections.map((s) => `\\`${s}\\``).join(', ')}`);\n }\n }\n lines.push('');\n\n lines.push('## Waivers (must be disclosed in any synthesis output)');\n lines.push('');\n if (map.waiver_dependencies.length === 0) {\n lines.push('_None active._');\n } else {\n for (const w of map.waiver_dependencies) {\n lines.push(`- **${w.scope}.${w.family}** applied to \\`${w.applied_to}\\` — disclose in: ${w.must_disclose_in}`);\n lines.push(` - Reason: ${w.reason || '_(empty — INVALID)_'}`);\n if (w.compensating_controls.length === 0) {\n lines.push(' - Compensating controls: _(none — INVALID)_');\n } else {\n for (const cc of w.compensating_controls) lines.push(` - Compensating: ${cc}`);\n }\n }\n }\n lines.push('');\n\n lines.push('## Sections excluded from synthesis');\n lines.push('');\n const excluded = map.sections.filter((s) => s.excluded_reason !== null);\n if (excluded.length === 0) {\n lines.push('_All sections contributed accepted claims._');\n } else {\n for (const s of excluded) {\n lines.push(`- \\`${s.section_id}\\`: ${s.excluded_reason}`);\n }\n }\n lines.push('');\n\n lines.push('## Useful index queries');\n lines.push('');\n lines.push('- `research-os query \"<scope-term>\"` — pull claims by scope tag');\n lines.push('- `research-os query \"<source-id>\" --type claim` — claims that cite a specific source');\n lines.push('- `research-os query \"blocking\" --type gate_result` — re-confirm no blocking gate failures before drafting');\n lines.push('- `research-os query \"unresolved\" --type contradiction` — re-confirm cross-section contradictions are still tracked');\n lines.push('');\n\n lines.push('## Forbidden inputs');\n lines.push('');\n if (map.forbidden_inputs.length === 0) {\n lines.push('_All claims in the pack are accepted for synthesis._');\n } else {\n lines.push('Synthesis must not cite any of the following claims:');\n lines.push('');\n for (const f of map.forbidden_inputs) {\n lines.push(`- \\`${f.claim_id}\\` (\\`${f.section_id}\\`, decision=${f.decision}): ${f.reason}`);\n }\n }\n lines.push('');\n\n return lines.join('\\n');\n}\n\nconst COMMON_GUARDRAILS = [\n '- **Cite only `claim_id` values listed in `synthesis/cross-section-map.json` under `allowed_synthesis_inputs[]`.**',\n '- **Do not introduce facts not present in the cited claims.**',\n '- **Do not flatten unresolved contradictions; preserve them by name.**',\n '- **Do not widen any claim\\'s `scope`; restate it verbatim where the claim is invoked.**',\n '- **Disclose every active waiver from `waiver_dependencies[]`.**',\n '- **Do not cite any claim listed under `forbidden_inputs[]`.**',\n];\n\nexport function renderDecisionBrief(map: CrossSectionMap): string {\n const lines: string[] = [];\n lines.push('# Decision Brief');\n lines.push('');\n lines.push(`**Pack:** ${map.pack_topic}`);\n lines.push(`**Pack ID:** \\`${map.pack_id}\\``);\n lines.push(`**Decision question:** ${map.pack_decision || '_(no decision recorded in research.yaml)_'}`);\n lines.push('');\n lines.push('> **Guardrails (enforced at freeze time):**');\n for (const g of COMMON_GUARDRAILS) lines.push(`> ${g}`);\n lines.push('> - **Recommendation must cite at least one accepted claim_id.**');\n lines.push('');\n lines.push('## Recommendation');\n lines.push('');\n lines.push('_(empty — Cowork or operator writes here. Cite accepted_claim_ids inline as `[claim:clm_...]`.)_');\n lines.push('');\n lines.push('## Evidence cited');\n lines.push('');\n lines.push('_(empty — list the accepted_claim_ids you actually cited above.)_');\n lines.push('');\n lines.push('## Unresolved contradictions preserved');\n lines.push('');\n if (map.cross_section_contradictions.length === 0) {\n lines.push('_None._');\n } else {\n for (const c of map.cross_section_contradictions) {\n lines.push(`- \\`${c.contradiction_id}\\` — ${c.type}, severity ${c.severity}`);\n }\n }\n lines.push('');\n lines.push('## Waivers disclosed');\n lines.push('');\n if (map.waiver_dependencies.length === 0) {\n lines.push('_None active._');\n } else {\n for (const w of map.waiver_dependencies) {\n lines.push(`- **${w.scope}.${w.family}** — ${w.reason}`);\n }\n }\n lines.push('');\n return lines.join('\\n');\n}\n\nexport function renderWorkingReport(map: CrossSectionMap): string {\n const lines: string[] = [];\n lines.push('# Working Report');\n lines.push('');\n lines.push(`**Pack:** ${map.pack_topic}`);\n lines.push(`**Pack ID:** \\`${map.pack_id}\\``);\n lines.push('');\n lines.push('> **Guardrails:**');\n lines.push('> - This is the working synthesis area. Drafts here are not final.');\n for (const g of COMMON_GUARDRAILS) lines.push(`> ${g}`);\n lines.push('> - **Every paragraph must cite at least one accepted_claim_id (inline `[claim:clm_...]`).**');\n lines.push('> - **Unresolved contradictions must remain visible in the prose, not summarized away.**');\n lines.push('');\n lines.push('## Working synthesis');\n lines.push('');\n lines.push('_(empty — Cowork drafts here.)_');\n lines.push('');\n return lines.join('\\n');\n}\n\nexport function renderFinalReport(map: CrossSectionMap): string {\n const lines: string[] = [];\n lines.push('# Final Report');\n lines.push('');\n lines.push(`**Pack:** ${map.pack_topic}`);\n lines.push(`**Pack ID:** \\`${map.pack_id}\\``);\n lines.push(`**Decision question:** ${map.pack_decision || '_(no decision recorded in research.yaml)_'}`);\n lines.push('');\n lines.push('> **Guardrails (locked area):**');\n lines.push('> - This file cannot be considered complete until the freeze step (Link 12) verifies citation coverage and claim-id existence.');\n lines.push('> - Until then, treat this as a draft. Do not promote it externally.');\n for (const g of COMMON_GUARDRAILS) lines.push(`> ${g}`);\n lines.push('');\n lines.push('## Summary');\n lines.push('');\n lines.push('_(empty — Cowork or operator writes here.)_');\n lines.push('');\n lines.push('## Body');\n lines.push('');\n lines.push('_(empty — Cowork or operator writes here.)_');\n lines.push('');\n lines.push('## Limitations and unresolved tensions');\n lines.push('');\n if (map.cross_section_contradictions.length === 0) {\n lines.push('_(empty — Cowork must list anything that the evidence base could not resolve.)_');\n } else {\n for (const c of map.cross_section_contradictions) {\n lines.push(`- \\`${c.contradiction_id}\\` — ${c.type}, severity ${c.severity}, status ${c.status}`);\n }\n }\n lines.push('');\n lines.push('## Waivers disclosed');\n lines.push('');\n if (map.waiver_dependencies.length === 0) {\n lines.push('_None active._');\n } else {\n for (const w of map.waiver_dependencies) {\n lines.push(`- **${w.scope}.${w.family}** applied to \\`${w.applied_to}\\` — ${w.reason}`);\n }\n }\n lines.push('');\n return lines.join('\\n');\n}\n","import { existsSync } from 'node:fs';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { join, resolve } from 'node:path';\nimport { parse as yamlParse } from 'yaml';\n\nimport { HandoffNotFoundError, PackNotFoundError } from '../errors.js';\nimport { ResearchYamlSchema, type ResearchYaml } from '../intake/schema.js';\nimport { ClaimSchema, type Claim } from '../claims/schema.js';\nimport { ClaimReviewSchema, type ClaimReview } from '../review/schema.js';\nimport { ContradictionSchema, type Contradiction } from '../contradictions/schema.js';\nimport { SourceCardSchema, type SourceCard } from '../sources/schema.js';\nimport { CoworkHandoffPayloadSchema, type CoworkHandoffPayload } from '../cowork/schema.js';\n\nimport { deriveCrossSectionMap } from './derive.js';\nimport { CrossSectionMapSchema } from './schema.js';\nimport {\n renderCrossSectionMapMarkdown,\n renderDecisionBrief,\n renderFinalReport,\n renderWorkingReport,\n} from './markdown.js';\nimport type { WorkspaceOptions, WorkspaceSummary } from './types.js';\n\nasync function readJsonl<T>(path: string, parse: (raw: unknown) => T): Promise<T[]> {\n if (!existsSync(path)) return [];\n const text = await readFile(path, 'utf8');\n const out: T[] = [];\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n out.push(parse(JSON.parse(line)));\n }\n return out;\n}\n\nasync function readSourceCards(packPath: string): Promise<SourceCard[]> {\n const dir = join(packPath, 'evidence', 'source-cards');\n if (!existsSync(dir)) return [];\n const { readdir } = await import('node:fs/promises');\n const entries = await readdir(dir);\n const cards: SourceCard[] = [];\n for (const entry of entries) {\n if (!entry.endsWith('.json')) continue;\n const text = await readFile(join(dir, entry), 'utf8');\n cards.push(SourceCardSchema.parse(JSON.parse(text)));\n }\n return cards;\n}\n\nexport async function workspace(options: WorkspaceOptions): Promise<WorkspaceSummary> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n const yamlPath = join(packPath, 'research.yaml');\n if (!existsSync(yamlPath)) throw new PackNotFoundError(packPath);\n const research: ResearchYaml = ResearchYamlSchema.parse(yamlParse(await readFile(yamlPath, 'utf8')));\n\n const handoffPath = join(packPath, 'handoffs', 'cowork-handoff.json');\n if (!existsSync(handoffPath)) throw new HandoffNotFoundError();\n const handoff: CoworkHandoffPayload = CoworkHandoffPayloadSchema.parse(\n JSON.parse(await readFile(handoffPath, 'utf8')),\n );\n\n if (handoff.mode !== 'synthesis_ready') {\n return {\n packPath,\n mode: handoff.mode,\n refused: true,\n refusalReason: `Synthesis workspace refused: pack is in ${handoff.mode} mode. Run 'research-os cowork handoff' for repair instructions.`,\n filesWritten: [],\n acceptedClaims: handoff.accepted_claim_ids.length,\n claimClusters: 0,\n scopeOverlaps: 0,\n crossSectionContradictions: 0,\n };\n }\n\n const claimsBySection = new Map<string, Claim[]>();\n const reviewsBySection = new Map<string, ClaimReview[]>();\n const contradictionsBySection = new Map<string, Contradiction[]>();\n for (const section of research.sections) {\n claimsBySection.set(\n section.id,\n await readJsonl<Claim>(join(packPath, 'sections', section.id, 'claims.jsonl'), (r) =>\n ClaimSchema.parse(r),\n ),\n );\n reviewsBySection.set(\n section.id,\n await readJsonl<ClaimReview>(\n join(packPath, 'sections', section.id, 'claim-reviews.jsonl'),\n (r) => ClaimReviewSchema.parse(r),\n ),\n );\n contradictionsBySection.set(\n section.id,\n await readJsonl<Contradiction>(\n join(packPath, 'sections', section.id, 'contradictions.jsonl'),\n (r) => ContradictionSchema.parse(r),\n ),\n );\n }\n const sources = await readSourceCards(packPath);\n\n const map = CrossSectionMapSchema.parse(\n deriveCrossSectionMap({\n research,\n handoff,\n claimsBySection,\n reviewsBySection,\n contradictionsBySection,\n sources,\n generatedAt: new Date().toISOString(),\n }),\n );\n\n const synthDir = join(packPath, 'synthesis');\n await mkdir(synthDir, { recursive: true });\n\n const filesWritten: string[] = [];\n const writeIfAbsent = async (relPath: string, content: string): Promise<void> => {\n const abs = join(synthDir, relPath);\n if (existsSync(abs)) return;\n await writeFile(abs, content, 'utf8');\n filesWritten.push(abs);\n };\n const writeAlways = async (relPath: string, content: string): Promise<void> => {\n const abs = join(synthDir, relPath);\n await writeFile(abs, content, 'utf8');\n filesWritten.push(abs);\n };\n\n // cross-section-map.* always regenerated (it's derived state)\n await writeAlways('cross-section-map.json', JSON.stringify(map, null, 2));\n await writeAlways('cross-section-map.md', renderCrossSectionMapMarkdown(map));\n\n // Writable workspaces only created if absent — Cowork's drafts are preserved across re-runs\n await writeIfAbsent('decision-brief.md', renderDecisionBrief(map));\n await writeIfAbsent('working-report.md', renderWorkingReport(map));\n await writeIfAbsent('final-report.md', renderFinalReport(map));\n\n return {\n packPath,\n mode: handoff.mode,\n refused: false,\n refusalReason: null,\n filesWritten,\n acceptedClaims: map.accepted_claim_ids.length,\n claimClusters: map.claim_clusters.length,\n scopeOverlaps: map.scope_overlaps.length,\n crossSectionContradictions: map.cross_section_contradictions.length,\n };\n}\n","export { workspace } from './run.js';\nexport { deriveCrossSectionMap } from './derive.js';\nexport {\n renderCrossSectionMapMarkdown,\n renderDecisionBrief,\n renderWorkingReport,\n renderFinalReport,\n} from './markdown.js';\nexport {\n CrossSectionMapSchema,\n SectionAcceptedSummarySchema,\n ClaimClusterSchema,\n SharedSourceSchema,\n ScopeOverlapSchema,\n CrossSectionContradictionRefSchema,\n WaiverDependencySchema,\n AllowedSynthesisInputSchema,\n ForbiddenInputSchema,\n} from './schema.js';\nexport type {\n CrossSectionMap,\n SectionAcceptedSummary,\n ClaimCluster,\n SharedSource,\n ScopeOverlap,\n CrossSectionContradictionRef,\n WaiverDependency,\n AllowedSynthesisInput,\n ForbiddenInput,\n WorkspaceOptions,\n WorkspaceSummary,\n} from './types.js';\n","import type { ResearchYaml, SectionScopedWaiver } from '../intake/schema.js';\nimport type { Claim } from '../claims/schema.js';\nimport type { ClaimReview, ReviewFinding } from '../review/schema.js';\nimport type { Contradiction } from '../contradictions/schema.js';\nimport type { ContradictionResolution } from '../contradictions/resolution-schema.js';\nimport type { ClaimSynthesisDisposition } from '../dispositions/schema.js';\nimport type { SectionGateResult } from '../gates/schema.js';\nimport type { FetchReceipt, SourceCard } from '../sources/schema.js';\nimport type { CoworkHandoffPayload } from '../cowork/schema.js';\n\nimport type {\n ClaimSummary,\n ContradictionSummary,\n HandoffMode,\n OrphanClaimRow,\n PackAuditPayload,\n PackVerdict,\n ReadinessSummary,\n ReviewSummary,\n ScopeWideningRiskRow,\n SourceDiversityGapRow,\n SourceSummary,\n StaleSourceRow,\n SynthesisReadinessRow,\n UnresolvedContradictionRow,\n WaiverSummary,\n WeakSourceRow,\n} from './types.js';\n\nexport interface AggregateInput {\n research: ResearchYaml;\n perSection: Map<\n string,\n {\n claims: Claim[];\n candidateClaims: Claim[];\n claimReviews: ClaimReview[];\n contradictions: Contradiction[];\n resolutions?: ContradictionResolution[];\n dispositions?: ClaimSynthesisDisposition[];\n gate: SectionGateResult | null;\n findings: ReviewFinding[];\n sourceIdsForSection: string[];\n }\n >;\n sources: SourceCard[];\n receipts: FetchReceipt[];\n handoff: CoworkHandoffPayload | null;\n generatedAt: string;\n warnings: string[];\n}\n\nexport interface AggregateOutput {\n payload: PackAuditPayload;\n orphanClaims: OrphanClaimRow[];\n staleSources: StaleSourceRow[];\n weakSources: WeakSourceRow[];\n unresolvedContradictions: UnresolvedContradictionRow[];\n scopeWideningRisks: ScopeWideningRiskRow[];\n sourceDiversityGaps: SourceDiversityGapRow[];\n}\n\nfunction packId(research: ResearchYaml): string {\n // Stable ID derived from topic + created_at; same logic as cowork derive\n // (kept inline so audit module does not depend on cowork internals).\n const fingerprint = `${research.topic}|${research.created_at}`;\n let hash = 0;\n for (let i = 0; i < fingerprint.length; i += 1) {\n hash = Math.imul(31, hash) + fingerprint.charCodeAt(i);\n hash |= 0;\n }\n return Math.abs(hash).toString(16).padStart(12, '0').slice(-12);\n}\n\nfunction latestDecisionByClaim(reviews: ClaimReview[]): Map<string, ClaimReview> {\n const m = new Map<string, ClaimReview>();\n for (const r of reviews) {\n const existing = m.get(r.claim_id);\n if (!existing || r.created_at > existing.created_at) m.set(r.claim_id, r);\n }\n return m;\n}\n\nfunction buildEffectiveStatuses(resolutions: ContradictionResolution[]): Map<string, string> {\n const map = new Map<string, string>();\n if (resolutions.length === 0) return map;\n const sorted = [...resolutions].sort((a, b) => a.resolved_at.localeCompare(b.resolved_at));\n for (const r of sorted) map.set(r.contradiction_id, r.status);\n return map;\n}\n\nfunction buildEffectiveDispositions(\n dispositions: ClaimSynthesisDisposition[],\n decisionByClaim: Map<string, ClaimReview>,\n warnings: string[],\n): Map<string, string> {\n const map = new Map<string, string>();\n if (dispositions.length === 0) return map;\n const sorted = [...dispositions].sort((a, b) => a.created_at.localeCompare(b.created_at));\n for (const d of sorted) {\n const review = decisionByClaim.get(d.claim_id);\n if (review?.decision === 'accepted_for_synthesis') {\n warnings.push(\n `invalid disposition: claim ${d.claim_id} has accepted_for_synthesis review but a disposition entry was found — layer separation violated`,\n );\n continue;\n }\n map.set(d.claim_id, d.status);\n }\n return map;\n}\n\nfunction buildOrphanClaims(input: AggregateInput): OrphanClaimRow[] {\n const out: OrphanClaimRow[] = [];\n const cardIds = new Set(input.sources.map((c) => c.source_id));\n const okReceiptSourceIds = new Set(\n input.receipts.filter((r) => r.fetch_outcome === 'ok').map((r) => r.source_id),\n );\n\n for (const [sid, data] of input.perSection) {\n const path = `sections/${sid}/claims.jsonl`;\n for (const claim of data.candidateClaims) {\n for (const refSid of claim.source_ids) {\n if (!cardIds.has(refSid)) {\n out.push({\n claim_id: claim.claim_id,\n section_id: sid,\n reason: 'missing_source_card',\n details: `Claim cites source_id ${refSid} but no source card exists at evidence/source-cards/${refSid}.json`,\n artifact_path: path,\n });\n }\n if (!okReceiptSourceIds.has(refSid)) {\n out.push({\n claim_id: claim.claim_id,\n section_id: sid,\n reason: 'unresolvable_source_id',\n details: `Claim cites source_id ${refSid} which has no successful fetch receipt in evidence/fetch-log.jsonl`,\n artifact_path: path,\n });\n }\n }\n if (claim.source_hashes.length === 0) {\n out.push({\n claim_id: claim.claim_id,\n section_id: sid,\n reason: 'missing_source_hash',\n details: 'Claim has empty source_hashes — tamper detection is not anchored to a fetch receipt.',\n artifact_path: path,\n });\n }\n if (claim.evidence_excerpt.trim().length === 0) {\n out.push({\n claim_id: claim.claim_id,\n section_id: sid,\n reason: 'missing_evidence_excerpt',\n details: 'Claim has empty evidence_excerpt.',\n artifact_path: path,\n });\n }\n }\n }\n return out;\n}\n\nfunction buildStaleSources(input: AggregateInput): StaleSourceRow[] {\n const out: StaleSourceRow[] = [];\n const policy = {\n required: input.research.freshness.required,\n max_source_age_months: input.research.freshness.max_source_age_months,\n stale_source_policy: input.research.gates.freshness.stale_source_policy,\n };\n if (!policy.required) return out;\n for (const card of input.sources) {\n const path = `evidence/source-cards/${card.source_id}.json`;\n if (!card.published_at) {\n out.push({\n source_id: card.source_id,\n section_id: card.section_id,\n publisher: card.publisher,\n reason: 'missing_date',\n details: 'Source card has no published_at; freshness cannot be evaluated.',\n artifact_path: path,\n policy,\n });\n continue;\n }\n const d = Date.parse(card.published_at);\n if (Number.isNaN(d)) {\n out.push({\n source_id: card.source_id,\n section_id: card.section_id,\n publisher: card.publisher,\n reason: 'unparseable_date',\n details: `published_at \"${card.published_at}\" is not a valid date.`,\n artifact_path: path,\n policy,\n });\n continue;\n }\n if (policy.max_source_age_months !== null) {\n const ageMonths = (Date.now() - d) / (1000 * 60 * 60 * 24 * 30.44);\n if (ageMonths > policy.max_source_age_months) {\n out.push({\n source_id: card.source_id,\n section_id: card.section_id,\n publisher: card.publisher,\n reason: 'too_old',\n details: `Source is ~${ageMonths.toFixed(1)} months old; pack policy max=${policy.max_source_age_months}. stale_source_policy=${policy.stale_source_policy}.`,\n artifact_path: path,\n policy,\n });\n }\n }\n }\n return out;\n}\n\nfunction findSectionWaiver(\n research: ResearchYaml,\n sectionId: string,\n scope: SectionScopedWaiver['scope'],\n): SectionScopedWaiver | undefined {\n return (research.primary_source_waiver.section_waivers ?? []).find(\n (w) => w.section_id === sectionId && w.scope === scope,\n );\n}\n\nfunction annotateWeakSource(\n row: WeakSourceRow,\n waiver: SectionScopedWaiver | undefined,\n): WeakSourceRow {\n if (!waiver) return row;\n return { ...row, waived: true, waiver_reason: waiver.reason };\n}\n\nfunction annotateDiversityGap(\n row: SourceDiversityGapRow,\n waiver: SectionScopedWaiver | undefined,\n): SourceDiversityGapRow {\n if (!waiver) return row;\n return { ...row, waived: true, waiver_reason: waiver.reason };\n}\n\nfunction buildWeakSources(input: AggregateInput): WeakSourceRow[] {\n const out: WeakSourceRow[] = [];\n const cfg = input.research.gates.source_floor;\n for (const [sid, data] of input.perSection) {\n const sectionSources = input.sources.filter((c) => data.sourceIdsForSection.includes(c.source_id));\n if (sectionSources.length === 0) continue;\n const publishers = new Set(\n sectionSources.map((c) => c.publisher).filter((p): p is string => typeof p === 'string'),\n );\n const monopolyWaiver = findSectionWaiver(input.research, sid, 'min_independent_publishers');\n const primaryWaiver = findSectionWaiver(input.research, sid, 'primary_sources_required');\n if (publishers.size === 1 && sectionSources.length >= 2) {\n out.push(\n annotateWeakSource(\n {\n reason: 'source_cluster_monopoly' as const,\n section_id: sid,\n details: `Every source in this section traces to a single publisher (${[...publishers][0]}).`,\n evidence_ids: sectionSources.map((s) => s.source_id),\n artifact_path: `sections/${sid}/sources.jsonl`,\n },\n monopolyWaiver,\n ),\n );\n }\n if (publishers.size < cfg.min_independent_publishers) {\n out.push(\n annotateWeakSource(\n {\n reason: 'low_independent_publishers' as const,\n section_id: sid,\n details: `${publishers.size} independent publisher(s) — pack policy requires at least ${cfg.min_independent_publishers}.`,\n evidence_ids: [...publishers],\n artifact_path: `sections/${sid}/sources.jsonl`,\n },\n monopolyWaiver,\n ),\n );\n }\n const primary = sectionSources.filter((c) => c.source_type === 'primary').length;\n if (primary < cfg.primary_sources_required) {\n out.push(\n annotateWeakSource(\n {\n reason: 'missing_primary_source' as const,\n section_id: sid,\n details: `${primary} primary source(s) — pack policy requires at least ${cfg.primary_sources_required}.`,\n evidence_ids: sectionSources.filter((c) => c.source_type === 'primary').map((c) => c.source_id),\n artifact_path: `sections/${sid}/sources.jsonl`,\n },\n primaryWaiver,\n ),\n );\n }\n const types = new Map<string, number>();\n for (const c of sectionSources) types.set(c.source_type, (types.get(c.source_type) ?? 0) + 1);\n let dominantType: string | null = null;\n let dominantCount = 0;\n for (const [t, n] of types) if (n > dominantCount) { dominantType = t; dominantCount = n; }\n if (dominantType && sectionSources.length >= 4 && dominantCount / sectionSources.length > 0.8) {\n out.push({\n reason: 'excessive_type_imbalance',\n section_id: sid,\n details: `${dominantCount}/${sectionSources.length} (${Math.round((100 * dominantCount) / sectionSources.length)}%) of sources are type=${dominantType}.`,\n evidence_ids: sectionSources.filter((s) => s.source_type === dominantType).map((s) => s.source_id),\n artifact_path: `sections/${sid}/sources.jsonl`,\n });\n }\n const failedReceipts = input.receipts.filter(\n (r) => r.section_id === sid && r.fetch_outcome !== 'ok',\n );\n if (failedReceipts.length > 0 && sectionSources.length < cfg.min_sources) {\n out.push({\n reason: 'failed_fetches_reducing_floor',\n section_id: sid,\n details: `${failedReceipts.length} failed fetch(es) recorded; section currently has ${sectionSources.length} source(s) vs minimum ${cfg.min_sources}.`,\n evidence_ids: failedReceipts.map((r) => r.receipt_id),\n artifact_path: `evidence/fetch-log.jsonl`,\n });\n }\n }\n return out;\n}\n\nfunction buildUnresolvedContradictions(input: AggregateInput): UnresolvedContradictionRow[] {\n const out: UnresolvedContradictionRow[] = [];\n for (const [sid, data] of input.perSection) {\n const effectiveStatuses = buildEffectiveStatuses(data.resolutions ?? []);\n for (const c of data.contradictions) {\n const eff = effectiveStatuses.get(c.contradiction_id);\n const isUnresolved = eff !== undefined ? eff === 'unresolved' : c.status === 'unresolved';\n if (!isUnresolved) continue;\n out.push({\n contradiction_id: c.contradiction_id,\n section_id: sid,\n type: c.type,\n severity: c.severity,\n status: c.status,\n claim_ids: c.claim_ids,\n artifact_path: `sections/${sid}/contradictions.jsonl`,\n });\n }\n }\n return out;\n}\n\nfunction buildScopeWideningRisks(input: AggregateInput): ScopeWideningRiskRow[] {\n const out: ScopeWideningRiskRow[] = [];\n for (const [sid, data] of input.perSection) {\n for (const f of data.findings) {\n if (f.category === 'overgeneralized_claim' || f.category === 'scope_widening') {\n for (const cid of f.claim_ids) {\n out.push({\n reason: 'overgeneralization_finding',\n claim_id: cid,\n section_id: sid,\n details: `${f.category} (${f.severity}): ${f.summary}`,\n artifact_path: `audits/${sid}-findings.jsonl`,\n });\n }\n }\n if (f.category === 'missing_not_constraint') {\n for (const cid of f.claim_ids) {\n out.push({\n reason: 'missing_not_flagged',\n claim_id: cid,\n section_id: sid,\n details: f.summary,\n artifact_path: `audits/${sid}-findings.jsonl`,\n });\n }\n }\n }\n for (const claim of data.candidateClaims) {\n if (claim.scope === null && claim.asserts.length > 40) {\n out.push({\n reason: 'scope_null_in_use',\n claim_id: claim.claim_id,\n section_id: sid,\n details: 'Candidate claim has scope=null with substantive assertion — synthesis must not treat it as broad.',\n artifact_path: `sections/${sid}/claims.jsonl`,\n });\n }\n }\n }\n return out;\n}\n\nfunction buildSourceDiversityGaps(input: AggregateInput): SourceDiversityGapRow[] {\n const out: SourceDiversityGapRow[] = [];\n const cfg = input.research.gates.source_floor;\n const allPublishersBySection = new Map<string, Set<string>>();\n for (const [sid, data] of input.perSection) {\n const sectionSources = input.sources.filter((c) => data.sourceIdsForSection.includes(c.source_id));\n const publishers = new Set(\n sectionSources.map((c) => c.publisher).filter((p): p is string => typeof p === 'string'),\n );\n allPublishersBySection.set(sid, publishers);\n if (sectionSources.length === 0) {\n out.push({\n reason: 'section_has_no_sources',\n section_id: sid,\n details: 'Section has no source cards on file.',\n evidence_ids: [],\n });\n continue;\n }\n const monopolyWaiver = findSectionWaiver(input.research, sid, 'min_independent_publishers');\n if (publishers.size === 1 && sectionSources.length >= 2) {\n out.push(\n annotateDiversityGap(\n {\n reason: 'section_publisher_monopoly' as const,\n section_id: sid,\n details: `Section sources monopolized by ${[...publishers][0]}.`,\n evidence_ids: sectionSources.map((s) => s.source_id),\n },\n monopolyWaiver,\n ),\n );\n } else if (publishers.size < cfg.min_independent_publishers) {\n out.push(\n annotateDiversityGap(\n {\n reason: 'low_section_publisher_count' as const,\n section_id: sid,\n details: `${publishers.size} publisher(s); pack policy requires ${cfg.min_independent_publishers}.`,\n evidence_ids: [...publishers],\n },\n monopolyWaiver,\n ),\n );\n }\n }\n // cross-section overlap: a publisher dominating across multiple sections\n const pubSectionCount = new Map<string, Set<string>>();\n for (const [sid, pubs] of allPublishersBySection) {\n for (const p of pubs) {\n if (!pubSectionCount.has(p)) pubSectionCount.set(p, new Set());\n pubSectionCount.get(p)!.add(sid);\n }\n }\n for (const [pub, sects] of pubSectionCount) {\n if (sects.size >= 3 && allPublishersBySection.size >= 4) {\n out.push({\n reason: 'cross_section_publisher_overlap',\n section_id: '*',\n details: `Publisher \"${pub}\" appears in ${sects.size} sections; cross-section diversity is reduced.`,\n evidence_ids: [...sects],\n });\n }\n }\n return out;\n}\n\nfunction buildSectionReadiness(input: AggregateInput, warnings: string[]): SynthesisReadinessRow[] {\n const handoffMode: HandoffMode =\n (input.handoff?.mode as HandoffMode | undefined) ?? 'unknown';\n const workspaceAllowed = input.handoff?.synthesis_allowed ?? false;\n return input.research.sections.map((s) => {\n const data = input.perSection.get(s.id);\n const decisionByClaim = data ? latestDecisionByClaim(data.claimReviews) : new Map();\n const effectiveDispositions = buildEffectiveDispositions(\n data?.dispositions ?? [],\n decisionByClaim,\n warnings,\n );\n let accepted = 0;\n let repair = 0;\n let rejected = 0;\n let dispositioned = 0;\n if (data) {\n for (const c of data.candidateClaims) {\n const d = decisionByClaim.get(c.claim_id);\n if (!d) continue;\n if (d.decision === 'accepted_for_synthesis') {\n accepted += 1;\n } else if (d.decision === 'rejected') {\n rejected += 1;\n } else if (effectiveDispositions.has(c.claim_id)) {\n dispositioned += 1;\n } else {\n repair += 1;\n }\n }\n }\n return {\n section_id: s.id,\n purpose: s.purpose,\n status: s.status,\n has_gate_run: !!data?.gate,\n has_review_run: (data?.claimReviews.length ?? 0) > 0,\n gate_verdict: data?.gate?.verdict ?? null,\n synthesis_eligible: data?.gate?.synthesis_eligible ?? false,\n candidate_claims: data?.candidateClaims.length ?? 0,\n accepted_claims: accepted,\n repair_claims: repair,\n rejected_claims: rejected,\n dispositioned_claims: dispositioned,\n blocking_reasons: data?.gate?.blocking_reasons ?? [],\n cowork_handoff_mode: handoffMode,\n workspace_allowed: workspaceAllowed,\n };\n });\n}\n\nfunction buildClaimSummary(input: AggregateInput, orphans: OrphanClaimRow[], warnings: string[]): ClaimSummary {\n let total = 0;\n let candidate = 0;\n let accepted = 0;\n let rejected = 0;\n let repair = 0;\n let dispositioned = 0;\n let noReview = 0;\n let withEvidence = 0;\n let withSourceHashes = 0;\n let scopeNull = 0;\n let notNull = 0;\n for (const data of input.perSection.values()) {\n total += data.claims.length;\n candidate += data.candidateClaims.length;\n const decisionByClaim = latestDecisionByClaim(data.claimReviews);\n const effectiveDispositions = buildEffectiveDispositions(\n data.dispositions ?? [],\n decisionByClaim,\n warnings,\n );\n for (const c of data.candidateClaims) {\n if (c.evidence_excerpt.trim().length > 0) withEvidence += 1;\n if (c.source_hashes.length > 0) withSourceHashes += 1;\n if (c.scope === null) scopeNull += 1;\n if (c.not !== null) notNull += 1;\n const d = decisionByClaim.get(c.claim_id);\n if (!d) noReview += 1;\n else if (d.decision === 'accepted_for_synthesis') accepted += 1;\n else if (d.decision === 'rejected') rejected += 1;\n else if (effectiveDispositions.has(c.claim_id)) dispositioned += 1;\n else repair += 1;\n }\n }\n const orphanIds = new Set(orphans.map((o) => o.claim_id));\n return {\n total,\n candidate,\n accepted_for_synthesis: accepted,\n rejected,\n needs_repair: repair,\n dispositioned,\n no_review: noReview,\n with_evidence_excerpt: withEvidence,\n with_source_hashes: withSourceHashes,\n scope_null: scopeNull,\n not_null: notNull,\n orphans: orphanIds.size,\n };\n}\n\nfunction buildSourceSummary(input: AggregateInput): SourceSummary {\n const cards = input.sources;\n const failed = input.receipts.filter((r) => r.fetch_outcome !== 'ok').length;\n const publishers = new Set(\n cards.map((c) => c.publisher).filter((p): p is string => typeof p === 'string'),\n );\n let withSources = 0;\n let withoutSources = 0;\n for (const data of input.perSection.values()) {\n if (data.sourceIdsForSection.length > 0) withSources += 1;\n else withoutSources += 1;\n }\n return {\n total: cards.length,\n primary: cards.filter((c) => c.source_type === 'primary').length,\n secondary: cards.filter((c) => c.source_type === 'secondary').length,\n forum: cards.filter((c) => c.source_type === 'forum').length,\n benchmark: cards.filter((c) => c.source_type === 'benchmark').length,\n docs: cards.filter((c) => c.source_type === 'docs').length,\n unknown: cards.filter((c) => c.source_type === 'unknown').length,\n independent_publishers: publishers.size,\n failed_fetches: failed,\n sections_with_sources: withSources,\n sections_without_sources: withoutSources,\n };\n}\n\nfunction buildContradictionSummary(input: AggregateInput): ContradictionSummary {\n const all: Contradiction[] = [];\n let cleanLedgers = 0;\n const effectiveUnresolved: Contradiction[] = [];\n for (const [, data] of input.perSection) {\n all.push(...data.contradictions);\n if (data.contradictions.length === 0) cleanLedgers += 1;\n const effectiveStatuses = buildEffectiveStatuses(data.resolutions ?? []);\n for (const c of data.contradictions) {\n const eff = effectiveStatuses.get(c.contradiction_id);\n if (eff !== undefined ? eff === 'unresolved' : c.status === 'unresolved') {\n effectiveUnresolved.push(c);\n }\n }\n }\n const unresolved = effectiveUnresolved;\n const blocking = unresolved.filter(\n (c) => c.severity === 'high' || c.severity === 'blocking',\n );\n const byType: Record<string, number> = {};\n for (const c of all) byType[c.type] = (byType[c.type] ?? 0) + 1;\n return {\n total: all.length,\n unresolved: unresolved.length,\n blocking: blocking.length,\n reconciled: all.filter((c) => c.status === 'reconciled').length,\n preserved_deliberately: all.filter((c) => c.status === 'preserved_deliberately').length,\n rejected: all.filter((c) => c.status === 'rejected').length,\n by_type: byType,\n sections_with_clean_ledger: cleanLedgers,\n };\n}\n\nfunction buildReviewSummary(input: AggregateInput): ReviewSummary {\n let withReview = 0;\n let withoutReview = 0;\n const decisionCounts: Record<string, number> = {};\n let blockingFindings = 0;\n for (const data of input.perSection.values()) {\n if (data.claimReviews.length > 0) withReview += 1;\n else withoutReview += 1;\n const latest = latestDecisionByClaim(data.claimReviews);\n for (const r of latest.values()) {\n decisionCounts[r.decision] = (decisionCounts[r.decision] ?? 0) + 1;\n }\n blockingFindings += data.findings.filter((f) => f.severity === 'block').length;\n }\n return {\n sections_with_review_run: withReview,\n sections_without_review_run: withoutReview,\n decision_counts: decisionCounts,\n blocking_findings: blockingFindings,\n };\n}\n\nfunction buildWaiverSummary(input: AggregateInput): WaiverSummary {\n const byFamily: Record<string, number> = {};\n let total = 0;\n let invalid = 0;\n if (input.handoff) {\n for (const w of input.handoff.waivers) {\n total += 1;\n byFamily[w.family] = (byFamily[w.family] ?? 0) + 1;\n if (!w.reason || w.compensating_controls.length === 0) invalid += 1;\n }\n } else {\n const w = input.research.primary_source_waiver;\n if (w.status === 'granted') {\n total = 1;\n byFamily['source_floor'] = 1;\n if (!w.reason || w.compensating_controls.length === 0) invalid = 1;\n }\n }\n return { total, invalid, by_family: byFamily };\n}\n\nfunction buildReadinessSummary(\n rows: SynthesisReadinessRow[],\n handoff: CoworkHandoffPayload | null,\n unresolvedContradictions: UnresolvedContradictionRow[],\n): ReadinessSummary {\n let ready = 0;\n let repair = 0;\n let blocked = 0;\n let noGate = 0;\n let noReview = 0;\n const unresolvedBySection = new Map<string, number>();\n for (const c of unresolvedContradictions) {\n unresolvedBySection.set(c.section_id, (unresolvedBySection.get(c.section_id) ?? 0) + 1);\n }\n for (const r of rows) {\n if (!r.has_gate_run) noGate += 1;\n if (!r.has_review_run) noReview += 1;\n const unresolvedCount = unresolvedBySection.get(r.section_id) ?? 0;\n if (\n r.synthesis_eligible &&\n r.has_review_run &&\n r.candidate_claims > 0 &&\n r.blocking_reasons.length === 0 &&\n unresolvedCount === 0\n ) {\n ready += 1;\n } else if (r.has_gate_run && r.gate_verdict === 'blocked' && !r.synthesis_eligible) {\n blocked += 1;\n } else {\n repair += 1;\n }\n }\n return {\n total_sections: rows.length,\n ready_sections: ready,\n repair_sections: repair,\n blocked_sections: blocked,\n no_gate_sections: noGate,\n no_review_sections: noReview,\n cowork_handoff_mode: (handoff?.mode as HandoffMode | undefined) ?? 'unknown',\n workspace_allowed: handoff?.synthesis_allowed ?? false,\n };\n}\n\nfunction determineVerdict(args: {\n rows: SynthesisReadinessRow[];\n unresolvedContradictions: UnresolvedContradictionRow[];\n waiverSummary: WaiverSummary;\n warnings: string[];\n readiness: ReadinessSummary;\n totalSections: number;\n}): { verdict: PackVerdict; blockingReasons: string[] } {\n const reasons: string[] = [];\n const malformed = args.warnings.filter((w) => /malformed|invalid|parse/i.test(w));\n const blockingContradictions = args.unresolvedContradictions.filter(\n (c) => c.severity === 'blocking' || c.severity === 'high',\n );\n\n if (malformed.length > 0) {\n reasons.push(...malformed);\n return { verdict: 'human_review_required', blockingReasons: reasons };\n }\n if (args.waiverSummary.invalid > 0) {\n reasons.push('One or more granted waivers are missing reason or compensating_controls.');\n return { verdict: 'human_review_required', blockingReasons: reasons };\n }\n if (blockingContradictions.length > 0) {\n for (const c of blockingContradictions) {\n reasons.push(`Unresolved ${c.severity} contradiction in ${c.section_id}: ${c.contradiction_id}`);\n }\n return { verdict: 'human_review_required', blockingReasons: reasons };\n }\n\n if (args.readiness.ready_sections === args.totalSections && args.totalSections > 0) {\n return { verdict: 'ready_for_synthesis', blockingReasons: [] };\n }\n\n // No gates run on any section AND no claims anywhere → blocked (foundational gap).\n if (args.readiness.no_gate_sections === args.totalSections && args.totalSections > 0) {\n reasons.push('No section has a gate result on file. Pack has not begun gating.');\n return { verdict: 'blocked', blockingReasons: reasons };\n }\n\n // Otherwise repair_required\n if (args.readiness.no_gate_sections > 0) {\n reasons.push(`${args.readiness.no_gate_sections} section(s) have no gate result.`);\n }\n for (const r of args.rows) {\n if (r.gate_verdict === 'blocked') {\n reasons.push(`Section ${r.section_id} is gate-blocked: ${r.blocking_reasons.join('; ')}`);\n }\n }\n return { verdict: 'repair_required', blockingReasons: reasons };\n}\n\nfunction buildNextActions(args: {\n rows: SynthesisReadinessRow[];\n verdict: PackVerdict;\n unresolvedContradictions: UnresolvedContradictionRow[];\n waiverSummary: WaiverSummary;\n weakSources: WeakSourceRow[];\n}): string[] {\n const actions = new Set<string>();\n if (args.verdict === 'ready_for_synthesis') {\n actions.add('Run `research-os synth workspace` to lay out the synthesis area.');\n actions.add('Run `research-os index build --all` to refresh the queryable index.');\n return Array.from(actions);\n }\n if (args.verdict === 'human_review_required') {\n actions.add('Stop. Surface blocking reasons to the operator before any further automated work.');\n if (args.waiverSummary.invalid > 0) {\n actions.add('Fix each invalid waiver in research.yaml — granted requires reason + compensating_controls.');\n }\n if (args.unresolvedContradictions.some((c) => c.severity === 'blocking' || c.severity === 'high')) {\n actions.add('Reconcile, preserve_deliberately, or reject blocking contradictions in claim-reviews.');\n }\n return Array.from(actions);\n }\n // repair_required or blocked\n for (const r of args.rows) {\n if (!r.has_gate_run) {\n actions.add(`Run \\`research-os gate ${r.section_id}\\` (no gate result on file).`);\n } else if (r.gate_verdict === 'blocked') {\n actions.add(`[${r.section_id}] address blocking gate failures, then re-run \\`research-os gate ${r.section_id}\\`.`);\n }\n if (!r.has_review_run && r.candidate_claims > 0) {\n actions.add(`Run \\`research-os review ${r.section_id}\\` (no review run on file).`);\n }\n if (r.repair_claims > 0) {\n actions.add(`[${r.section_id}] ${r.repair_claims} claim(s) need repair — re-run gather/extract/review for affected sources.`);\n }\n }\n for (const w of args.weakSources) {\n if (w.reason === 'source_cluster_monopoly') {\n actions.add(`[${w.section_id}] add a source from an independent publisher.`);\n }\n }\n if (actions.size === 0) {\n actions.add('No specific next-actions identified, but pack is not synthesis-ready — re-run audit after refreshing inputs.');\n }\n return Array.from(actions);\n}\n\nconst AUDIT_FILE_PATHS = [\n 'audits/pack-audit.json',\n 'audits/pack-audit.md',\n 'audits/orphan-claims.json',\n 'audits/orphan-claims.md',\n 'audits/stale-sources.json',\n 'audits/stale-sources.md',\n 'audits/weak-sources.json',\n 'audits/weak-sources.md',\n 'audits/unresolved-contradictions.json',\n 'audits/unresolved-contradictions.md',\n 'audits/scope-widening-risks.json',\n 'audits/scope-widening-risks.md',\n 'audits/source-diversity-gaps.json',\n 'audits/source-diversity-gaps.md',\n 'audits/synthesis-readiness.json',\n 'audits/synthesis-readiness.md',\n];\n\nexport function aggregate(input: AggregateInput): AggregateOutput {\n const orphanClaims = buildOrphanClaims(input);\n const staleSources = buildStaleSources(input);\n const weakSources = buildWeakSources(input);\n const unresolvedContradictions = buildUnresolvedContradictions(input);\n const scopeWideningRisks = buildScopeWideningRisks(input);\n const sourceDiversityGaps = buildSourceDiversityGaps(input);\n const sectionRows = buildSectionReadiness(input, input.warnings);\n\n const claimSummary = buildClaimSummary(input, orphanClaims, input.warnings);\n const sourceSummary = buildSourceSummary(input);\n const contradictionSummary = buildContradictionSummary(input);\n const reviewSummary = buildReviewSummary(input);\n const waiverSummary = buildWaiverSummary(input);\n const readinessSummary = buildReadinessSummary(sectionRows, input.handoff, unresolvedContradictions);\n\n const { verdict, blockingReasons } = determineVerdict({\n rows: sectionRows,\n unresolvedContradictions,\n waiverSummary,\n warnings: input.warnings,\n readiness: readinessSummary,\n totalSections: input.research.sections.length,\n });\n\n const synthesisAllowed = verdict === 'ready_for_synthesis';\n const nextActions = buildNextActions({\n rows: sectionRows,\n verdict,\n unresolvedContradictions,\n waiverSummary,\n weakSources,\n });\n\n const payload: PackAuditPayload = {\n pack_id: packId(input.research),\n pack_topic: input.research.topic,\n generated_at: input.generatedAt,\n verdict,\n synthesis_allowed: synthesisAllowed,\n section_summaries: sectionRows,\n claim_summary: claimSummary,\n source_summary: sourceSummary,\n contradiction_summary: contradictionSummary,\n review_summary: reviewSummary,\n waiver_summary: waiverSummary,\n readiness_summary: readinessSummary,\n audit_files: AUDIT_FILE_PATHS,\n blocking_reasons: blockingReasons,\n warnings: input.warnings,\n next_actions: nextActions,\n };\n\n return {\n payload,\n orphanClaims,\n staleSources,\n weakSources,\n unresolvedContradictions,\n scopeWideningRisks,\n sourceDiversityGaps,\n };\n}\n","import { z } from 'zod';\n\nexport const PackVerdictSchema = z.enum([\n 'ready_for_synthesis',\n 'repair_required',\n 'human_review_required',\n 'blocked',\n]);\n\nexport const HandoffModeSchema = z.enum([\n 'repair_required',\n 'synthesis_ready',\n 'human_review_required',\n 'unknown',\n]);\n\nexport const OrphanClaimRowSchema = z.object({\n claim_id: z.string(),\n section_id: z.string(),\n reason: z.enum([\n 'missing_source_card',\n 'missing_source_hash',\n 'missing_evidence_excerpt',\n 'unresolvable_source_id',\n ]),\n details: z.string(),\n artifact_path: z.string(),\n});\n\nexport const StaleSourceRowSchema = z.object({\n source_id: z.string(),\n section_id: z.string(),\n publisher: z.string().nullable(),\n reason: z.enum(['too_old', 'missing_date', 'unparseable_date']),\n details: z.string(),\n artifact_path: z.string(),\n policy: z.object({\n required: z.boolean(),\n max_source_age_months: z.number().int().nullable(),\n stale_source_policy: z.enum(['warn', 'fail']),\n }),\n});\n\nexport const WeakSourceRowSchema = z.object({\n reason: z.enum([\n 'source_cluster_monopoly',\n 'low_independent_publishers',\n 'missing_primary_source',\n 'excessive_type_imbalance',\n 'failed_fetches_reducing_floor',\n ]),\n section_id: z.string(),\n details: z.string(),\n evidence_ids: z.array(z.string()),\n artifact_path: z.string(),\n});\n\nexport const UnresolvedContradictionRowSchema = z.object({\n contradiction_id: z.string(),\n section_id: z.string(),\n type: z.string(),\n severity: z.string(),\n status: z.string(),\n claim_ids: z.array(z.string()),\n artifact_path: z.string(),\n});\n\nexport const ScopeWideningRiskRowSchema = z.object({\n reason: z.enum([\n 'overgeneralization_finding',\n 'scope_null_in_use',\n 'missing_not_flagged',\n 'contextual_to_universal_risk',\n ]),\n claim_id: z.string(),\n section_id: z.string(),\n details: z.string(),\n artifact_path: z.string(),\n});\n\nexport const SourceDiversityGapRowSchema = z.object({\n reason: z.enum([\n 'section_publisher_monopoly',\n 'low_section_publisher_count',\n 'cross_section_publisher_overlap',\n 'section_has_no_sources',\n ]),\n section_id: z.string(),\n details: z.string(),\n evidence_ids: z.array(z.string()),\n});\n\nexport const SynthesisReadinessRowSchema = z.object({\n section_id: z.string(),\n purpose: z.string(),\n status: z.string(),\n has_gate_run: z.boolean(),\n has_review_run: z.boolean(),\n gate_verdict: z.string().nullable(),\n synthesis_eligible: z.boolean(),\n candidate_claims: z.number().int().nonnegative(),\n accepted_claims: z.number().int().nonnegative(),\n repair_claims: z.number().int().nonnegative(),\n rejected_claims: z.number().int().nonnegative(),\n dispositioned_claims: z.number().int().nonnegative(),\n blocking_reasons: z.array(z.string()),\n cowork_handoff_mode: HandoffModeSchema,\n workspace_allowed: z.boolean(),\n});\n\nexport const PackAuditPayloadSchema = z.object({\n pack_id: z.string(),\n pack_topic: z.string(),\n generated_at: z.string(),\n verdict: PackVerdictSchema,\n synthesis_allowed: z.boolean(),\n section_summaries: z.array(SynthesisReadinessRowSchema),\n claim_summary: z.object({\n total: z.number().int().nonnegative(),\n candidate: z.number().int().nonnegative(),\n accepted_for_synthesis: z.number().int().nonnegative(),\n rejected: z.number().int().nonnegative(),\n needs_repair: z.number().int().nonnegative(),\n dispositioned: z.number().int().nonnegative(),\n no_review: z.number().int().nonnegative(),\n with_evidence_excerpt: z.number().int().nonnegative(),\n with_source_hashes: z.number().int().nonnegative(),\n scope_null: z.number().int().nonnegative(),\n not_null: z.number().int().nonnegative(),\n orphans: z.number().int().nonnegative(),\n }),\n source_summary: z.object({\n total: z.number().int().nonnegative(),\n primary: z.number().int().nonnegative(),\n secondary: z.number().int().nonnegative(),\n forum: z.number().int().nonnegative(),\n benchmark: z.number().int().nonnegative(),\n docs: z.number().int().nonnegative(),\n unknown: z.number().int().nonnegative(),\n independent_publishers: z.number().int().nonnegative(),\n failed_fetches: z.number().int().nonnegative(),\n sections_with_sources: z.number().int().nonnegative(),\n sections_without_sources: z.number().int().nonnegative(),\n }),\n contradiction_summary: z.object({\n total: z.number().int().nonnegative(),\n unresolved: z.number().int().nonnegative(),\n blocking: z.number().int().nonnegative(),\n reconciled: z.number().int().nonnegative(),\n preserved_deliberately: z.number().int().nonnegative(),\n rejected: z.number().int().nonnegative(),\n by_type: z.record(z.string(), z.number().int().nonnegative()),\n sections_with_clean_ledger: z.number().int().nonnegative(),\n }),\n review_summary: z.object({\n sections_with_review_run: z.number().int().nonnegative(),\n sections_without_review_run: z.number().int().nonnegative(),\n decision_counts: z.record(z.string(), z.number().int().nonnegative()),\n blocking_findings: z.number().int().nonnegative(),\n }),\n waiver_summary: z.object({\n total: z.number().int().nonnegative(),\n invalid: z.number().int().nonnegative(),\n by_family: z.record(z.string(), z.number().int().nonnegative()),\n }),\n readiness_summary: z.object({\n total_sections: z.number().int().nonnegative(),\n ready_sections: z.number().int().nonnegative(),\n repair_sections: z.number().int().nonnegative(),\n blocked_sections: z.number().int().nonnegative(),\n no_gate_sections: z.number().int().nonnegative(),\n no_review_sections: z.number().int().nonnegative(),\n cowork_handoff_mode: HandoffModeSchema,\n workspace_allowed: z.boolean(),\n }),\n audit_files: z.array(z.string()),\n blocking_reasons: z.array(z.string()),\n warnings: z.array(z.string()),\n next_actions: z.array(z.string()),\n});\n\nexport type PackAuditPayload = z.infer<typeof PackAuditPayloadSchema>;\n","import type {\n OrphanClaimRow,\n PackAuditPayload,\n PackVerdict,\n ScopeWideningRiskRow,\n SourceDiversityGapRow,\n StaleSourceRow,\n UnresolvedContradictionRow,\n WeakSourceRow,\n} from './types.js';\n\nconst VERDICT_GLYPH: Record<PackVerdict, string> = {\n ready_for_synthesis: '[READY FOR SYNTHESIS]',\n repair_required: '[REPAIR REQUIRED]',\n human_review_required: '[HUMAN REVIEW REQUIRED]',\n blocked: '[BLOCKED]',\n};\n\nconst COMMON_LAW =\n '> Pack audit aggregates existing research truth. It does not create new truth, resolve failures, or hide section-level evidence. The canonical artifacts (claims, source-cards, fetch-log, gate/review JSON) are the source of authority — these rollups are pointers.';\n\nexport function renderPackAuditMarkdown(p: PackAuditPayload): string {\n const lines: string[] = [];\n lines.push(`# Pack Audit: ${p.pack_topic}`);\n lines.push('');\n lines.push(`**Pack ID:** \\`${p.pack_id}\\``);\n lines.push(`**Verdict:** ${VERDICT_GLYPH[p.verdict]} ${p.verdict}`);\n lines.push(`**Synthesis allowed:** ${p.synthesis_allowed ? 'yes' : 'no'}`);\n lines.push(`**Generated:** ${p.generated_at}`);\n lines.push(`**Cowork handoff mode:** ${p.readiness_summary.cowork_handoff_mode}`);\n lines.push(`**Workspace allowed:** ${p.readiness_summary.workspace_allowed ? 'yes' : 'no'}`);\n lines.push('');\n lines.push(COMMON_LAW);\n lines.push('');\n\n if (p.blocking_reasons.length > 0) {\n lines.push('## Blocking reasons');\n lines.push('');\n for (const r of p.blocking_reasons) lines.push(`- ${r}`);\n lines.push('');\n }\n\n lines.push('## Counts at a glance');\n lines.push('');\n lines.push(`- **Sections:** ${p.readiness_summary.total_sections} total — ${p.readiness_summary.ready_sections} ready, ${p.readiness_summary.repair_sections} in repair, ${p.readiness_summary.blocked_sections} blocked, ${p.readiness_summary.no_gate_sections} without gate, ${p.readiness_summary.no_review_sections} without review`);\n lines.push(`- **Claims:** ${p.claim_summary.total} total (${p.claim_summary.candidate} candidate; ${p.claim_summary.accepted_for_synthesis} accepted, ${p.claim_summary.needs_repair} repair, ${p.claim_summary.rejected} rejected, ${p.claim_summary.no_review} no_review, ${p.claim_summary.orphans} orphan)`);\n lines.push(`- **Sources:** ${p.source_summary.total} total (${p.source_summary.primary} primary, ${p.source_summary.secondary} secondary, ${p.source_summary.docs} docs, ${p.source_summary.forum} forum, ${p.source_summary.benchmark} benchmark, ${p.source_summary.unknown} unknown), ${p.source_summary.independent_publishers} publishers, ${p.source_summary.failed_fetches} failed fetches; ${p.source_summary.sections_with_sources}/${p.readiness_summary.total_sections} sections have at least one source`);\n lines.push(`- **Contradictions:** ${p.contradiction_summary.total} total (${p.contradiction_summary.unresolved} unresolved, ${p.contradiction_summary.blocking} high/blocking, ${p.contradiction_summary.reconciled} reconciled, ${p.contradiction_summary.preserved_deliberately} preserved_deliberately, ${p.contradiction_summary.rejected} rejected); ${p.contradiction_summary.sections_with_clean_ledger} sections have an empty contradiction ledger — *empty is not proof of completeness, only that the configured detector found nothing*`);\n lines.push(`- **Review:** ${p.review_summary.sections_with_review_run}/${p.readiness_summary.total_sections} sections have had \\`research-os review\\` run; ${p.review_summary.blocking_findings} blocking findings recorded`);\n lines.push(`- **Waivers:** ${p.waiver_summary.total} total (${p.waiver_summary.invalid} invalid)`);\n lines.push('');\n\n lines.push('## Section synthesis-readiness');\n lines.push('');\n lines.push('| Section | Status | Gate | Synthesis-eligible | Candidates | Accepted | Repair | Rejected |');\n lines.push('|---|---|---|---|---|---|---|---|');\n for (const r of p.section_summaries) {\n lines.push(`| \\`${r.section_id}\\` | ${r.status} | ${r.gate_verdict ?? '—'} | ${r.synthesis_eligible ? 'yes' : 'no'} | ${r.candidate_claims} | ${r.accepted_claims} | ${r.repair_claims} | ${r.rejected_claims} |`);\n }\n lines.push('');\n\n lines.push('## Audit files (canonical pointers)');\n lines.push('');\n for (const f of p.audit_files) lines.push(`- \\`${f}\\``);\n lines.push('');\n\n lines.push('## Recommended next actions');\n lines.push('');\n if (p.next_actions.length === 0) {\n lines.push('_(none recommended)_');\n } else {\n let i = 1;\n for (const a of p.next_actions) {\n lines.push(`${i}. ${a}`);\n i += 1;\n }\n }\n lines.push('');\n\n if (p.warnings.length > 0) {\n lines.push('## Warnings (from audit generation)');\n lines.push('');\n for (const w of p.warnings) lines.push(`- ${w}`);\n lines.push('');\n }\n\n return lines.join('\\n');\n}\n\n\nexport function renderOrphanClaimsMarkdown(rows: OrphanClaimRow[]): string {\n const lines: string[] = [];\n lines.push('# Orphan claims');\n lines.push('');\n lines.push(COMMON_LAW);\n lines.push('');\n if (rows.length === 0) {\n lines.push('_No orphan claims detected. (A clean orphan-claims ledger is a precondition for synthesis, not a proof of completeness.)_');\n return lines.join('\\n') + '\\n';\n }\n lines.push('| Claim ID | Section | Reason | Details | Artifact |');\n lines.push('|---|---|---|---|---|');\n for (const r of rows) {\n lines.push(`| \\`${r.claim_id}\\` | \\`${r.section_id}\\` | ${r.reason} | ${r.details.replace(/\\|/g, '\\\\|')} | \\`${r.artifact_path}\\` |`);\n }\n lines.push('');\n return lines.join('\\n');\n}\n\nexport function renderStaleSourcesMarkdown(rows: StaleSourceRow[]): string {\n const lines: string[] = [];\n lines.push('# Stale sources');\n lines.push('');\n lines.push(COMMON_LAW);\n lines.push('');\n if (rows.length === 0) {\n lines.push('_No stale sources detected (or pack freshness policy not required)._');\n return lines.join('\\n') + '\\n';\n }\n lines.push('| Source | Section | Publisher | Reason | Policy | Details | Artifact |');\n lines.push('|---|---|---|---|---|---|---|');\n for (const r of rows) {\n lines.push(`| \\`${r.source_id}\\` | \\`${r.section_id}\\` | ${r.publisher ?? '—'} | ${r.reason} | ${r.policy.stale_source_policy}${r.policy.max_source_age_months !== null ? ` (max ${r.policy.max_source_age_months}mo)` : ''} | ${r.details.replace(/\\|/g, '\\\\|')} | \\`${r.artifact_path}\\` |`);\n }\n lines.push('');\n return lines.join('\\n');\n}\n\nexport function renderWeakSourcesMarkdown(rows: WeakSourceRow[]): string {\n const lines: string[] = [];\n lines.push('# Weak sources');\n lines.push('');\n lines.push(COMMON_LAW);\n lines.push('');\n if (rows.length === 0) {\n lines.push('_No weak-source signals detected._');\n return lines.join('\\n') + '\\n';\n }\n for (const r of rows) {\n lines.push(`### \\`${r.section_id}\\`: ${r.reason}`);\n lines.push('');\n lines.push(`- **Details:** ${r.details}`);\n lines.push(`- **Evidence IDs:** ${r.evidence_ids.length === 0 ? '_(none)_' : r.evidence_ids.map((e) => `\\`${e}\\``).join(', ')}`);\n lines.push(`- **Artifact:** \\`${r.artifact_path}\\``);\n lines.push('');\n }\n return lines.join('\\n');\n}\n\nexport function renderUnresolvedContradictionsMarkdown(rows: UnresolvedContradictionRow[]): string {\n const lines: string[] = [];\n lines.push('# Unresolved contradictions');\n lines.push('');\n lines.push(COMMON_LAW);\n lines.push('');\n if (rows.length === 0) {\n lines.push('_No unresolved contradictions recorded across the pack. **A clean contradiction ledger is not proof of completeness — it means the configured detector found nothing of tension.** Adversarial review and Cowork synthesis must continue to challenge claims._');\n return lines.join('\\n') + '\\n';\n }\n lines.push('| Contradiction | Section | Type | Severity | Status | Claims | Artifact |');\n lines.push('|---|---|---|---|---|---|---|');\n for (const r of rows) {\n lines.push(`| \\`${r.contradiction_id}\\` | \\`${r.section_id}\\` | ${r.type} | ${r.severity} | ${r.status} | ${r.claim_ids.map((c) => `\\`${c}\\``).join(', ')} | \\`${r.artifact_path}\\` |`);\n }\n lines.push('');\n return lines.join('\\n');\n}\n\nexport function renderScopeWideningRisksMarkdown(rows: ScopeWideningRiskRow[]): string {\n const lines: string[] = [];\n lines.push('# Scope-widening risks');\n lines.push('');\n lines.push(COMMON_LAW);\n lines.push('');\n if (rows.length === 0) {\n lines.push('_No scope-widening risks detected at audit time. Synthesis must still preserve every claim\\'s scope verbatim._');\n return lines.join('\\n') + '\\n';\n }\n lines.push('| Claim | Section | Reason | Details | Artifact |');\n lines.push('|---|---|---|---|---|');\n for (const r of rows) {\n lines.push(`| \\`${r.claim_id}\\` | \\`${r.section_id}\\` | ${r.reason} | ${r.details.replace(/\\|/g, '\\\\|')} | \\`${r.artifact_path}\\` |`);\n }\n lines.push('');\n return lines.join('\\n');\n}\n\nexport function renderSourceDiversityGapsMarkdown(rows: SourceDiversityGapRow[]): string {\n const lines: string[] = [];\n lines.push('# Source-diversity gaps');\n lines.push('');\n lines.push(COMMON_LAW);\n lines.push('');\n if (rows.length === 0) {\n lines.push('_No source-diversity gaps detected._');\n return lines.join('\\n') + '\\n';\n }\n for (const r of rows) {\n lines.push(`### \\`${r.section_id}\\`: ${r.reason}`);\n lines.push('');\n lines.push(`- **Details:** ${r.details}`);\n lines.push(`- **Evidence IDs:** ${r.evidence_ids.length === 0 ? '_(none)_' : r.evidence_ids.map((e) => `\\`${e}\\``).join(', ')}`);\n lines.push('');\n }\n return lines.join('\\n');\n}\n\nexport function renderSynthesisReadinessMarkdown(p: PackAuditPayload): string {\n const lines: string[] = [];\n lines.push('# Synthesis readiness');\n lines.push('');\n lines.push(COMMON_LAW);\n lines.push('');\n lines.push(`**Pack verdict:** ${VERDICT_GLYPH[p.verdict]} ${p.verdict}`);\n lines.push(`**Synthesis allowed:** ${p.synthesis_allowed ? 'yes' : 'no'}`);\n lines.push(`**Cowork handoff mode:** ${p.readiness_summary.cowork_handoff_mode}`);\n lines.push(`**Workspace allowed:** ${p.readiness_summary.workspace_allowed ? 'yes' : 'no'}`);\n lines.push('');\n lines.push('## Section detail');\n lines.push('');\n lines.push('| Section | Status | Gate | Eligible | Candidates | Accepted | Repair | Rejected | Blocking reasons |');\n lines.push('|---|---|---|---|---|---|---|---|---|');\n for (const r of p.section_summaries) {\n const blocking = r.blocking_reasons.length === 0 ? '_(none)_' : r.blocking_reasons.map((b) => b.replace(/\\|/g, '\\\\|')).join('<br>');\n lines.push(`| \\`${r.section_id}\\` | ${r.status} | ${r.gate_verdict ?? '—'} | ${r.synthesis_eligible ? 'yes' : 'no'} | ${r.candidate_claims} | ${r.accepted_claims} | ${r.repair_claims} | ${r.rejected_claims} | ${blocking} |`);\n }\n lines.push('');\n lines.push('## Recommended next actions');\n lines.push('');\n let i = 1;\n for (const a of p.next_actions) {\n lines.push(`${i}. ${a}`);\n i += 1;\n }\n lines.push('');\n return lines.join('\\n');\n}\n","import { existsSync } from 'node:fs';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { join, resolve } from 'node:path';\nimport { parse as yamlParse } from 'yaml';\n\nimport { PackNotFoundError } from '../errors.js';\nimport { ResearchYamlSchema, type ResearchYaml } from '../intake/schema.js';\nimport { ClaimSchema, type Claim } from '../claims/schema.js';\nimport { ContradictionSchema, type Contradiction } from '../contradictions/schema.js';\nimport {\n ContradictionResolutionSchema,\n type ContradictionResolution,\n} from '../contradictions/resolution-schema.js';\nimport {\n ClaimSynthesisDispositionSchema,\n type ClaimSynthesisDisposition,\n} from '../dispositions/schema.js';\nimport {\n FetchReceiptSchema,\n SourceCardSchema,\n type FetchReceipt,\n type SourceCard,\n} from '../sources/schema.js';\nimport { SectionGateResultSchema, type SectionGateResult } from '../gates/schema.js';\nimport {\n ClaimReviewSchema,\n ReviewFindingSchema,\n type ClaimReview,\n type ReviewFinding,\n} from '../review/schema.js';\nimport {\n CoworkHandoffPayloadSchema,\n type CoworkHandoffPayload,\n} from '../cowork/schema.js';\n\nimport { aggregate, type AggregateInput } from './aggregate.js';\nimport { PackAuditPayloadSchema } from './schema.js';\nimport {\n renderOrphanClaimsMarkdown,\n renderPackAuditMarkdown,\n renderScopeWideningRisksMarkdown,\n renderSourceDiversityGapsMarkdown,\n renderStaleSourcesMarkdown,\n renderSynthesisReadinessMarkdown,\n renderUnresolvedContradictionsMarkdown,\n renderWeakSourcesMarkdown,\n} from './markdown.js';\nimport type { AuditOptions, AuditSummary } from './types.js';\n\nasync function readJsonl<T>(\n path: string,\n parse: (raw: unknown) => T,\n warnings: string[],\n): Promise<T[]> {\n if (!existsSync(path)) return [];\n const text = await readFile(path, 'utf8');\n const out: T[] = [];\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n out.push(parse(JSON.parse(line)));\n } catch (err) {\n warnings.push(`malformed line in ${path}: ${err instanceof Error ? err.message : 'parse error'}`);\n }\n }\n return out;\n}\n\nasync function readSourceCards(\n packPath: string,\n warnings: string[],\n): Promise<SourceCard[]> {\n const dir = join(packPath, 'evidence', 'source-cards');\n if (!existsSync(dir)) return [];\n const { readdir } = await import('node:fs/promises');\n const entries = await readdir(dir);\n const cards: SourceCard[] = [];\n for (const entry of entries) {\n if (!entry.endsWith('.json')) continue;\n try {\n const text = await readFile(join(dir, entry), 'utf8');\n cards.push(SourceCardSchema.parse(JSON.parse(text)));\n } catch (err) {\n warnings.push(`malformed source card ${entry}: ${err instanceof Error ? err.message : 'parse error'}`);\n }\n }\n return cards;\n}\n\nasync function readGate(\n packPath: string,\n sectionId: string,\n warnings: string[],\n): Promise<SectionGateResult | null> {\n const path = join(packPath, 'audits', `${sectionId}-gate.json`);\n if (!existsSync(path)) return null;\n try {\n return SectionGateResultSchema.parse(JSON.parse(await readFile(path, 'utf8')));\n } catch (err) {\n warnings.push(`malformed gate result for ${sectionId}: ${err instanceof Error ? err.message : 'parse error'}`);\n return null;\n }\n}\n\nasync function readHandoff(\n packPath: string,\n warnings: string[],\n): Promise<CoworkHandoffPayload | null> {\n const path = join(packPath, 'handoffs', 'cowork-handoff.json');\n if (!existsSync(path)) return null;\n try {\n return CoworkHandoffPayloadSchema.parse(JSON.parse(await readFile(path, 'utf8')));\n } catch (err) {\n warnings.push(`malformed handoff: ${err instanceof Error ? err.message : 'parse error'}`);\n return null;\n }\n}\n\nasync function readSourceIdsForSection(\n packPath: string,\n sectionId: string,\n): Promise<string[]> {\n const path = join(packPath, 'sections', sectionId, 'sources.jsonl');\n if (!existsSync(path)) return [];\n const text = await readFile(path, 'utf8');\n const ids: string[] = [];\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n const parsed = JSON.parse(line) as { source_id?: string };\n if (typeof parsed.source_id === 'string') ids.push(parsed.source_id);\n } catch {\n /* skip */\n }\n }\n return ids;\n}\n\nexport async function audit(options: AuditOptions): Promise<AuditSummary> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n const yamlPath = join(packPath, 'research.yaml');\n if (!existsSync(yamlPath)) throw new PackNotFoundError(packPath);\n const research: ResearchYaml = ResearchYamlSchema.parse(yamlParse(await readFile(yamlPath, 'utf8')));\n\n const warnings: string[] = [];\n const perSection: AggregateInput['perSection'] = new Map();\n for (const section of research.sections) {\n const sid = section.id;\n const claims = await readJsonl<Claim>(\n join(packPath, 'sections', sid, 'claims.jsonl'),\n (r) => ClaimSchema.parse(r),\n warnings,\n );\n const candidateClaims = claims.filter((c) => c.review_state === 'candidate');\n const claimReviews = await readJsonl<ClaimReview>(\n join(packPath, 'sections', sid, 'claim-reviews.jsonl'),\n (r) => ClaimReviewSchema.parse(r),\n warnings,\n );\n const contradictions = await readJsonl<Contradiction>(\n join(packPath, 'sections', sid, 'contradictions.jsonl'),\n (r) => ContradictionSchema.parse(r),\n warnings,\n );\n const resolutions = await readJsonl<ContradictionResolution>(\n join(packPath, 'sections', sid, 'contradiction-resolutions.jsonl'),\n (r) => ContradictionResolutionSchema.parse(r),\n warnings,\n );\n const dispositions = await readJsonl<ClaimSynthesisDisposition>(\n join(packPath, 'sections', sid, 'claim-synthesis-dispositions.jsonl'),\n (r) => ClaimSynthesisDispositionSchema.parse(r),\n warnings,\n );\n const findings = await readJsonl<ReviewFinding>(\n join(packPath, 'audits', `${sid}-findings.jsonl`),\n (r) => ReviewFindingSchema.parse(r),\n warnings,\n );\n const gate = await readGate(packPath, sid, warnings);\n const sourceIdsForSection = await readSourceIdsForSection(packPath, sid);\n perSection.set(sid, {\n claims,\n candidateClaims,\n claimReviews,\n contradictions,\n resolutions,\n dispositions,\n gate,\n findings,\n sourceIdsForSection,\n });\n }\n\n const sources = await readSourceCards(packPath, warnings);\n const receipts = await readJsonl<FetchReceipt>(\n join(packPath, 'evidence', 'fetch-log.jsonl'),\n (r) => FetchReceiptSchema.parse(r),\n warnings,\n );\n const handoff = await readHandoff(packPath, warnings);\n\n const generatedAt = new Date().toISOString();\n const result = aggregate({\n research,\n perSection,\n sources,\n receipts,\n handoff,\n generatedAt,\n warnings,\n });\n\n // Validate the payload before writing\n const payload = PackAuditPayloadSchema.parse(result.payload);\n\n const auditsDir = join(packPath, 'audits');\n await mkdir(auditsDir, { recursive: true });\n const filesWritten: string[] = [];\n\n const writeFileAndTrack = async (rel: string, content: string): Promise<void> => {\n const abs = join(packPath, rel);\n await writeFile(abs, content, 'utf8');\n filesWritten.push(abs);\n };\n\n await writeFileAndTrack('audits/pack-audit.json', JSON.stringify(payload, null, 2));\n await writeFileAndTrack('audits/pack-audit.md', renderPackAuditMarkdown(payload));\n\n await writeFileAndTrack('audits/orphan-claims.json', JSON.stringify(result.orphanClaims, null, 2));\n await writeFileAndTrack('audits/orphan-claims.md', renderOrphanClaimsMarkdown(result.orphanClaims));\n\n await writeFileAndTrack('audits/stale-sources.json', JSON.stringify(result.staleSources, null, 2));\n await writeFileAndTrack('audits/stale-sources.md', renderStaleSourcesMarkdown(result.staleSources));\n\n await writeFileAndTrack('audits/weak-sources.json', JSON.stringify(result.weakSources, null, 2));\n await writeFileAndTrack('audits/weak-sources.md', renderWeakSourcesMarkdown(result.weakSources));\n\n await writeFileAndTrack(\n 'audits/unresolved-contradictions.json',\n JSON.stringify(result.unresolvedContradictions, null, 2),\n );\n await writeFileAndTrack(\n 'audits/unresolved-contradictions.md',\n renderUnresolvedContradictionsMarkdown(result.unresolvedContradictions),\n );\n\n await writeFileAndTrack(\n 'audits/scope-widening-risks.json',\n JSON.stringify(result.scopeWideningRisks, null, 2),\n );\n await writeFileAndTrack(\n 'audits/scope-widening-risks.md',\n renderScopeWideningRisksMarkdown(result.scopeWideningRisks),\n );\n\n await writeFileAndTrack(\n 'audits/source-diversity-gaps.json',\n JSON.stringify(result.sourceDiversityGaps, null, 2),\n );\n await writeFileAndTrack(\n 'audits/source-diversity-gaps.md',\n renderSourceDiversityGapsMarkdown(result.sourceDiversityGaps),\n );\n\n await writeFileAndTrack('audits/synthesis-readiness.json', JSON.stringify(payload.section_summaries, null, 2));\n await writeFileAndTrack('audits/synthesis-readiness.md', renderSynthesisReadinessMarkdown(payload));\n\n return {\n packPath,\n verdict: payload.verdict,\n synthesisAllowed: payload.synthesis_allowed,\n filesWritten,\n warnings: payload.warnings,\n blockingReasons: payload.blocking_reasons,\n orphans: result.orphanClaims.length,\n staleSources: result.staleSources.length,\n weakSources: result.weakSources.length,\n unresolvedContradictions: result.unresolvedContradictions.length,\n scopeWideningRisks: result.scopeWideningRisks.length,\n sourceDiversityGaps: result.sourceDiversityGaps.length,\n };\n}\n","export { audit } from './run.js';\nexport { aggregate } from './aggregate.js';\nexport {\n renderPackAuditMarkdown,\n renderOrphanClaimsMarkdown,\n renderStaleSourcesMarkdown,\n renderWeakSourcesMarkdown,\n renderUnresolvedContradictionsMarkdown,\n renderScopeWideningRisksMarkdown,\n renderSourceDiversityGapsMarkdown,\n renderSynthesisReadinessMarkdown,\n} from './markdown.js';\nexport {\n PackVerdictSchema,\n HandoffModeSchema as AuditHandoffModeSchema,\n OrphanClaimRowSchema,\n StaleSourceRowSchema,\n WeakSourceRowSchema,\n UnresolvedContradictionRowSchema,\n ScopeWideningRiskRowSchema,\n SourceDiversityGapRowSchema,\n SynthesisReadinessRowSchema,\n PackAuditPayloadSchema,\n} from './schema.js';\nexport type {\n PackVerdict,\n HandoffMode as AuditHandoffMode,\n OrphanClaimRow,\n StaleSourceRow,\n WeakSourceRow,\n UnresolvedContradictionRow,\n ScopeWideningRiskRow,\n SourceDiversityGapRow,\n SynthesisReadinessRow,\n PackAuditPayload,\n ClaimSummary,\n SourceSummary,\n ContradictionSummary,\n ReviewSummary,\n WaiverSummary,\n ReadinessSummary,\n AuditOptions,\n AuditSummary,\n} from './types.js';\n","import { existsSync } from 'node:fs';\nimport { readFile, stat } from 'node:fs/promises';\nimport { createHash } from 'node:crypto';\nimport { join } from 'node:path';\n\nimport type { ArtifactHash, IntegrityCheck } from './types.js';\n\nexport interface CheckContext {\n packPath: string;\n invalidArtifacts: Array<{ path: string; error: string }>;\n missingArtifacts: string[];\n}\n\nexport async function fileSha256(absPath: string): Promise<ArtifactHash> {\n const buf = await readFile(absPath);\n const sha = createHash('sha256').update(buf).digest('hex');\n return { path: absPath, sha256: sha, bytes: buf.byteLength };\n}\n\nexport async function hashArtifact(\n ctx: CheckContext,\n rel: string,\n): Promise<ArtifactHash | null> {\n const abs = join(ctx.packPath, rel);\n if (!existsSync(abs)) {\n ctx.missingArtifacts.push(rel);\n return null;\n }\n try {\n const s = await stat(abs);\n if (!s.isFile()) {\n ctx.invalidArtifacts.push({ path: rel, error: 'not a regular file' });\n return null;\n }\n const h = await fileSha256(abs);\n return { ...h, path: rel };\n } catch (err) {\n ctx.invalidArtifacts.push({\n path: rel,\n error: err instanceof Error ? err.message : 'read error',\n });\n return null;\n }\n}\n\nexport function pass(name: string, detail = ''): IntegrityCheck {\n return { name, passed: true, detail: detail || 'ok' };\n}\n\nexport function fail(name: string, detail: string): IntegrityCheck {\n return { name, passed: false, detail };\n}\n","// Permissive at extract; strict at validate. Anything inside [claim:...] counts as\n// an attempted citation — freeze then checks whether the captured id resolves.\nconst CITATION_PATTERN = /\\[claim:([^\\]\\s]+)\\]/g;\nconst STRICT_CLAIM_ID_PATTERN = /^clm_[a-f0-9]{12}_(heuristic|ollama_intern)_\\d+$/;\n\nexport function isWellFormedClaimId(id: string): boolean {\n return STRICT_CLAIM_ID_PATTERN.test(id);\n}\n\nexport function extractClaimCitations(text: string): string[] {\n const out = new Set<string>();\n let match: RegExpExecArray | null;\n while ((match = CITATION_PATTERN.exec(text)) !== null) {\n out.add(match[1]!);\n }\n return Array.from(out);\n}\n\nexport function extractContradictionDisclosures(text: string, contradictionIds: string[]): string[] {\n const out: string[] = [];\n for (const id of contradictionIds) {\n if (text.includes(id)) out.push(id);\n }\n return out;\n}\n\nexport function extractWaiverDisclosures(\n text: string,\n waivers: Array<{ family: string; applied_to: string; reason: string }>,\n): string[] {\n // A waiver counts as disclosed if its applied_to identifier OR its family appears\n // verbatim in the synthesis text.\n const out: string[] = [];\n for (const w of waivers) {\n if (\n text.includes(w.applied_to) ||\n text.includes(w.family) ||\n (w.reason && w.reason.length > 12 && text.includes(w.reason.slice(0, 40)))\n ) {\n out.push(`${w.family}.${w.applied_to}`);\n }\n }\n return out;\n}\n","import type { FreezeReceiptPayload, FreezeRefusalPayload } from './types.js';\n\nexport function renderFreezeReceiptMarkdown(p: FreezeReceiptPayload): string {\n const lines: string[] = [];\n lines.push(`# Freeze Receipt: ${p.pack_topic}`);\n lines.push('');\n lines.push(`**Verdict:** [FROZEN]`);\n lines.push(`**Pack ID:** \\`${p.pack_id}\\``);\n lines.push(`**Frozen at:** ${p.frozen_at}`);\n lines.push('');\n lines.push(\n '> Freeze locks completed research truth. Every artifact below carries a sha256 fingerprint. The pack is now immutable evidence; any further mutation invalidates the receipt.',\n );\n lines.push('');\n\n lines.push('## Counts');\n lines.push('');\n lines.push(`- **Sources:** ${p.source_count}`);\n lines.push(`- **Claims:** ${p.claim_count}`);\n lines.push(`- **Contradictions:** ${p.contradiction_count}`);\n lines.push(`- **Review findings:** ${p.review_finding_count}`);\n lines.push(`- **Gate results:** ${p.gate_result_count}`);\n lines.push('');\n\n lines.push('## Sections');\n lines.push('');\n lines.push('| Section | Status | Accepted claims | Sources | Contradictions |');\n lines.push('|---|---|---|---|---|');\n for (const s of p.sections) {\n lines.push(`| \\`${s.section_id}\\` | ${s.status} | ${s.accepted_claims} | ${s.sources} | ${s.contradictions} |`);\n }\n lines.push('');\n\n lines.push('## Citation coverage');\n lines.push('');\n lines.push(`- **Accepted claims:** ${p.accepted_claim_ids.length}`);\n lines.push(`- **Cited in synthesis:** ${p.cited_claim_ids.length}`);\n lines.push(`- **Uncited accepted (informational):** ${p.uncited_accepted_claim_ids.length}`);\n if (p.uncited_accepted_claim_ids.length > 0) {\n lines.push('');\n lines.push('Uncited accepted claim_ids (preserved for future synthesis):');\n for (const cid of p.uncited_accepted_claim_ids) lines.push(`- \\`${cid}\\``);\n }\n lines.push('');\n\n lines.push('## Unresolved contradictions disclosed');\n lines.push('');\n if (p.unresolved_contradictions.length === 0) {\n lines.push('_None._');\n } else {\n for (const c of p.unresolved_contradictions) {\n lines.push(`- \\`${c.contradiction_id}\\` (\\`${c.section_id}\\`, ${c.type}, ${c.severity}) — disclosed in ${c.disclosed_in.map((d) => `\\`${d}\\``).join(', ')}`);\n }\n }\n lines.push('');\n\n lines.push('## Waivers disclosed');\n lines.push('');\n if (p.waivers_disclosed.length === 0) {\n lines.push('_None active._');\n } else {\n for (const w of p.waivers_disclosed) {\n lines.push(`- **${w.family}.${w.applied_to}** — disclosed in ${w.disclosed_in.map((d) => `\\`${d}\\``).join(', ')}`);\n lines.push(` - Reason: ${w.reason}`);\n for (const cc of w.compensating_controls) lines.push(` - Compensating: ${cc}`);\n }\n }\n lines.push('');\n\n lines.push('## Integrity checks');\n lines.push('');\n for (const c of p.integrity_checks) {\n const glyph = c.passed ? '[PASS]' : '[FAIL]';\n lines.push(`- ${glyph} **${c.name}** — ${c.detail}`);\n }\n lines.push('');\n\n lines.push('## Synthesis fingerprints');\n lines.push('');\n lines.push('| Path | Bytes | sha256 |');\n lines.push('|---|---|---|');\n for (const h of p.synthesis_hashes) {\n lines.push(`| \\`${h.path}\\` | ${h.bytes} | \\`${h.sha256.slice(0, 16)}…\\` |`);\n }\n lines.push('');\n\n lines.push('## Canonical artifact fingerprints');\n lines.push('');\n lines.push(`Total: ${p.canonical_artifact_hashes.length} files`);\n lines.push('');\n lines.push('| Path | Bytes | sha256 |');\n lines.push('|---|---|---|');\n for (const h of p.canonical_artifact_hashes) {\n lines.push(`| \\`${h.path}\\` | ${h.bytes} | \\`${h.sha256.slice(0, 16)}…\\` |`);\n }\n lines.push('');\n\n return lines.join('\\n');\n}\n\nexport function renderFreezeRefusalMarkdown(p: FreezeRefusalPayload): string {\n const lines: string[] = [];\n lines.push(`# Freeze Refusal: ${p.pack_topic}`);\n lines.push('');\n lines.push(`**Verdict:** [REFUSED]`);\n lines.push(`**Pack ID:** \\`${p.pack_id}\\``);\n lines.push(`**Checked at:** ${p.checked_at}`);\n lines.push(`**Would freeze:** no`);\n lines.push('');\n lines.push(\n '> Freeze locks completed research truth. It does not complete unfinished research, excuse missing synthesis, or convert repair state into evidence. The conditions below were not met; the pack remains active.',\n );\n lines.push('');\n\n if (p.blocking_reasons.length > 0) {\n lines.push('## Blocking reasons');\n lines.push('');\n for (const r of p.blocking_reasons) lines.push(`- ${r}`);\n lines.push('');\n }\n\n if (p.reasons.length > 0) {\n lines.push('## All reasons');\n lines.push('');\n for (const r of p.reasons) lines.push(`- ${r}`);\n lines.push('');\n }\n\n if (p.missing_artifacts.length > 0) {\n lines.push('## Missing artifacts');\n lines.push('');\n for (const a of p.missing_artifacts) lines.push(`- \\`${a}\\``);\n lines.push('');\n }\n\n if (p.invalid_artifacts.length > 0) {\n lines.push('## Invalid artifacts');\n lines.push('');\n for (const ia of p.invalid_artifacts) lines.push(`- \\`${ia.path}\\` — ${ia.error}`);\n lines.push('');\n }\n\n if (p.next_actions.length > 0) {\n lines.push('## Next actions');\n lines.push('');\n let i = 1;\n for (const a of p.next_actions) {\n lines.push(`${i}. ${a}`);\n i += 1;\n }\n lines.push('');\n }\n\n return lines.join('\\n');\n}\n","import { z } from 'zod';\n\nexport const ArtifactHashSchema = z.object({\n path: z.string(),\n sha256: z.string().regex(/^[a-f0-9]{64}$/),\n bytes: z.number().int().nonnegative(),\n});\n\nexport const IntegrityCheckSchema = z.object({\n name: z.string().min(1),\n passed: z.boolean(),\n detail: z.string(),\n});\n\nexport const FreezeReceiptPayloadSchema = z.object({\n pack_id: z.string(),\n pack_topic: z.string(),\n frozen_at: z.string(),\n verdict: z.literal('frozen'),\n pack_audit_hash: z.string().regex(/^[a-f0-9]{64}$/),\n handoff_hash: z.string().regex(/^[a-f0-9]{64}$/),\n synthesis_hashes: z.array(ArtifactHashSchema),\n canonical_artifact_hashes: z.array(ArtifactHashSchema),\n accepted_claim_ids: z.array(z.string()),\n cited_claim_ids: z.array(z.string()),\n uncited_accepted_claim_ids: z.array(z.string()),\n unresolved_contradictions: z.array(\n z.object({\n contradiction_id: z.string(),\n section_id: z.string(),\n type: z.string(),\n severity: z.string(),\n status: z.string(),\n disclosed_in: z.array(z.string()),\n }),\n ),\n waivers_disclosed: z.array(\n z.object({\n family: z.string(),\n applied_to: z.string(),\n reason: z.string(),\n compensating_controls: z.array(z.string()),\n disclosed_in: z.array(z.string()),\n }),\n ),\n sections: z.array(\n z.object({\n section_id: z.string(),\n status: z.string(),\n accepted_claims: z.number().int().nonnegative(),\n sources: z.number().int().nonnegative(),\n contradictions: z.number().int().nonnegative(),\n }),\n ),\n source_count: z.number().int().nonnegative(),\n claim_count: z.number().int().nonnegative(),\n contradiction_count: z.number().int().nonnegative(),\n review_finding_count: z.number().int().nonnegative(),\n gate_result_count: z.number().int().nonnegative(),\n integrity_checks: z.array(IntegrityCheckSchema),\n});\n\nexport const FreezeRefusalPayloadSchema = z.object({\n pack_id: z.string(),\n pack_topic: z.string(),\n checked_at: z.string(),\n verdict: z.literal('refused'),\n reasons: z.array(z.string()),\n blocking_reasons: z.array(z.string()),\n missing_artifacts: z.array(z.string()),\n invalid_artifacts: z.array(z.object({ path: z.string(), error: z.string() })),\n next_actions: z.array(z.string()),\n would_freeze: z.literal(false),\n});\n\nexport type FreezeReceiptPayload = z.infer<typeof FreezeReceiptPayloadSchema>;\nexport type FreezeRefusalPayload = z.infer<typeof FreezeRefusalPayloadSchema>;\n","import { existsSync } from 'node:fs';\nimport { mkdir, readFile, readdir, unlink, writeFile } from 'node:fs/promises';\nimport { createHash } from 'node:crypto';\nimport { join, resolve } from 'node:path';\nimport { parse as yamlParse, stringify as yamlStringify } from 'yaml';\n\nimport { PackNotFoundError } from '../errors.js';\nimport { ResearchYamlSchema, type ResearchYaml } from '../intake/schema.js';\nimport {\n PackAuditPayloadSchema,\n type PackAuditPayload,\n} from '../audit/schema.js';\nimport {\n CoworkHandoffPayloadSchema,\n type CoworkHandoffPayload,\n} from '../cowork/schema.js';\nimport { CrossSectionMapSchema } from '../synth/schema.js';\nimport { ClaimSchema } from '../claims/schema.js';\nimport { ClaimReviewSchema, type ClaimReview } from '../review/schema.js';\n\nimport { hashArtifact, pass, type CheckContext } from './checks.js';\nimport {\n extractClaimCitations,\n extractWaiverDisclosures,\n isWellFormedClaimId,\n} from './citations.js';\nimport { renderFreezeReceiptMarkdown, renderFreezeRefusalMarkdown } from './markdown.js';\nimport {\n FreezeReceiptPayloadSchema,\n FreezeRefusalPayloadSchema,\n} from './schema.js';\nimport type {\n ArtifactHash,\n FreezeOptions,\n FreezeReceiptPayload,\n FreezeRefusalPayload,\n FreezeSummary,\n IntegrityCheck,\n} from './types.js';\n\nconst REQUIRED_PACK_ARTIFACTS = ['research.yaml', 'audits/pack-audit.json', 'handoffs/cowork-handoff.json'];\nconst SYNTHESIS_FILES = [\n 'synthesis/cross-section-map.json',\n 'synthesis/cross-section-map.md',\n 'synthesis/decision-brief.md',\n 'synthesis/working-report.md',\n 'synthesis/final-report.md',\n];\n\nfunction packId(research: ResearchYaml): string {\n const fingerprint = `${research.topic}|${research.created_at}`;\n let hash = 0;\n for (let i = 0; i < fingerprint.length; i += 1) {\n hash = Math.imul(31, hash) + fingerprint.charCodeAt(i);\n hash |= 0;\n }\n return Math.abs(hash).toString(16).padStart(12, '0').slice(-12);\n}\n\nfunction fileSha256Of(text: string): string {\n return createHash('sha256').update(text).digest('hex');\n}\n\ninterface RefusalContext {\n reasons: string[];\n blockingReasons: string[];\n missingArtifacts: string[];\n invalidArtifacts: Array<{ path: string; error: string }>;\n}\n\nfunction noteRefusal(ctx: RefusalContext, reason: string, blocking = true): void {\n ctx.reasons.push(reason);\n if (blocking) ctx.blockingReasons.push(reason);\n}\n\nasync function tryReadJson<T>(\n packPath: string,\n rel: string,\n parse: (raw: unknown) => T,\n invalid: Array<{ path: string; error: string }>,\n): Promise<T | null> {\n const abs = join(packPath, rel);\n if (!existsSync(abs)) return null;\n try {\n return parse(JSON.parse(await readFile(abs, 'utf8')));\n } catch (err) {\n invalid.push({ path: rel, error: err instanceof Error ? err.message : 'parse error' });\n return null;\n }\n}\n\nexport async function freeze(options: FreezeOptions): Promise<FreezeSummary> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n const yamlPath = join(packPath, 'research.yaml');\n if (!existsSync(yamlPath)) throw new PackNotFoundError(packPath);\n\n const refusal: RefusalContext = {\n reasons: [],\n blockingReasons: [],\n missingArtifacts: [],\n invalidArtifacts: [],\n };\n let research: ResearchYaml;\n try {\n research = ResearchYamlSchema.parse(yamlParse(await readFile(yamlPath, 'utf8')));\n } catch (err) {\n refusal.invalidArtifacts.push({ path: 'research.yaml', error: err instanceof Error ? err.message : 'parse error' });\n return writeRefusal({\n packPath,\n pid: 'unknown',\n topic: 'unknown',\n refusal,\n });\n }\n\n const pid = packId(research);\n\n // Required artifacts presence\n for (const rel of REQUIRED_PACK_ARTIFACTS) {\n if (!existsSync(join(packPath, rel))) {\n refusal.missingArtifacts.push(rel);\n noteRefusal(refusal, `Required artifact missing: ${rel}.`);\n }\n }\n for (const rel of SYNTHESIS_FILES) {\n if (!existsSync(join(packPath, rel))) {\n refusal.missingArtifacts.push(rel);\n noteRefusal(refusal, `Synthesis artifact missing: ${rel}. Run \\`research-os synth workspace\\` after the pack reaches synthesis_ready.`);\n }\n }\n\n const packAudit = await tryReadJson<PackAuditPayload>(\n packPath,\n 'audits/pack-audit.json',\n (r) => PackAuditPayloadSchema.parse(r),\n refusal.invalidArtifacts,\n );\n const handoff = await tryReadJson<CoworkHandoffPayload>(\n packPath,\n 'handoffs/cowork-handoff.json',\n (r) => CoworkHandoffPayloadSchema.parse(r),\n refusal.invalidArtifacts,\n );\n const crossSectionMap = await tryReadJson(\n packPath,\n 'synthesis/cross-section-map.json',\n (r) => CrossSectionMapSchema.parse(r),\n refusal.invalidArtifacts,\n );\n\n if (refusal.invalidArtifacts.length > 0) {\n for (const ia of refusal.invalidArtifacts) {\n noteRefusal(refusal, `Canonical artifact failed to parse: ${ia.path}: ${ia.error}`);\n }\n }\n\n if (packAudit && packAudit.verdict !== 'ready_for_synthesis') {\n noteRefusal(refusal, `Pack audit verdict is \"${packAudit.verdict}\", not \"ready_for_synthesis\".`);\n }\n if (handoff && handoff.mode !== 'synthesis_ready') {\n noteRefusal(refusal, `Cowork handoff mode is \"${handoff.mode}\", not \"synthesis_ready\".`);\n }\n\n // Citation analysis\n const finalReportAbs = join(packPath, 'synthesis/final-report.md');\n const decisionBriefAbs = join(packPath, 'synthesis/decision-brief.md');\n const workingReportAbs = join(packPath, 'synthesis/working-report.md');\n let finalReportText = '';\n let decisionBriefText = '';\n let workingReportText = '';\n if (existsSync(finalReportAbs)) finalReportText = await readFile(finalReportAbs, 'utf8');\n if (existsSync(decisionBriefAbs)) decisionBriefText = await readFile(decisionBriefAbs, 'utf8');\n if (existsSync(workingReportAbs)) workingReportText = await readFile(workingReportAbs, 'utf8');\n\n // Defense in depth: read live claims + claim-reviews directly rather than\n // trusting the cross-section-map snapshot. If reviews changed after synth\n // workspace ran, we want to catch it at freeze.\n const livePackClaimIds = new Set<string>();\n const liveLatestDecisionByClaim = new Map<string, string>();\n const liveLatestCreatedAtByClaim = new Map<string, string>();\n for (const section of research.sections) {\n const claimsFile = join(packPath, 'sections', section.id, 'claims.jsonl');\n if (existsSync(claimsFile)) {\n const text = await readFile(claimsFile, 'utf8');\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n const c = ClaimSchema.parse(JSON.parse(line));\n livePackClaimIds.add(c.claim_id);\n } catch (err) {\n refusal.invalidArtifacts.push({\n path: `sections/${section.id}/claims.jsonl`,\n error: err instanceof Error ? err.message : 'parse error',\n });\n }\n }\n }\n const reviewsFile = join(packPath, 'sections', section.id, 'claim-reviews.jsonl');\n if (existsSync(reviewsFile)) {\n const text = await readFile(reviewsFile, 'utf8');\n const reviews: ClaimReview[] = [];\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n reviews.push(ClaimReviewSchema.parse(JSON.parse(line)));\n } catch (err) {\n refusal.invalidArtifacts.push({\n path: `sections/${section.id}/claim-reviews.jsonl`,\n error: err instanceof Error ? err.message : 'parse error',\n });\n }\n }\n // Latest by created_at wins\n for (const r of reviews) {\n const existingCreatedAt = liveLatestCreatedAtByClaim.get(r.claim_id);\n if (!existingCreatedAt || r.created_at > existingCreatedAt) {\n liveLatestCreatedAtByClaim.set(r.claim_id, r.created_at);\n liveLatestDecisionByClaim.set(r.claim_id, r.decision);\n }\n }\n }\n }\n\n const acceptedClaimIds: string[] = [];\n for (const [cid, decision] of liveLatestDecisionByClaim) {\n if (decision === 'accepted_for_synthesis') acceptedClaimIds.push(cid);\n }\n acceptedClaimIds.sort();\n\n const allClaimIds = livePackClaimIds;\n const repairOrRejected = new Set<string>();\n for (const [cid, decision] of liveLatestDecisionByClaim) {\n if (decision === 'rejected' || decision.startsWith('needs_')) {\n repairOrRejected.add(cid);\n }\n }\n\n const citationsInFinal = extractClaimCitations(finalReportText);\n const citationsInBrief = extractClaimCitations(decisionBriefText);\n const citationsInWorking = extractClaimCitations(workingReportText);\n const allCitedSet = new Set<string>([...citationsInFinal, ...citationsInBrief, ...citationsInWorking]);\n const allCited = Array.from(allCitedSet);\n\n const unknownCitations = allCited.filter((c) => isWellFormedClaimId(c) && !allClaimIds.has(c));\n const repairCitations = allCited.filter((c) => repairOrRejected.has(c));\n const uncitedAccepted = acceptedClaimIds.filter((c) => !allCitedSet.has(c));\n\n if (existsSync(finalReportAbs) && finalReportText.trim().length > 0) {\n if (citationsInFinal.length === 0 && acceptedClaimIds.length > 0) {\n noteRefusal(refusal, 'final-report.md contains no [claim:...] citations even though accepted claims exist.');\n }\n }\n if (unknownCitations.length > 0) {\n noteRefusal(refusal, `Synthesis cites unknown claim_id(s) not present in the pack: ${unknownCitations.join(', ')}.`);\n }\n if (repairCitations.length > 0) {\n noteRefusal(refusal, `Synthesis cites claim(s) that are in repair or rejected state: ${repairCitations.join(', ')}.`);\n }\n\n // Disclosure check: every unresolved contradiction must appear in decision-brief.md OR final-report.md\n const unresolvedContradictionRefs: FreezeReceiptPayload['unresolved_contradictions'] = [];\n if (crossSectionMap) {\n for (const c of crossSectionMap.cross_section_contradictions) {\n if (c.status !== 'unresolved') continue;\n const disclosedIn: string[] = [];\n if (decisionBriefText.includes(c.contradiction_id)) disclosedIn.push('synthesis/decision-brief.md');\n if (finalReportText.includes(c.contradiction_id)) disclosedIn.push('synthesis/final-report.md');\n if (disclosedIn.length === 0) {\n noteRefusal(refusal, `Unresolved contradiction ${c.contradiction_id} not disclosed in decision-brief.md or final-report.md.`);\n }\n unresolvedContradictionRefs.push({\n contradiction_id: c.contradiction_id,\n section_id: c.sections.join(','),\n type: c.type,\n severity: c.severity,\n status: c.status,\n disclosed_in: disclosedIn,\n });\n }\n }\n\n // Waiver disclosure\n const waiversDisclosed: FreezeReceiptPayload['waivers_disclosed'] = [];\n if (handoff) {\n for (const w of handoff.waivers) {\n const disclosedInBrief = extractWaiverDisclosures(decisionBriefText, [w]);\n const disclosedInFinal = extractWaiverDisclosures(finalReportText, [w]);\n const disclosedIn: string[] = [];\n if (disclosedInBrief.length > 0) disclosedIn.push('synthesis/decision-brief.md');\n if (disclosedInFinal.length > 0) disclosedIn.push('synthesis/final-report.md');\n if (disclosedIn.length === 0) {\n noteRefusal(refusal, `Waiver \"${w.family}.${w.applied_to}\" is not disclosed in decision-brief.md or final-report.md.`);\n }\n waiversDisclosed.push({\n family: w.family,\n applied_to: w.applied_to,\n reason: w.reason,\n compensating_controls: w.compensating_controls,\n disclosed_in: disclosedIn,\n });\n }\n }\n\n // Section status — every section must have a gate audit on file\n for (const section of research.sections) {\n if (!existsSync(join(packPath, 'audits', `${section.id}-gate.json`))) {\n noteRefusal(refusal, `Section ${section.id} has no gate result on file.`);\n refusal.missingArtifacts.push(`audits/${section.id}-gate.json`);\n }\n }\n\n // If we have refusal reasons, write the refusal artifact and return\n if (refusal.reasons.length > 0) {\n return writeRefusal({\n packPath,\n pid,\n topic: research.topic,\n refusal,\n });\n }\n\n // PASS PATH\n // Compute integrity checks\n const checks: IntegrityCheck[] = [];\n const ctx: CheckContext = {\n packPath,\n invalidArtifacts: [],\n missingArtifacts: [],\n };\n\n const synthesisHashes: ArtifactHash[] = [];\n for (const rel of SYNTHESIS_FILES) {\n const h = await hashArtifact(ctx, rel);\n if (h) synthesisHashes.push(h);\n }\n\n const canonicalPaths: string[] = [];\n canonicalPaths.push('research.yaml');\n for (const section of research.sections) {\n canonicalPaths.push(\n `sections/${section.id}/claims.jsonl`,\n `sections/${section.id}/sources.jsonl`,\n `sections/${section.id}/contradictions.jsonl`,\n `sections/${section.id}/claim-reviews.jsonl`,\n `sections/${section.id}/gates.yaml`,\n `audits/${section.id}-gate.json`,\n `audits/${section.id}-review.json`,\n `audits/${section.id}-findings.jsonl`,\n );\n }\n canonicalPaths.push('evidence/fetch-log.jsonl');\n canonicalPaths.push('evidence/citation-ledger.jsonl');\n if (existsSync(join(packPath, 'evidence', 'source-cards'))) {\n const entries = await readdir(join(packPath, 'evidence', 'source-cards'));\n for (const e of entries) {\n if (e.endsWith('.json')) canonicalPaths.push(`evidence/source-cards/${e}`);\n }\n }\n\n const canonicalHashes: ArtifactHash[] = [];\n for (const rel of canonicalPaths) {\n const abs = join(packPath, rel);\n if (!existsSync(abs)) continue;\n const h = await hashArtifact(ctx, rel);\n if (h) canonicalHashes.push(h);\n }\n\n checks.push(pass('pack_audit_ready', `pack-audit verdict=${packAudit?.verdict}`));\n checks.push(pass('handoff_synthesis_ready', `cowork-handoff mode=${handoff?.mode}`));\n checks.push(pass('synthesis_workspace_present', `${synthesisHashes.length}/${SYNTHESIS_FILES.length} synthesis files hashed`));\n checks.push(\n pass(\n 'final_report_cites_accepted_claims_only',\n `${citationsInFinal.length} citation(s); 0 unknown, 0 repair/rejected`,\n ),\n );\n checks.push(\n pass(\n 'unresolved_contradictions_disclosed',\n `${unresolvedContradictionRefs.length} contradiction(s) checked`,\n ),\n );\n checks.push(pass('waivers_disclosed', `${waiversDisclosed.length} waiver(s) checked`));\n checks.push(pass('canonical_artifacts_fingerprinted', `${canonicalHashes.length} artifact(s) hashed`));\n\n const packAuditHash = packAudit ? fileSha256Of(JSON.stringify(packAudit)) : '0'.repeat(64);\n const handoffHash = handoff ? fileSha256Of(JSON.stringify(handoff)) : '0'.repeat(64);\n\n // Section summaries\n const sections = research.sections.map((s) => {\n const handoffSection = handoff?.sections.find((hs) => hs.section_id === s.id);\n return {\n section_id: s.id,\n status: 'frozen',\n accepted_claims: handoffSection?.accepted_claim_ids.length ?? 0,\n sources: 0, // populated below if cross-section-map has data\n contradictions: handoffSection?.unresolved_contradiction_ids.length ?? 0,\n };\n });\n\n const frozenAt = new Date().toISOString();\n const receipt: FreezeReceiptPayload = FreezeReceiptPayloadSchema.parse({\n pack_id: pid,\n pack_topic: research.topic,\n frozen_at: frozenAt,\n verdict: 'frozen',\n pack_audit_hash: packAuditHash,\n handoff_hash: handoffHash,\n synthesis_hashes: synthesisHashes,\n canonical_artifact_hashes: canonicalHashes,\n accepted_claim_ids: acceptedClaimIds,\n cited_claim_ids: allCited,\n uncited_accepted_claim_ids: uncitedAccepted,\n unresolved_contradictions: unresolvedContradictionRefs,\n waivers_disclosed: waiversDisclosed,\n sections,\n source_count: canonicalHashes.filter((h) => h.path.includes('source-cards/')).length,\n claim_count: acceptedClaimIds.length,\n contradiction_count: unresolvedContradictionRefs.length,\n review_finding_count: 0,\n gate_result_count: research.sections.filter((s) => existsSync(join(packPath, 'audits', `${s.id}-gate.json`))).length,\n integrity_checks: checks,\n });\n\n // Update research.yaml: frozen_at + bump section statuses to 'frozen'\n const frozenResearch: ResearchYaml = {\n ...research,\n frozen_at: frozenAt,\n sections: research.sections.map((s) => ({ ...s, status: 'frozen' as const })),\n };\n await writeFile(yamlPath, yamlStringify(frozenResearch, { lineWidth: 0 }), 'utf8');\n\n const auditsDir = join(packPath, 'audits');\n await mkdir(auditsDir, { recursive: true });\n // Remove any stale refusal from a previous run\n for (const stale of ['freeze-refusal.json', 'freeze-refusal.md']) {\n const p = join(auditsDir, stale);\n if (existsSync(p)) await unlink(p);\n }\n const jsonPath = join(auditsDir, 'freeze-receipt.json');\n const mdPath = join(auditsDir, 'freeze-receipt.md');\n await writeFile(jsonPath, JSON.stringify(receipt, null, 2), 'utf8');\n await writeFile(mdPath, renderFreezeReceiptMarkdown(receipt), 'utf8');\n\n return {\n packPath,\n verdict: 'frozen',\n jsonPath,\n markdownPath: mdPath,\n receiptPayload: receipt,\n refusalPayload: null,\n reasonsCount: 0,\n citedClaimCount: allCited.length,\n uncitedAcceptedClaimCount: uncitedAccepted.length,\n };\n}\n\nasync function writeRefusal(args: {\n packPath: string;\n pid: string;\n topic: string;\n refusal: RefusalContext;\n}): Promise<FreezeSummary> {\n const checkedAt = new Date().toISOString();\n const nextActions = buildRefusalNextActions(args.refusal);\n const payload: FreezeRefusalPayload = FreezeRefusalPayloadSchema.parse({\n pack_id: args.pid,\n pack_topic: args.topic,\n checked_at: checkedAt,\n verdict: 'refused',\n reasons: args.refusal.reasons,\n blocking_reasons: args.refusal.blockingReasons,\n missing_artifacts: args.refusal.missingArtifacts,\n invalid_artifacts: args.refusal.invalidArtifacts,\n next_actions: nextActions,\n would_freeze: false,\n });\n\n const auditsDir = join(args.packPath, 'audits');\n await mkdir(auditsDir, { recursive: true });\n // Remove any stale receipt from a previous successful freeze that has now regressed\n for (const stale of ['freeze-receipt.json', 'freeze-receipt.md']) {\n const p = join(auditsDir, stale);\n if (existsSync(p)) await unlink(p);\n }\n const jsonPath = join(auditsDir, 'freeze-refusal.json');\n const mdPath = join(auditsDir, 'freeze-refusal.md');\n await writeFile(jsonPath, JSON.stringify(payload, null, 2), 'utf8');\n await writeFile(mdPath, renderFreezeRefusalMarkdown(payload), 'utf8');\n\n return {\n packPath: args.packPath,\n verdict: 'refused',\n jsonPath,\n markdownPath: mdPath,\n receiptPayload: null,\n refusalPayload: payload,\n reasonsCount: payload.reasons.length,\n citedClaimCount: 0,\n uncitedAcceptedClaimCount: 0,\n };\n}\n\nfunction buildRefusalNextActions(refusal: RefusalContext): string[] {\n const actions = new Set<string>();\n for (const r of refusal.reasons) {\n if (r.includes('pack-audit') || r.includes('Pack audit')) {\n actions.add('Run `research-os audit` after addressing repair items; freeze requires verdict=ready_for_synthesis.');\n }\n if (r.includes('handoff') || r.includes('Cowork handoff')) {\n actions.add('Run `research-os cowork handoff` after the pack reaches synthesis_ready.');\n }\n if (r.includes('synth') || r.includes('Synthesis')) {\n actions.add('Run `research-os synth workspace` to lay out the synthesis area (it refuses unless mode=synthesis_ready).');\n }\n if (r.includes('final-report')) {\n actions.add('Edit synthesis/final-report.md to cite accepted claims via [claim:clm_...] references.');\n }\n if (r.includes('unknown claim_id')) {\n actions.add('Replace any [claim:...] citation in synthesis with a claim_id that exists in the pack.');\n }\n if (r.includes('repair or rejected')) {\n actions.add('Remove citations to repair/rejected claims from synthesis or repair them via review.');\n }\n if (r.includes('contradiction') && r.includes('not disclosed')) {\n actions.add('Disclose every unresolved contradiction by id in decision-brief.md or final-report.md.');\n }\n if (r.includes('Waiver') && r.includes('not disclosed')) {\n actions.add('Disclose each active waiver by family.applied_to in decision-brief.md or final-report.md.');\n }\n if (r.includes('gate result on file')) {\n actions.add('Run `research-os gate <section>` for any section without a gate audit.');\n }\n if (r.includes('failed to parse')) {\n actions.add('Repair the malformed canonical artifact reported above (zod will not parse a corrupt file).');\n }\n }\n if (actions.size === 0) {\n actions.add('Re-run `research-os audit` to surface a fresh next-actions list.');\n }\n return Array.from(actions);\n}\n","export { freeze } from './run.js';\nexport { extractClaimCitations, extractContradictionDisclosures, extractWaiverDisclosures } from './citations.js';\nexport {\n renderFreezeReceiptMarkdown,\n renderFreezeRefusalMarkdown,\n} from './markdown.js';\nexport {\n ArtifactHashSchema,\n IntegrityCheckSchema,\n FreezeReceiptPayloadSchema,\n FreezeRefusalPayloadSchema,\n} from './schema.js';\nexport type {\n ArtifactHash,\n IntegrityCheck,\n CitationCoverage,\n FreezeReceiptPayload,\n FreezeRefusalPayload,\n FreezeOptions,\n FreezeSummary,\n} from './types.js';\n","import { z } from 'zod';\n\n// An invalidation receipt records that a class of artifacts was archived\n// because the contract that produced them was superseded. It is the\n// truth-preserving alternative to silent deletion: the old artifacts move\n// into audits/legacy/<label>/<timestamp>/, the receipt names what moved and\n// why, and downstream consumers can see that legacy state existed and\n// what replaced it.\n\nexport const ArchivedArtifactSchema = z.object({\n src: z.string(), // path relative to packPath, before archival\n dst: z.string(), // path relative to packPath, after archival\n});\n\nexport const SectionStatusChangeSchema = z.object({\n section_id: z.string().regex(/^[0-9]{2}-[a-z0-9-]+$/),\n before: z.string(),\n after: z.string(),\n});\n\nexport const InvalidationReceiptSchema = z.object({\n receipt_id: z.string().regex(/^inv_[0-9]+_[a-z0-9-]+$/),\n contract_label: z.string().min(1),\n superseded_contract: z.string().min(1).nullable(),\n new_contract: z.string().min(1),\n reason: z.string().min(8),\n invalidated_at: z.string(),\n research_os_version: z.string(),\n affected_sections: z.array(z.string().regex(/^[0-9]{2}-[a-z0-9-]+$/)),\n archived_artifacts: z.array(ArchivedArtifactSchema),\n section_status_changes: z.array(SectionStatusChangeSchema),\n frozen_at_cleared: z.boolean(),\n notes: z.string().nullable(),\n});\n\nexport type InvalidationReceipt = z.infer<typeof InvalidationReceiptSchema>;\nexport type ArchivedArtifact = z.infer<typeof ArchivedArtifactSchema>;\nexport type SectionStatusChange = z.infer<typeof SectionStatusChangeSchema>;\n","import { existsSync } from 'node:fs';\nimport { mkdir, readFile, readdir, rename, writeFile } from 'node:fs/promises';\nimport { dirname, join, posix, relative, resolve, sep } from 'node:path';\nimport { parse as yamlParse, stringify as yamlStringify } from 'yaml';\n\nimport { PackNotFoundError } from '../errors.js';\nimport { ResearchYamlSchema, type ResearchYaml } from '../intake/schema.js';\nimport { RESEARCH_OS_VERSION } from '../index.js';\nimport {\n InvalidationReceiptSchema,\n type ArchivedArtifact,\n type InvalidationReceipt,\n type SectionStatusChange,\n} from './schema.js';\nimport type {\n InvalidateExtractionOptions,\n InvalidateExtractionResult,\n} from './types.js';\n\n// Make all stored paths POSIX-style for cross-platform receipt portability.\nfunction posixify(p: string): string {\n return p.split(sep).join('/');\n}\n\n// A claim authored under the legacy contract has either no\n// evidence_excerpt_ids field at all, or an empty array. Span-first writes\n// always populate >= 1.\nfunction isLegacyClaimLine(line: string): boolean {\n const trimmed = line.trim();\n if (!trimmed) return false;\n try {\n const obj = JSON.parse(trimmed) as { evidence_excerpt_ids?: unknown };\n if (obj.evidence_excerpt_ids === undefined) return true;\n if (!Array.isArray(obj.evidence_excerpt_ids)) return true;\n return obj.evidence_excerpt_ids.length === 0;\n } catch {\n return false;\n }\n}\n\nasync function detectLegacyClaimSections(packPath: string): Promise<string[]> {\n const sectionsDir = join(packPath, 'sections');\n if (!existsSync(sectionsDir)) return [];\n const entries = await readdir(sectionsDir, { withFileTypes: true });\n const affected: string[] = [];\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n const claimsPath = join(sectionsDir, entry.name, 'claims.jsonl');\n if (!existsSync(claimsPath)) continue;\n const text = await readFile(claimsPath, 'utf8');\n let hasLegacy = false;\n for (const line of text.split(/\\r?\\n/)) {\n if (isLegacyClaimLine(line)) {\n hasLegacy = true;\n break;\n }\n }\n if (hasLegacy) affected.push(entry.name);\n }\n return affected.sort();\n}\n\nasync function moveIfExists(\n packPath: string,\n archiveRel: string,\n rel: string,\n): Promise<ArchivedArtifact | null> {\n const src = join(packPath, rel);\n if (!existsSync(src)) return null;\n const dst = join(packPath, archiveRel, rel);\n await mkdir(dirname(dst), { recursive: true });\n await rename(src, dst);\n return { src: posixify(rel), dst: posixify(join(archiveRel, rel)) };\n}\n\nasync function moveDirContentsIfExists(\n packPath: string,\n archiveRel: string,\n relDir: string,\n // Skip any path under the new archive itself so we never archive into ourselves.\n // skipPrefix is POSIX-style (forward slashes); we compare against POSIX form\n // of relative paths to keep behaviour identical across Windows and POSIX.\n skipPrefix: string,\n): Promise<ArchivedArtifact[]> {\n const fullDir = join(packPath, relDir);\n if (!existsSync(fullDir)) return [];\n const entries = await readdir(fullDir, { withFileTypes: true });\n const moved: ArchivedArtifact[] = [];\n for (const entry of entries) {\n // Always join in POSIX form for stable cross-platform comparisons.\n const childRelPosix = posix.join(posixify(relDir), entry.name);\n if (childRelPosix === skipPrefix || childRelPosix.startsWith(skipPrefix + '/')) continue;\n if (entry.isDirectory()) {\n moved.push(\n ...(await moveDirContentsIfExists(packPath, archiveRel, childRelPosix, skipPrefix)),\n );\n } else if (entry.isFile()) {\n const m = await moveIfExists(packPath, archiveRel, childRelPosix);\n if (m) moved.push(m);\n }\n }\n return moved;\n}\n\nfunction buildReceiptMarkdown(receipt: InvalidationReceipt): string {\n const lines: string[] = [];\n lines.push(`# Invalidation receipt: ${receipt.contract_label}`);\n lines.push('');\n lines.push(`- **Receipt ID:** \\`${receipt.receipt_id}\\``);\n lines.push(`- **Invalidated at:** ${receipt.invalidated_at}`);\n lines.push(`- **research-os version:** ${receipt.research_os_version}`);\n lines.push(`- **New contract:** ${receipt.new_contract}`);\n if (receipt.superseded_contract) {\n lines.push(`- **Superseded contract:** ${receipt.superseded_contract}`);\n }\n lines.push(`- **frozen_at cleared:** ${receipt.frozen_at_cleared ? 'yes' : 'no'}`);\n lines.push('');\n lines.push('## Reason');\n lines.push('');\n lines.push(receipt.reason);\n lines.push('');\n if (receipt.notes) {\n lines.push('## Notes');\n lines.push('');\n lines.push(receipt.notes);\n lines.push('');\n }\n lines.push(`## Affected sections (${receipt.affected_sections.length})`);\n lines.push('');\n if (receipt.affected_sections.length === 0) {\n lines.push('_None at the section level — only pack-level downstream artifacts were archived._');\n } else {\n for (const id of receipt.affected_sections) lines.push(`- \\`${id}\\``);\n }\n lines.push('');\n lines.push(`## Section status changes (${receipt.section_status_changes.length})`);\n lines.push('');\n if (receipt.section_status_changes.length === 0) {\n lines.push('_No section status changes._');\n } else {\n lines.push('| Section | Before | After |');\n lines.push('|---|---|---|');\n for (const c of receipt.section_status_changes) {\n lines.push(`| \\`${c.section_id}\\` | ${c.before} | ${c.after} |`);\n }\n }\n lines.push('');\n lines.push(`## Archived artifacts (${receipt.archived_artifacts.length})`);\n lines.push('');\n if (receipt.archived_artifacts.length === 0) {\n lines.push('_No artifacts archived._');\n } else {\n lines.push('Each row shows where the artifact was, and where it lives now.');\n lines.push('');\n lines.push('| From | To |');\n lines.push('|---|---|');\n for (const a of receipt.archived_artifacts) {\n lines.push(`| \\`${a.src}\\` | \\`${a.dst}\\` |`);\n }\n }\n lines.push('');\n return lines.join('\\n');\n}\n\nexport async function invalidateExtraction(\n options: InvalidateExtractionOptions,\n): Promise<InvalidateExtractionResult> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n const yamlPath = join(packPath, 'research.yaml');\n if (!existsSync(yamlPath)) throw new PackNotFoundError(packPath);\n\n const reason = options.reason.trim();\n if (reason.length < 8) {\n throw new Error('invalidation reason must be at least 8 characters');\n }\n\n const label = (options.label ?? 'pre-span-extraction').trim();\n if (!/^[a-z0-9-]+$/.test(label)) {\n throw new Error('invalidation label must be a kebab-case slug');\n }\n const newContract = options.newContract ?? 'span-first-extraction';\n const supersededContract = options.supersededContract ?? 'authored-evidence-excerpt';\n\n const now = options.now ?? (() => new Date());\n const stamp = now();\n const stampMs = stamp.getTime();\n const stampIso = stamp.toISOString();\n // Folder-friendly ISO without colons.\n const stampPath = stampIso.replace(/[:]/g, '').replace(/\\.\\d+Z$/, 'Z');\n const archiveRel = posix.join('audits', 'legacy', label, stampPath);\n\n const affectedSections = await detectLegacyClaimSections(packPath);\n\n const research = ResearchYamlSchema.parse(yamlParse(await readFile(yamlPath, 'utf8')));\n\n // Pack-level downstream artifacts that depend on extraction truth. Even if\n // only one section's claims are legacy, these aggregate over all sections\n // and reflect a state that no longer exists. Re-run audit/handoff/synth\n // after invalidation to rebuild them.\n const packLevelDirs = ['handoffs', 'synthesis', 'audits'];\n\n // If no affected sections AND no pack-level artifacts to archive, nothing\n // to do — return idempotent no-op.\n let probeArtifactsExist = affectedSections.length > 0;\n if (!probeArtifactsExist) {\n for (const d of packLevelDirs) {\n const full = join(packPath, d);\n if (!existsSync(full)) continue;\n // For audits/, a pre-existing legacy/ tree alone shouldn't trigger.\n const entries = await readdir(full, { withFileTypes: true });\n const meaningful = entries.some(\n (e) => !(d === 'audits' && e.isDirectory() && e.name === 'legacy'),\n );\n if (meaningful) {\n probeArtifactsExist = true;\n break;\n }\n }\n }\n\n if (!probeArtifactsExist) {\n return {\n performed: false,\n receiptId: null,\n contractLabel: label,\n affectedSections: [],\n archivedCount: 0,\n archiveDir: null,\n message: 'No legacy artifacts found. Pack is on the current extraction contract.',\n };\n }\n\n // Make the archive root early so moveIfExists has a stable target.\n await mkdir(join(packPath, archiveRel), { recursive: true });\n\n const archived: ArchivedArtifact[] = [];\n\n // Per-section files for affected sections.\n for (const sectionId of affectedSections) {\n for (const filename of [\n 'claims.jsonl',\n 'claim-reviews.jsonl',\n 'findings.jsonl',\n 'contradictions.jsonl',\n 'contradictions.md',\n 'claims.md',\n ]) {\n const rel = posix.join('sections', sectionId, filename);\n const a = await moveIfExists(packPath, archiveRel, rel);\n if (a) archived.push(a);\n }\n }\n\n // Pack-level downstream artifacts. Skip the archive's own subtree so we\n // don't try to archive ourselves.\n const skipPrefix = posix.join('audits', 'legacy');\n for (const d of packLevelDirs) {\n archived.push(...(await moveDirContentsIfExists(packPath, archiveRel, d, skipPrefix)));\n }\n\n // Reset section statuses for affected sections; remember the original.\n const statusChanges: SectionStatusChange[] = [];\n const affectedSet = new Set(affectedSections);\n const updatedSections = research.sections.map((s) => {\n if (!affectedSet.has(s.id)) return s;\n if (s.status === 'draft') return s;\n statusChanges.push({ section_id: s.id, before: s.status, after: 'draft' });\n return { ...s, status: 'draft' as const };\n });\n const frozenAtCleared = research.frozen_at !== null;\n const updated: ResearchYaml = {\n ...research,\n sections: updatedSections,\n frozen_at: null,\n };\n await writeFile(yamlPath, yamlStringify(updated, { lineWidth: 0 }), 'utf8');\n\n const receipt: InvalidationReceipt = InvalidationReceiptSchema.parse({\n receipt_id: `inv_${stampMs}_${label}`,\n contract_label: label,\n superseded_contract: supersededContract,\n new_contract: newContract,\n reason,\n invalidated_at: stampIso,\n research_os_version: RESEARCH_OS_VERSION,\n affected_sections: affectedSections,\n archived_artifacts: archived,\n section_status_changes: statusChanges,\n frozen_at_cleared: frozenAtCleared,\n notes: options.notes ?? null,\n });\n\n const receiptDir = join(packPath, archiveRel);\n await writeFile(\n join(receiptDir, 'invalidation.json'),\n JSON.stringify(receipt, null, 2),\n 'utf8',\n );\n await writeFile(\n join(receiptDir, 'invalidation.md'),\n buildReceiptMarkdown(receipt),\n 'utf8',\n );\n\n const archiveDirRel = posixify(relative(packPath, receiptDir));\n return {\n performed: true,\n receiptId: receipt.receipt_id,\n contractLabel: label,\n affectedSections,\n archivedCount: archived.length,\n archiveDir: archiveDirRel,\n message: `Archived ${archived.length} artifact(s) across ${affectedSections.length} affected section(s) → ${archiveDirRel}`,\n };\n}\n","import { existsSync } from 'node:fs';\nimport { mkdir, rename, writeFile } from 'node:fs/promises';\nimport { dirname, join, posix, relative, resolve, sep } from 'node:path';\n\nimport { PackNotFoundError, SectionNotFoundError } from '../errors.js';\nimport { RESEARCH_OS_VERSION } from '../index.js';\nimport {\n ArchivedArtifactSchema,\n type ArchivedArtifact,\n} from './schema.js';\nimport { z } from 'zod';\n\n// Review-scoped invalidation receipt. Distinct from the extraction\n// invalidation receipt because it operates on a different artifact set\n// and a different scope (per-section, not pack-wide), but follows the\n// same truth-preserving pattern: archive + receipt, never silent delete.\n\nexport const ReviewInvalidationReceiptSchema = z.object({\n receipt_id: z.string().regex(/^invr_[0-9]+_[a-z0-9-]+$/),\n section_id: z.string().regex(/^[0-9]{2}-[a-z0-9-]+$/),\n contract_label: z.string().min(1),\n reason: z.string().min(8),\n invalidated_at: z.string(),\n research_os_version: z.string(),\n archived_artifacts: z.array(ArchivedArtifactSchema),\n notes: z.string().nullable(),\n});\n\nexport type ReviewInvalidationReceipt = z.infer<typeof ReviewInvalidationReceiptSchema>;\n\nexport interface InvalidateReviewOptions {\n packPath?: string;\n sectionId: string;\n reason: string;\n // Folder label under sections/<id>/legacy/. Default: 'pre-review-profiles'.\n label?: string;\n notes?: string;\n now?: () => Date;\n}\n\nexport interface InvalidateReviewResult {\n performed: boolean;\n receiptId: string | null;\n sectionId: string;\n contractLabel: string;\n archivedCount: number;\n archiveDir: string | null;\n message: string;\n}\n\nfunction posixify(p: string): string {\n return p.split(sep).join('/');\n}\n\nasync function moveIfExists(\n packPath: string,\n archiveRel: string,\n rel: string,\n): Promise<ArchivedArtifact | null> {\n const src = join(packPath, rel);\n if (!existsSync(src)) return null;\n const dst = join(packPath, archiveRel, rel);\n await mkdir(dirname(dst), { recursive: true });\n await rename(src, dst);\n return { src: posixify(rel), dst: posixify(join(archiveRel, rel)) };\n}\n\nfunction buildReceiptMarkdown(receipt: ReviewInvalidationReceipt): string {\n const lines: string[] = [];\n lines.push(`# Review invalidation receipt: ${receipt.section_id}`);\n lines.push('');\n lines.push(`- **Receipt ID:** \\`${receipt.receipt_id}\\``);\n lines.push(`- **Contract label:** ${receipt.contract_label}`);\n lines.push(`- **Invalidated at:** ${receipt.invalidated_at}`);\n lines.push(`- **research-os version:** ${receipt.research_os_version}`);\n lines.push('');\n lines.push('## Reason');\n lines.push('');\n lines.push(receipt.reason);\n lines.push('');\n if (receipt.notes) {\n lines.push('## Notes');\n lines.push('');\n lines.push(receipt.notes);\n lines.push('');\n }\n lines.push(`## Archived artifacts (${receipt.archived_artifacts.length})`);\n lines.push('');\n if (receipt.archived_artifacts.length === 0) {\n lines.push('_No artifacts found to archive (canonical review state was already empty)._');\n } else {\n lines.push('| From | To |');\n lines.push('|---|---|');\n for (const a of receipt.archived_artifacts) {\n lines.push(`| \\`${a.src}\\` | \\`${a.dst}\\` |`);\n }\n }\n lines.push('');\n lines.push('---');\n lines.push('');\n lines.push(\n '_The reviewer profile data under `sections/<id>/reviews/<profile>/` is unaffected; this receipt only invalidates canonical (active) review state. Promote a profile via `research-os review-promote` to set new canonical truth._',\n );\n return lines.join('\\n');\n}\n\n// Archive the canonical review artifacts for a single section. The pre-profile\n// dogfood pack accumulated mixed Hermes/Qwen review history before profile\n// isolation existed; that ambiguity is itself a truth-seam and must be\n// invalidated explicitly, not papered over by the next promote.\nexport async function invalidateReview(\n options: InvalidateReviewOptions,\n): Promise<InvalidateReviewResult> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n if (!existsSync(join(packPath, 'research.yaml'))) throw new PackNotFoundError(packPath);\n if (!existsSync(join(packPath, 'sections', options.sectionId)))\n throw new SectionNotFoundError(options.sectionId);\n\n const reason = options.reason.trim();\n if (reason.length < 8) {\n throw new Error('invalidation reason must be at least 8 characters');\n }\n const label = (options.label ?? 'pre-review-profiles').trim();\n if (!/^[a-z0-9-]+$/.test(label)) {\n throw new Error('invalidation label must be a kebab-case slug');\n }\n\n const stamp = (options.now ?? (() => new Date()))();\n const stampMs = stamp.getTime();\n const stampIso = stamp.toISOString();\n const stampPath = stampIso.replace(/[:]/g, '').replace(/\\.\\d+Z$/, 'Z');\n const archiveRel = posix.join('sections', options.sectionId, 'legacy', label, stampPath);\n\n // Canonical review artifacts to archive.\n const candidatePaths = [\n posix.join('audits', `${options.sectionId}-review.json`),\n posix.join('audits', `${options.sectionId}-review.md`),\n posix.join('audits', `${options.sectionId}-findings.jsonl`),\n posix.join('sections', options.sectionId, 'claim-reviews.jsonl'),\n // Also clear review-active.json so the next review run is unambiguous.\n posix.join('sections', options.sectionId, 'review-active.json'),\n ];\n\n // No-op if there's nothing to archive.\n const present = candidatePaths.filter((rel) => existsSync(join(packPath, rel)));\n if (present.length === 0) {\n return {\n performed: false,\n receiptId: null,\n sectionId: options.sectionId,\n contractLabel: label,\n archivedCount: 0,\n archiveDir: null,\n message:\n 'No canonical review artifacts found to invalidate. Section has no active review state.',\n };\n }\n\n await mkdir(join(packPath, archiveRel), { recursive: true });\n const archived: ArchivedArtifact[] = [];\n for (const rel of present) {\n const a = await moveIfExists(packPath, archiveRel, rel);\n if (a) archived.push(a);\n }\n\n const receipt: ReviewInvalidationReceipt = ReviewInvalidationReceiptSchema.parse({\n receipt_id: `invr_${stampMs}_${options.sectionId}`,\n section_id: options.sectionId,\n contract_label: label,\n reason,\n invalidated_at: stampIso,\n research_os_version: RESEARCH_OS_VERSION,\n archived_artifacts: archived,\n notes: options.notes ?? null,\n });\n\n const receiptDir = join(packPath, archiveRel);\n await writeFile(\n join(receiptDir, 'invalidation.json'),\n JSON.stringify(receipt, null, 2),\n 'utf8',\n );\n await writeFile(\n join(receiptDir, 'invalidation.md'),\n buildReceiptMarkdown(receipt),\n 'utf8',\n );\n\n return {\n performed: true,\n receiptId: receipt.receipt_id,\n sectionId: options.sectionId,\n contractLabel: label,\n archivedCount: archived.length,\n archiveDir: posixify(relative(packPath, receiptDir)),\n message: `Archived ${archived.length} canonical review artifact(s) → ${posixify(relative(packPath, receiptDir))}`,\n };\n}\n","export { invalidateExtraction } from './run.js';\nexport {\n invalidateReview,\n ReviewInvalidationReceiptSchema,\n type ReviewInvalidationReceipt,\n type InvalidateReviewOptions,\n type InvalidateReviewResult,\n} from './review.js';\nexport {\n InvalidationReceiptSchema,\n ArchivedArtifactSchema,\n SectionStatusChangeSchema,\n type InvalidationReceipt,\n type ArchivedArtifact,\n type SectionStatusChange,\n} from './schema.js';\nexport type {\n InvalidateExtractionOptions,\n InvalidateExtractionResult,\n} from './types.js';\n","export { triage, readTriagedClaimIds } from './run.js';\nexport {\n ClaimTriageSchema,\n TriageDecisionSchema,\n TriageSummarySchema,\n type ClaimTriage,\n type TriageDecision,\n type TriageSummary,\n} from './schema.js';\nexport type { TriageOptions, TriageRunResult } from './types.js';\n","import { z } from 'zod';\n\n// Discovery proposes leads. A lead is NOT evidence. A lead becomes evidence\n// only after fetch receipt + source card + excerpt ledger + claim extraction.\n//\n// The boundary is enforced structurally: discovery writes to its own\n// per-section ledger and produces an `urls.approved.txt` file for `gather`\n// to consume. `gather` is unaware of how URLs were proposed; it just fetches\n// and emits receipts. If a discovered URL doesn't fetch, the operator sees a\n// failed receipt — exactly as if they'd typed the URL themselves.\n\nexport const DiscoveryCandidateStatusSchema = z.enum([\n 'candidate',\n 'approved',\n 'rejected',\n]);\n\nexport const SourceTypeGuessSchema = z.enum([\n 'primary',\n 'docs',\n 'paper',\n 'standard',\n 'article',\n 'forum',\n 'benchmark',\n 'unknown',\n]);\n\nexport const DiscoveryCandidateSchema = z.object({\n candidate_id: z.string().regex(/^disc_[a-f0-9]{12}$/),\n section_id: z.string().regex(/^[0-9]{2}-[a-z0-9-]+$/),\n url: z.string().url(),\n title: z.string().min(1),\n publisher: z.string().nullable(),\n source_type_guess: SourceTypeGuessSchema,\n why_relevant: z.string().min(1),\n // The free-text query that produced this candidate (for traceability).\n query: z.string().min(1),\n // Lower rank = more central. Stable per-(query, provider) ordering.\n rank: z.number().int().positive(),\n discovered_at: z.string(),\n // 'candidate' | 'approved' | 'rejected'. Append-only: new entries with\n // same candidate_id supersede older ones; the latest entry's status wins.\n status: DiscoveryCandidateStatusSchema,\n discovered_by: z.string().min(1),\n reason: z.string().nullable().default(null),\n});\n\nexport const DiscoverySummarySchema = z.object({\n summary_id: z.string().regex(/^disum_[0-9]+_[a-z0-9-]+$/),\n section_id: z.string().regex(/^[0-9]{2}-[a-z0-9-]+$/),\n ran_at: z.string(),\n research_os_version: z.string(),\n query: z.string().min(1),\n provider: z.string().min(1),\n candidates_proposed: z.number().int().nonnegative(),\n candidates_validated: z.number().int().nonnegative(),\n candidates_rejected_invalid_url: z.number().int().nonnegative(),\n warnings: z.array(z.string()),\n});\n\nexport type DiscoveryCandidate = z.infer<typeof DiscoveryCandidateSchema>;\nexport type DiscoveryCandidateStatus = z.infer<typeof DiscoveryCandidateStatusSchema>;\nexport type SourceTypeGuess = z.infer<typeof SourceTypeGuessSchema>;\nexport type DiscoverySummary = z.infer<typeof DiscoverySummarySchema>;\n","import { normalizeOllamaHost } from '../../sources/extractors/ollama-intern.js';\nimport type {\n DiscoverProposal,\n DiscoverProvider,\n DiscoverProviderInput,\n DiscoverProviderResult,\n} from '../types.js';\nimport type { SourceTypeGuess } from '../schema.js';\n\nconst DEFAULT_HOST = 'http://localhost:11434';\nconst DEFAULT_MODEL = 'hermes3:8b';\nconst DEFAULT_TIMEOUT_MS = 240_000;\n\nconst SYSTEM_PROMPT = `You are proposing source URLs for a research-pack section. You produce LEADS, not evidence. The system fetches each lead and decides on its own whether the URL is real and the content is acceptable.\n\nReturn ONE JSON object: {\"candidates\": [...]}.\n\nFor each candidate:\n{\n \"url\": \"absolute https URL\",\n \"title\": \"short human-readable title\",\n \"publisher\": \"the entity that hosts/publishes this page, or null if unknown\",\n \"source_type_guess\": one of \"primary\" | \"docs\" | \"paper\" | \"standard\" | \"article\" | \"forum\" | \"benchmark\" | \"unknown\",\n \"why_relevant\": \"ONE sentence on why this source is relevant to the section purpose\",\n \"rank\": integer 1..N where 1 is most central\n}\n\nHard rules:\n- Propose ONLY URLs you have high confidence exist. Canonical documentation, well-known papers, foundational standards, recognized authority sites. If you would have to guess, do not propose it.\n- Prefer primary sources (specs, official docs, peer-reviewed papers, standards bodies) over blog posts or forum threads.\n- Each URL must be a syntactically valid absolute https://… URL. No relative paths. No placeholder URLs.\n- Each title must be the actual page title or a tight summary, not a generic search-keyword string.\n- Be honest about source_type_guess; use \"unknown\" if truly unsure.\n- Order by rank — most central first. Do not return more than the requested target count.\n- If you cannot find enough confident candidates, return fewer. Quality over quantity.`;\n\nexport interface LlmHeuristicConfig {\n host?: string;\n model?: string;\n timeoutMs?: number;\n fetchImpl?: typeof fetch;\n}\n\ninterface ChatResponse {\n message?: { content?: string };\n response?: string;\n}\n\nconst VALID_SOURCE_TYPES: SourceTypeGuess[] = [\n 'primary',\n 'docs',\n 'paper',\n 'standard',\n 'article',\n 'forum',\n 'benchmark',\n 'unknown',\n];\n\nfunction asString(v: unknown, fallback = ''): string {\n return typeof v === 'string' && v.trim().length > 0 ? v.trim() : fallback;\n}\n\nfunction asStringOrNull(v: unknown): string | null {\n return typeof v === 'string' && v.trim().length > 0 ? v.trim() : null;\n}\n\nfunction asSourceType(v: unknown): SourceTypeGuess {\n return typeof v === 'string' && (VALID_SOURCE_TYPES as readonly string[]).includes(v)\n ? (v as SourceTypeGuess)\n : 'unknown';\n}\n\nexport class LlmHeuristicDiscoverProvider implements DiscoverProvider {\n readonly name = 'llm-heuristic';\n private readonly host: string;\n private readonly model: string;\n private readonly timeoutMs: number;\n private readonly fetchImpl: typeof fetch;\n\n constructor(config: LlmHeuristicConfig = {}) {\n this.host = normalizeOllamaHost(config.host ?? process.env.OLLAMA_HOST ?? DEFAULT_HOST);\n this.model = config.model ?? process.env.OLLAMA_INTERN_MODEL ?? DEFAULT_MODEL;\n this.timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n this.fetchImpl = config.fetchImpl ?? globalThis.fetch;\n }\n\n async available(): Promise<boolean> {\n try {\n const ctrl = new AbortController();\n const t = setTimeout(() => ctrl.abort(), 1500);\n const res = await this.fetchImpl(`${this.host}/api/tags`, { signal: ctrl.signal });\n clearTimeout(t);\n if (!res.ok) return false;\n const body = (await res.json()) as { models?: Array<{ name: string }> };\n const names = (body.models ?? []).map((m) => m.name);\n const family = this.model.split(':')[0] ?? this.model;\n return names.some((n) => n === this.model || n === family || n.startsWith(`${family}:`));\n } catch {\n return false;\n }\n }\n\n async propose(input: DiscoverProviderInput): Promise<DiscoverProviderResult> {\n const userMsg = `Section: ${input.sectionId}\nSection purpose: ${input.sectionPurpose}\nQuery: ${input.query}\nTarget candidate count: ${input.targetCount}\n\nPropose source-URL candidates for this section. Quality over quantity.`;\n\n const ctrl = new AbortController();\n const t = setTimeout(() => ctrl.abort(), this.timeoutMs);\n let body: ChatResponse;\n try {\n const res = await this.fetchImpl(`${this.host}/api/chat`, {\n method: 'POST',\n signal: ctrl.signal,\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n model: this.model,\n stream: false,\n format: 'json',\n options: { num_ctx: 8192 },\n messages: [\n { role: 'system', content: SYSTEM_PROMPT },\n { role: 'user', content: userMsg },\n ],\n }),\n });\n if (!res.ok) return { ok: false, error: `Ollama HTTP ${res.status}` };\n body = (await res.json()) as ChatResponse;\n } catch (err) {\n return { ok: false, error: err instanceof Error ? err.message : 'Ollama request failed' };\n } finally {\n clearTimeout(t);\n }\n\n const text = body.message?.content ?? body.response ?? '';\n let parsed: { candidates?: unknown };\n try {\n parsed = JSON.parse(text) as { candidates?: unknown };\n } catch {\n return { ok: false, error: 'Ollama response was not valid JSON' };\n }\n if (!Array.isArray(parsed.candidates)) {\n return { ok: false, error: 'Ollama response did not contain a candidates array' };\n }\n\n const proposals: DiscoverProposal[] = [];\n let nextRank = 1;\n for (const raw of parsed.candidates) {\n if (!raw || typeof raw !== 'object') continue;\n const r = raw as Record<string, unknown>;\n const url = asString(r.url);\n const title = asString(r.title);\n const why = asString(r.why_relevant);\n if (!url || !title || !why) continue;\n const rRank = typeof r.rank === 'number' && r.rank >= 1 ? Math.floor(r.rank) : nextRank;\n proposals.push({\n url,\n title,\n publisher: asStringOrNull(r.publisher),\n source_type_guess: asSourceType(r.source_type_guess),\n why_relevant: why,\n rank: rRank,\n });\n nextRank += 1;\n }\n return { ok: true, proposals, method: 'llm_heuristic_canonical_only' };\n }\n}\n","import { existsSync } from 'node:fs';\nimport { createHash } from 'node:crypto';\nimport { mkdir, readFile, writeFile, appendFile } from 'node:fs/promises';\nimport { join, resolve } from 'node:path';\nimport { parse as yamlParse } from 'yaml';\n\nimport { PackNotFoundError, SectionNotFoundError } from '../errors.js';\nimport { ResearchYamlSchema } from '../intake/schema.js';\nimport { RESEARCH_OS_VERSION } from '../index.js';\nimport {\n DiscoveryCandidateSchema,\n DiscoverySummarySchema,\n type DiscoveryCandidate,\n type DiscoveryCandidateStatus,\n type DiscoverySummary,\n} from './schema.js';\nimport type {\n ApproveOptions,\n ApproveResult,\n DiscoverOptions,\n DiscoverProvider,\n DiscoverProposal,\n DiscoverResult,\n ExportUrlsOptions,\n ExportUrlsResult,\n RejectOptions,\n RejectResult,\n} from './types.js';\nimport { LlmHeuristicDiscoverProvider } from './providers/llm-heuristic.js';\n\nconst DEFAULT_TARGET_COUNT = 12;\n\nfunction makeCandidateId(sectionId: string, url: string): string {\n // Stable per-(section,url) so re-running discover with the same query\n // doesn't generate duplicate candidate ids.\n const hex = createHash('sha256').update(`${sectionId}|${url}`).digest('hex').slice(0, 12);\n return `disc_${hex}`;\n}\n\nfunction isHttpsUrl(s: string): boolean {\n try {\n const u = new URL(s);\n return u.protocol === 'http:' || u.protocol === 'https:';\n } catch {\n return false;\n }\n}\n\nfunction candidatesPath(packPath: string, sectionId: string): string {\n return join(packPath, 'sections', sectionId, 'discovery-candidates.jsonl');\n}\n\nfunction reportPath(packPath: string, sectionId: string): string {\n return join(packPath, 'sections', sectionId, 'discovery-report.md');\n}\n\nfunction summaryPath(packPath: string, sectionId: string): string {\n return join(packPath, 'audits', `${sectionId}-discovery.json`);\n}\n\nfunction approvedUrlsPath(packPath: string, sectionId: string): string {\n return join(packPath, 'sections', sectionId, 'urls.approved.txt');\n}\n\nasync function readCandidates(packPath: string, sectionId: string): Promise<DiscoveryCandidate[]> {\n const path = candidatesPath(packPath, sectionId);\n if (!existsSync(path)) return [];\n const text = await readFile(path, 'utf8');\n const out: DiscoveryCandidate[] = [];\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n out.push(DiscoveryCandidateSchema.parse(JSON.parse(line)));\n } catch {\n /* skip malformed line */\n }\n }\n return out;\n}\n\n// Append-only ledger: latest entry per candidate_id wins. Approve/reject\n// emit a fresh entry with updated status; the ledger preserves history.\nfunction latestPerCandidate(candidates: DiscoveryCandidate[]): Map<string, DiscoveryCandidate> {\n const out = new Map<string, DiscoveryCandidate>();\n for (const c of candidates) {\n const prev = out.get(c.candidate_id);\n if (!prev || prev.discovered_at < c.discovered_at) out.set(c.candidate_id, c);\n }\n return out;\n}\n\nfunction defaultProviders(): DiscoverProvider[] {\n return [new LlmHeuristicDiscoverProvider()];\n}\n\nasync function pickProvider(providers: DiscoverProvider[]): Promise<DiscoverProvider | null> {\n for (const p of providers) {\n if (await p.available()) return p;\n }\n return null;\n}\n\nasync function loadSectionPurpose(packPath: string, sectionId: string): Promise<string> {\n const research = ResearchYamlSchema.parse(\n yamlParse(await readFile(join(packPath, 'research.yaml'), 'utf8')),\n );\n const section = research.sections.find((s) => s.id === sectionId);\n return section?.purpose ?? '';\n}\n\nfunction buildReportMarkdown(args: {\n sectionId: string;\n query: string;\n provider: string;\n ranAt: string;\n candidates: DiscoveryCandidate[];\n}): string {\n const lines: string[] = [];\n lines.push(`# Discovery report: ${args.sectionId}`);\n lines.push('');\n lines.push(`- **Query:** ${args.query}`);\n lines.push(`- **Provider:** ${args.provider}`);\n lines.push(`- **Ran at:** ${args.ranAt}`);\n lines.push(`- **Candidates:** ${args.candidates.length}`);\n lines.push('');\n lines.push('## Candidates');\n lines.push('');\n if (args.candidates.length === 0) {\n lines.push('_No candidates proposed. Provider may have refused on confidence grounds, or returned an empty result._');\n return lines.join('\\n');\n }\n lines.push('Discovery results are LEADS, not evidence. A lead becomes evidence only after `research-os gather` produces a fetch receipt + source card + excerpt ledger + claim extraction.');\n lines.push('');\n lines.push('| Rank | Status | Type | Title | Publisher | Why relevant | URL |');\n lines.push('|---:|---|---|---|---|---|---|');\n const sorted = [...args.candidates].sort((a, b) => a.rank - b.rank);\n for (const c of sorted) {\n lines.push(\n `| ${c.rank} | \\`${c.status}\\` | ${c.source_type_guess} | ${c.title.replace(/\\|/g, '\\\\|')} | ${(c.publisher ?? '—').replace(/\\|/g, '\\\\|')} | ${c.why_relevant.replace(/\\|/g, '\\\\|')} | ${c.url} |`,\n );\n }\n lines.push('');\n lines.push('---');\n lines.push('');\n lines.push('Approve candidates with `research-os discover approve <section> --top N` or `--candidate disc_<hex>`. Reject with `research-os discover reject <section> --candidate disc_<hex> --reason \"...\"`. Export approved URLs for gather with `research-os discover export-urls <section>` (or `gather <section> --approved`).');\n return lines.join('\\n');\n}\n\nexport async function discover(options: DiscoverOptions): Promise<DiscoverResult> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n if (!existsSync(join(packPath, 'research.yaml'))) throw new PackNotFoundError(packPath);\n if (!existsSync(join(packPath, 'sections', options.sectionId)))\n throw new SectionNotFoundError(options.sectionId);\n\n const query = options.query.trim();\n if (query.length < 4) throw new Error('discover query must be at least 4 characters');\n\n const target = options.targetCount ?? DEFAULT_TARGET_COUNT;\n const providers = options.providers ?? defaultProviders();\n const provider = await pickProvider(providers);\n if (!provider) {\n throw new Error('No discover provider available. Default provider is LLM-based and requires Ollama.');\n }\n\n const sectionPurpose = await loadSectionPurpose(packPath, options.sectionId);\n const result = await provider.propose({\n sectionId: options.sectionId,\n query,\n sectionPurpose,\n targetCount: target,\n });\n if (!result.ok) {\n throw new Error(`Discover provider \"${provider.name}\" failed: ${result.error}`);\n }\n\n const stamp = (options.now ?? (() => new Date()))();\n const stampIso = stamp.toISOString();\n\n // Filter syntactically invalid URLs at intake. Track count for the summary;\n // the operator will see it in the report.\n const validProposals: DiscoverProposal[] = [];\n let invalidCount = 0;\n const warnings: string[] = [];\n for (const p of result.proposals) {\n if (!isHttpsUrl(p.url)) {\n invalidCount += 1;\n warnings.push(`Rejected non-https URL: ${p.url}`);\n continue;\n }\n validProposals.push(p);\n }\n\n // De-duplicate against existing candidates for this section. If the same\n // URL was previously proposed (any status), don't append a duplicate.\n const existing = await readCandidates(packPath, options.sectionId);\n const existingByUrl = new Map<string, DiscoveryCandidate>();\n for (const e of latestPerCandidate(existing).values()) existingByUrl.set(e.url, e);\n\n const newCandidates: DiscoveryCandidate[] = [];\n for (const p of validProposals) {\n if (existingByUrl.has(p.url)) {\n warnings.push(`Skipped duplicate (already proposed): ${p.url}`);\n continue;\n }\n const candidate = DiscoveryCandidateSchema.parse({\n candidate_id: makeCandidateId(options.sectionId, p.url),\n section_id: options.sectionId,\n url: p.url,\n title: p.title,\n publisher: p.publisher,\n source_type_guess: p.source_type_guess,\n why_relevant: p.why_relevant,\n query,\n rank: p.rank,\n discovered_at: stampIso,\n status: 'candidate',\n discovered_by: provider.name,\n reason: null,\n });\n newCandidates.push(candidate);\n }\n\n // Append to ledger.\n const ledgerPath = candidatesPath(packPath, options.sectionId);\n await mkdir(join(packPath, 'sections', options.sectionId), { recursive: true });\n for (const c of newCandidates) {\n await appendFile(ledgerPath, JSON.stringify(c) + '\\n', 'utf8');\n }\n\n // Render the human-readable report against the FULL latest set (not just\n // this run's new candidates), so the report reflects current section state.\n const all = await readCandidates(packPath, options.sectionId);\n const latest = Array.from(latestPerCandidate(all).values());\n const md = buildReportMarkdown({\n sectionId: options.sectionId,\n query,\n provider: provider.name,\n ranAt: stampIso,\n candidates: latest,\n });\n await writeFile(reportPath(packPath, options.sectionId), md, 'utf8');\n\n // Run-level summary.\n const summary: DiscoverySummary = DiscoverySummarySchema.parse({\n summary_id: `disum_${stamp.getTime()}_${options.sectionId}`,\n section_id: options.sectionId,\n ran_at: stampIso,\n research_os_version: RESEARCH_OS_VERSION,\n query,\n provider: provider.name,\n candidates_proposed: result.proposals.length,\n candidates_validated: newCandidates.length,\n candidates_rejected_invalid_url: invalidCount,\n warnings,\n });\n await mkdir(join(packPath, 'audits'), { recursive: true });\n await writeFile(summaryPath(packPath, options.sectionId), JSON.stringify(summary, null, 2), 'utf8');\n\n return {\n candidatesAdded: newCandidates.length,\n candidatesProposed: result.proposals.length,\n candidatesRejectedInvalidUrl: invalidCount,\n warnings,\n candidates: newCandidates,\n candidatesPath: ledgerPath,\n reportPath: reportPath(packPath, options.sectionId),\n summaryPath: summaryPath(packPath, options.sectionId),\n };\n}\n\nasync function appendStatusUpdate(\n packPath: string,\n sectionId: string,\n candidate: DiscoveryCandidate,\n newStatus: DiscoveryCandidateStatus,\n reason: string | null,\n stampIso: string,\n): Promise<DiscoveryCandidate> {\n const updated: DiscoveryCandidate = DiscoveryCandidateSchema.parse({\n ...candidate,\n status: newStatus,\n reason,\n discovered_at: stampIso,\n });\n await appendFile(candidatesPath(packPath, sectionId), JSON.stringify(updated) + '\\n', 'utf8');\n return updated;\n}\n\nexport async function approve(options: ApproveOptions): Promise<ApproveResult> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n if (!existsSync(join(packPath, 'research.yaml'))) throw new PackNotFoundError(packPath);\n if (!existsSync(join(packPath, 'sections', options.sectionId)))\n throw new SectionNotFoundError(options.sectionId);\n\n const all = await readCandidates(packPath, options.sectionId);\n const latest = latestPerCandidate(all);\n const stamp = (options.now ?? (() => new Date()))();\n const stampIso = stamp.toISOString();\n\n const targets: DiscoveryCandidate[] = [];\n if (options.candidateIds && options.candidateIds.length > 0) {\n for (const id of options.candidateIds) {\n const c = latest.get(id);\n if (!c) throw new Error(`Candidate ${id} not found in section ${options.sectionId}`);\n targets.push(c);\n }\n } else if (options.topN && options.topN > 0) {\n const eligible = Array.from(latest.values())\n .filter((c) => c.status === 'candidate')\n .sort((a, b) => a.rank - b.rank);\n targets.push(...eligible.slice(0, options.topN));\n } else {\n throw new Error('approve requires --candidate <id> or --top <N>');\n }\n\n const approvedIds: string[] = [];\n for (const t of targets) {\n if (t.status === 'approved') {\n approvedIds.push(t.candidate_id);\n continue;\n }\n await appendStatusUpdate(packPath, options.sectionId, t, 'approved', options.reason ?? null, stampIso);\n approvedIds.push(t.candidate_id);\n }\n const exportPath = await exportUrls({ packPath, sectionId: options.sectionId });\n return { approved: approvedIds.length, approvedIds, exportPath: exportPath.exportPath };\n}\n\nexport async function reject(options: RejectOptions): Promise<RejectResult> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n if (!existsSync(join(packPath, 'research.yaml'))) throw new PackNotFoundError(packPath);\n if (!existsSync(join(packPath, 'sections', options.sectionId)))\n throw new SectionNotFoundError(options.sectionId);\n if (options.reason.trim().length < 4) {\n throw new Error('reject requires --reason of at least 4 characters');\n }\n const all = await readCandidates(packPath, options.sectionId);\n const latest = latestPerCandidate(all);\n const stamp = (options.now ?? (() => new Date()))();\n const stampIso = stamp.toISOString();\n const rejectedIds: string[] = [];\n for (const id of options.candidateIds) {\n const c = latest.get(id);\n if (!c) throw new Error(`Candidate ${id} not found in section ${options.sectionId}`);\n await appendStatusUpdate(\n packPath,\n options.sectionId,\n c,\n 'rejected',\n options.reason.trim(),\n stampIso,\n );\n rejectedIds.push(id);\n }\n // Re-export approved URLs (rejection of an approved candidate removes it).\n await exportUrls({ packPath, sectionId: options.sectionId });\n return { rejected: rejectedIds.length, rejectedIds };\n}\n\nexport async function exportUrls(options: ExportUrlsOptions): Promise<ExportUrlsResult> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n if (!existsSync(join(packPath, 'research.yaml'))) throw new PackNotFoundError(packPath);\n if (!existsSync(join(packPath, 'sections', options.sectionId)))\n throw new SectionNotFoundError(options.sectionId);\n const all = await readCandidates(packPath, options.sectionId);\n const latest = latestPerCandidate(all);\n const approved = Array.from(latest.values())\n .filter((c) => c.status === 'approved')\n .sort((a, b) => a.rank - b.rank);\n const lines = approved.map((c) => c.url).join('\\n');\n const path = approvedUrlsPath(packPath, options.sectionId);\n await mkdir(join(packPath, 'sections', options.sectionId), { recursive: true });\n await writeFile(path, lines + (lines.length > 0 ? '\\n' : ''), 'utf8');\n return { exportPath: path, approvedCount: approved.length };\n}\n","export { discover, approve, reject, exportUrls } from './run.js';\nexport {\n DiscoveryCandidateSchema,\n DiscoveryCandidateStatusSchema,\n SourceTypeGuessSchema,\n DiscoverySummarySchema,\n type DiscoveryCandidate,\n type DiscoveryCandidateStatus,\n type SourceTypeGuess,\n type DiscoverySummary,\n} from './schema.js';\nexport type {\n DiscoverOptions,\n DiscoverResult,\n DiscoverProvider,\n DiscoverProviderInput,\n DiscoverProviderResult,\n DiscoverProposal,\n ApproveOptions,\n ApproveResult,\n RejectOptions,\n RejectResult,\n ExportUrlsOptions,\n ExportUrlsResult,\n} from './types.js';\nexport { LlmHeuristicDiscoverProvider } from './providers/llm-heuristic.js';\n","export * from './intake/index.js';\nexport * from './sections/index.js';\nexport * from './sources/index.js';\nexport * from './claims/index.js';\nexport * from './contradictions/index.js';\nexport * from './gates/index.js';\nexport * from './review/index.js';\nexport * from './indexer/index.js';\nexport * from './cowork/index.js';\nexport * from './synth/index.js';\nexport * from './audit/index.js';\nexport * from './freeze/index.js';\nexport * from './invalidate/index.js';\nexport * from './section_report/index.js';\nexport * from './triage/index.js';\nexport * from './discover/index.js';\nexport {\n ResearchOSError,\n IntakeValidationError,\n PackExistsError,\n TemplateNotFoundError,\n PackNotFoundError,\n SectionExistsError,\n InvalidSectionIdError,\n SectionNotFoundError,\n NoUrlsProvidedError,\n NoSourcesGatheredError,\n HandoffNotFoundError,\n SynthesisNotReadyError,\n} from './errors.js';\n\nexport const RESEARCH_OS_VERSION = '0.3.1';\n","import { z } from 'zod';\n\n// A section report is a read-only roll-up of every research-os artifact for\n// a single section. It does not create new truth; it summarises existing\n// truth. The shape mirrors the workflow chain so a reader can follow the\n// section from gather → extract → density → contradict → review → gate\n// in one document.\n\nexport const SectionReportSourcesSchema = z.object({\n fetched_ok: z.number().int().nonnegative(),\n source_cards: z.number().int().nonnegative(),\n publishers: z.array(z.string()),\n primary_source_waiver: z.object({\n status: z.enum(['none', 'requested', 'granted']),\n reason: z.string().nullable(),\n compensating_controls: z.array(z.string()),\n }),\n});\n\nexport const SectionReportExtractionSchema = z.object({\n candidate_claims: z.number().int().nonnegative(),\n claims_per_source: z.array(\n z.object({\n source_id: z.string(),\n claims: z.number().int().nonnegative(),\n }),\n ),\n claims_per_1k_words: z.number(),\n excerpt_pages_processed: z.number().int().nonnegative().nullable(),\n excerpt_id_failures: z.number().int().nonnegative().nullable(),\n malformed_extractor_outputs: z.number().int().nonnegative().nullable(),\n near_duplicate_clusters: z.number().int().nonnegative(),\n weak_scope_count: z.number().int().nonnegative(),\n generic_scope_count: z.number().int().nonnegative(),\n density_flags: z.number().int().nonnegative(),\n});\n\nexport const SectionReportContradictionsSchema = z.object({\n pairs_compared: z.number().int().nonnegative().nullable(),\n contradiction_candidates: z.number().int().nonnegative(),\n overgeneralization_risks: z.number().int().nonnegative(),\n});\n\nexport const SectionReportReviewSchema = z.object({\n reviewed: z.boolean(),\n accepted_for_synthesis: z.number().int().nonnegative(),\n needs_scope_repair: z.number().int().nonnegative(),\n needs_source_repair: z.number().int().nonnegative(),\n needs_contradiction_mapping: z.number().int().nonnegative(),\n rejected: z.number().int().nonnegative(),\n needs_human_review: z.number().int().nonnegative(),\n rejection_or_repair_by_category: z.array(\n z.object({\n category: z.string(),\n count: z.number().int().nonnegative(),\n }),\n ),\n});\n\nexport const SectionReportAcceptanceSchema = z.object({\n candidate_claims: z.number().int().nonnegative(),\n accepted_for_synthesis: z.number().int().nonnegative(),\n acceptance_ratio: z.number(), // 0..1\n accepted_per_source: z.number(), // accepted / source_count, 0 if no sources\n accepted_per_1k_words: z.number(),\n top_rejection_category: z.string().nullable(),\n claim_overproduction_fired: z.boolean(),\n synthesis_ready: z.boolean(),\n});\n\nexport const SectionReportSchema = z.object({\n report_id: z.string().regex(/^secrep_[0-9]+_[a-z0-9-]+$/),\n section_id: z.string().regex(/^[0-9]{2}-[a-z0-9-]+$/),\n reported_at: z.string(),\n research_os_version: z.string(),\n status: z.string(),\n sources: SectionReportSourcesSchema,\n extraction: SectionReportExtractionSchema,\n contradictions: SectionReportContradictionsSchema,\n review: SectionReportReviewSchema,\n acceptance: SectionReportAcceptanceSchema,\n gate_verdict: z.string().nullable(),\n gate_synthesis_eligible: z.boolean().nullable(),\n});\n\nexport type SectionReport = z.infer<typeof SectionReportSchema>;\n","import { existsSync } from 'node:fs';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { join, resolve } from 'node:path';\nimport { parse as yamlParse } from 'yaml';\n\nimport { PackNotFoundError, SectionNotFoundError } from '../errors.js';\nimport { RESEARCH_OS_VERSION } from '../index.js';\nimport { ResearchYamlSchema } from '../intake/schema.js';\nimport {\n FetchReceiptSchema,\n SourceCardSchema,\n type FetchReceipt,\n type SourceCard,\n} from '../sources/schema.js';\nimport { ClaimSchema, type Claim } from '../claims/schema.js';\nimport { ContradictionSchema } from '../contradictions/schema.js';\nimport {\n ClaimReviewSchema,\n ReviewFindingSchema,\n type ClaimReview,\n} from '../review/schema.js';\nimport { SectionReportSchema, type SectionReport } from './schema.js';\n\nexport interface SectionReportOptions {\n sectionId: string;\n packPath?: string;\n now?: () => Date;\n}\n\nexport interface SectionReportResult {\n report: SectionReport;\n jsonPath: string;\n markdownPath: string;\n}\n\nasync function readJson<T>(path: string, parser: (raw: unknown) => T): Promise<T | null> {\n if (!existsSync(path)) return null;\n try {\n return parser(JSON.parse(await readFile(path, 'utf8')));\n } catch {\n return null;\n }\n}\n\nasync function readJsonl<T>(path: string, parse: (raw: unknown) => T): Promise<T[]> {\n if (!existsSync(path)) return [];\n const text = await readFile(path, 'utf8');\n const out: T[] = [];\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n out.push(parse(JSON.parse(line)));\n } catch {\n /* skip malformed line */\n }\n }\n return out;\n}\n\nfunction countWords(text: string | null | undefined): number {\n if (!text) return 0;\n return text\n .replace(/<[^>]+>/g, ' ')\n .replace(/\\s+/g, ' ')\n .trim()\n .split(' ')\n .filter((w) => w.length > 0).length;\n}\n\nexport async function reportSection(\n options: SectionReportOptions,\n): Promise<SectionReportResult> {\n const packPath = options.packPath ? resolve(options.packPath) : process.cwd();\n if (!existsSync(join(packPath, 'research.yaml'))) throw new PackNotFoundError(packPath);\n if (!existsSync(join(packPath, 'sections', options.sectionId)))\n throw new SectionNotFoundError(options.sectionId);\n\n const research = ResearchYamlSchema.parse(\n yamlParse(await readFile(join(packPath, 'research.yaml'), 'utf8')),\n );\n const section = research.sections.find((s) => s.id === options.sectionId);\n\n // Sources & receipts.\n const allReceipts = await readJsonl(join(packPath, 'evidence', 'fetch-log.jsonl'), (raw) =>\n FetchReceiptSchema.parse(raw),\n );\n const okReceipts = new Map<string, FetchReceipt>();\n for (const r of allReceipts) {\n if (r.section_id !== options.sectionId) continue;\n if (r.fetch_outcome !== 'ok') continue;\n const prev = okReceipts.get(r.source_id);\n if (!prev || prev.fetched_at < r.fetched_at) okReceipts.set(r.source_id, r);\n }\n const sectionSourceIds: string[] = [];\n const sourcesPath = join(packPath, 'sections', options.sectionId, 'sources.jsonl');\n if (existsSync(sourcesPath)) {\n const text = await readFile(sourcesPath, 'utf8');\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n const obj = JSON.parse(line) as { source_id?: string };\n if (obj.source_id) sectionSourceIds.push(obj.source_id);\n } catch {\n /* skip */\n }\n }\n }\n const cards = new Map<string, SourceCard>();\n for (const sid of sectionSourceIds) {\n const cardPath = join(packPath, 'evidence', 'source-cards', `${sid}.json`);\n if (!existsSync(cardPath)) continue;\n try {\n cards.set(sid, SourceCardSchema.parse(JSON.parse(await readFile(cardPath, 'utf8'))));\n } catch {\n /* skip */\n }\n }\n const publishers = Array.from(\n new Set(Array.from(cards.values()).map((c) => c.publisher).filter((p): p is string => !!p)),\n ).sort();\n\n // Total raw-text word count for this section.\n let totalWords = 0;\n for (const sid of sectionSourceIds) {\n const r = okReceipts.get(sid);\n if (!r?.raw_text_path) continue;\n const p = join(packPath, r.raw_text_path);\n if (!existsSync(p)) continue;\n totalWords += countWords(await readFile(p, 'utf8'));\n }\n\n // Claims.\n const claims = await readJsonl(\n join(packPath, 'sections', options.sectionId, 'claims.jsonl'),\n (raw) => ClaimSchema.parse(raw),\n );\n const claimsBySrc = new Map<string, Claim[]>();\n for (const c of claims) {\n for (const sid of c.source_ids) {\n const arr = claimsBySrc.get(sid) ?? [];\n arr.push(c);\n claimsBySrc.set(sid, arr);\n }\n }\n\n // Density audit (if it exists).\n const density = await readJson(\n join(packPath, 'audits', `${options.sectionId}-claim-density.json`),\n (raw) => raw as Record<string, unknown>,\n );\n\n // Extract receipt (if it exists).\n const extractReceipt = await readJson(\n join(packPath, 'audits', `${options.sectionId}-claim-extract.json`),\n (raw) => raw as Record<string, unknown>,\n );\n\n // Excerpt ledgers (so we can count pages even without an extract receipt).\n let excerptPagesProcessed: number | null = null;\n if (extractReceipt && typeof extractReceipt.excerpt_ledgers_built === 'number') {\n excerptPagesProcessed = extractReceipt.excerpt_ledgers_built as number;\n }\n let excerptIdFailures: number | null = null;\n if (extractReceipt && typeof extractReceipt.claims_rejected_excerpt_id_missing === 'number') {\n excerptIdFailures =\n (extractReceipt.claims_rejected_excerpt_id_missing as number) +\n ((extractReceipt.claims_rejected_excerpt_id_malformed as number) ?? 0);\n }\n let malformedOutputs: number | null = null;\n if (extractReceipt && Array.isArray(extractReceipt.failures)) {\n malformedOutputs = (extractReceipt.failures as Array<{ kind?: string }>).filter(\n (f) => f.kind === 'extractor_invalid_json',\n ).length;\n }\n\n // Contradictions.\n const contradictions = await readJsonl(\n join(packPath, 'sections', options.sectionId, 'contradictions.jsonl'),\n (raw) => ContradictionSchema.parse(raw),\n );\n let pairsCompared: number | null = null;\n if (claims.length > 1) pairsCompared = (claims.length * (claims.length - 1)) / 2;\n const overgeneralizationRisks = contradictions.filter(\n (c) => c.type === 'overgeneralization_risk',\n ).length;\n\n // Review.\n const reviews = await readJsonl(\n join(packPath, 'sections', options.sectionId, 'claim-reviews.jsonl'),\n (raw) => ClaimReviewSchema.parse(raw),\n );\n // For each claim, take the LATEST review (append-only ledger).\n const latestReviewByClaim = new Map<string, ClaimReview>();\n for (const r of reviews) {\n const prev = latestReviewByClaim.get(r.claim_id);\n if (!prev || prev.created_at < r.created_at) latestReviewByClaim.set(r.claim_id, r);\n }\n const findings = await readJsonl(\n join(packPath, 'audits', `${options.sectionId}-findings.jsonl`),\n (raw) => ReviewFindingSchema.parse(raw),\n );\n\n const decisionCounts = {\n accepted_for_synthesis: 0,\n needs_scope_repair: 0,\n needs_source_repair: 0,\n needs_contradiction_mapping: 0,\n rejected: 0,\n needs_human_review: 0,\n };\n for (const claim of claims) {\n const r = latestReviewByClaim.get(claim.claim_id);\n if (!r) continue;\n decisionCounts[r.decision] += 1;\n }\n // Tally finding categories that produced non-accept decisions.\n const categoryCounts = new Map<string, number>();\n for (const f of findings) {\n if (f.severity === 'info') continue;\n categoryCounts.set(f.category, (categoryCounts.get(f.category) ?? 0) + 1);\n }\n const rejectionByCategory = Array.from(categoryCounts.entries())\n .map(([category, count]) => ({ category, count }))\n .sort((a, b) => b.count - a.count);\n const topRejectionCategory = rejectionByCategory[0]?.category ?? null;\n const claimOverproductionFired = (categoryCounts.get('claim_overproduction') ?? 0) > 0;\n\n // Gate verdict.\n const gate = await readJson(\n join(packPath, 'audits', `${options.sectionId}-gate.json`),\n (raw) => raw as Record<string, unknown>,\n );\n\n const candidate = claims.length;\n const accepted = decisionCounts.accepted_for_synthesis;\n const acceptanceRatio = candidate > 0 ? accepted / candidate : 0;\n const acceptedPerSource = sectionSourceIds.length > 0 ? accepted / sectionSourceIds.length : 0;\n const acceptedPer1kWords = totalWords > 0 ? (accepted / totalWords) * 1000 : 0;\n const synthesisReady =\n typeof gate?.synthesis_eligible === 'boolean' ? gate.synthesis_eligible : false;\n\n const stamp = (options.now ?? (() => new Date()))();\n\n const report: SectionReport = SectionReportSchema.parse({\n report_id: `secrep_${stamp.getTime()}_${options.sectionId}`,\n section_id: options.sectionId,\n reported_at: stamp.toISOString(),\n research_os_version: RESEARCH_OS_VERSION,\n status: section?.status ?? 'unknown',\n sources: {\n fetched_ok: okReceipts.size,\n source_cards: cards.size,\n publishers,\n primary_source_waiver: {\n status: research.primary_source_waiver.status,\n reason: research.primary_source_waiver.reason ?? null,\n compensating_controls: research.primary_source_waiver.compensating_controls,\n },\n },\n extraction: {\n candidate_claims: candidate,\n claims_per_source: Array.from(claimsBySrc.entries())\n .map(([source_id, cs]) => ({ source_id, claims: cs.length }))\n .sort((a, b) => b.claims - a.claims),\n claims_per_1k_words: totalWords > 0 ? (candidate / totalWords) * 1000 : 0,\n excerpt_pages_processed: excerptPagesProcessed,\n excerpt_id_failures: excerptIdFailures,\n malformed_extractor_outputs: malformedOutputs,\n near_duplicate_clusters:\n density && Array.isArray((density as { near_duplicate_clusters?: unknown[] }).near_duplicate_clusters)\n ? ((density as { near_duplicate_clusters: unknown[] }).near_duplicate_clusters).length\n : 0,\n weak_scope_count:\n density && typeof (density as { weak_scope_count?: number }).weak_scope_count === 'number'\n ? ((density as { weak_scope_count: number }).weak_scope_count)\n : 0,\n generic_scope_count:\n density && typeof (density as { generic_scope_count?: number }).generic_scope_count === 'number'\n ? ((density as { generic_scope_count: number }).generic_scope_count)\n : 0,\n density_flags:\n density && Array.isArray((density as { flags?: unknown[] }).flags)\n ? ((density as { flags: unknown[] }).flags).length\n : 0,\n },\n contradictions: {\n pairs_compared: pairsCompared,\n contradiction_candidates: contradictions.length,\n overgeneralization_risks: overgeneralizationRisks,\n },\n review: {\n reviewed: latestReviewByClaim.size > 0,\n accepted_for_synthesis: decisionCounts.accepted_for_synthesis,\n needs_scope_repair: decisionCounts.needs_scope_repair,\n needs_source_repair: decisionCounts.needs_source_repair,\n needs_contradiction_mapping: decisionCounts.needs_contradiction_mapping,\n rejected: decisionCounts.rejected,\n needs_human_review: decisionCounts.needs_human_review,\n rejection_or_repair_by_category: rejectionByCategory,\n },\n acceptance: {\n candidate_claims: candidate,\n accepted_for_synthesis: accepted,\n acceptance_ratio: acceptanceRatio,\n accepted_per_source: acceptedPerSource,\n accepted_per_1k_words: acceptedPer1kWords,\n top_rejection_category: topRejectionCategory,\n claim_overproduction_fired: claimOverproductionFired,\n synthesis_ready: synthesisReady,\n },\n gate_verdict: typeof gate?.verdict === 'string' ? (gate.verdict as string) : null,\n gate_synthesis_eligible:\n typeof gate?.synthesis_eligible === 'boolean'\n ? (gate.synthesis_eligible as boolean)\n : null,\n });\n\n // Markdown render — exact shape from the user's spec.\n const md: string[] = [];\n md.push(`# Section ${report.section_id}`);\n md.push('');\n md.push(`- **Status:** ${report.status}`);\n md.push(`- **Reported at:** ${report.reported_at}`);\n md.push(`- **Report ID:** \\`${report.report_id}\\``);\n md.push('');\n md.push('## Sources');\n md.push('');\n md.push(`- fetched: ${report.sources.fetched_ok}`);\n md.push(`- source cards: ${report.sources.source_cards}`);\n md.push(`- publishers: ${report.sources.publishers.length === 0 ? '(none)' : report.sources.publishers.join(', ')}`);\n md.push(`- primary-source waiver: ${report.sources.primary_source_waiver.status}${report.sources.primary_source_waiver.reason ? ` — ${report.sources.primary_source_waiver.reason.slice(0, 200)}` : ''}`);\n md.push('');\n md.push('## Extraction');\n md.push('');\n md.push(`- candidate claims: ${report.extraction.candidate_claims}`);\n md.push(`- claims per source: ${report.extraction.claims_per_source.map((s) => `${s.source_id}=${s.claims}`).join(', ') || '(none)'}`);\n md.push(`- claims per 1k words: ${report.extraction.claims_per_1k_words.toFixed(2)}`);\n md.push(`- excerpt pages processed: ${report.extraction.excerpt_pages_processed ?? 'n/a'}`);\n md.push(`- excerpt-id failures: ${report.extraction.excerpt_id_failures ?? 'n/a'}`);\n md.push(`- malformed extractor outputs: ${report.extraction.malformed_extractor_outputs ?? 'n/a'}`);\n md.push(`- duplicate / near-duplicate clusters: ${report.extraction.near_duplicate_clusters}`);\n md.push(`- weak-scope claims: ${report.extraction.weak_scope_count}`);\n md.push(`- generic-scope claims: ${report.extraction.generic_scope_count}`);\n md.push(`- density flags: ${report.extraction.density_flags}`);\n md.push('');\n md.push('## Contradictions');\n md.push('');\n md.push(`- pairs compared: ${report.contradictions.pairs_compared ?? 'n/a'}`);\n md.push(`- contradiction candidates: ${report.contradictions.contradiction_candidates}`);\n md.push(`- overgeneralization risks: ${report.contradictions.overgeneralization_risks}`);\n md.push('');\n md.push('## Review');\n md.push('');\n if (!report.review.reviewed) {\n md.push('_Review has not run for this section yet._');\n } else {\n md.push(`- accepted_for_synthesis: ${report.review.accepted_for_synthesis}`);\n md.push(`- needs_scope_repair: ${report.review.needs_scope_repair}`);\n md.push(`- needs_source_repair: ${report.review.needs_source_repair}`);\n md.push(`- rejected: ${report.review.rejected}`);\n md.push(`- needs_human_review: ${report.review.needs_human_review}`);\n md.push(`- needs_contradiction_mapping: ${report.review.needs_contradiction_mapping}`);\n md.push('');\n md.push('### Rejection / repair by category');\n md.push('');\n if (report.review.rejection_or_repair_by_category.length === 0) {\n md.push('_No non-info findings recorded._');\n } else {\n md.push('| Category | Count |');\n md.push('|---|---:|');\n for (const r of report.review.rejection_or_repair_by_category) {\n md.push(`| \\`${r.category}\\` | ${r.count} |`);\n }\n }\n }\n md.push('');\n md.push('## Acceptance');\n md.push('');\n md.push(`- acceptance ratio: ${(report.acceptance.acceptance_ratio * 100).toFixed(1)}% (${report.acceptance.accepted_for_synthesis} / ${report.acceptance.candidate_claims})`);\n md.push(`- accepted per source: ${report.acceptance.accepted_per_source.toFixed(2)}`);\n md.push(`- accepted per 1k source words: ${report.acceptance.accepted_per_1k_words.toFixed(2)}`);\n md.push(`- top rejection category: ${report.acceptance.top_rejection_category ?? 'none'}`);\n md.push(`- claim_overproduction fired: ${report.acceptance.claim_overproduction_fired ? 'yes' : 'no'}`);\n md.push(`- synthesis ready: ${report.acceptance.synthesis_ready ? 'yes' : 'no'}`);\n md.push('');\n md.push('---');\n md.push('');\n md.push('_This report is read-only — it does not mutate any canonical artifact. Re-run after any pipeline step to refresh._');\n\n const auditsDir = join(packPath, 'audits');\n await mkdir(auditsDir, { recursive: true });\n const jsonPath = join(auditsDir, `${options.sectionId}-section-report.json`);\n const markdownPath = join(auditsDir, `${options.sectionId}-section-report.md`);\n await writeFile(jsonPath, JSON.stringify(report, null, 2), 'utf8');\n await writeFile(markdownPath, md.join('\\n'), 'utf8');\n return { report, jsonPath, markdownPath };\n}\n","export { reportSection, type SectionReportOptions, type SectionReportResult } from './run.js';\nexport {\n SectionReportSchema,\n SectionReportSourcesSchema,\n SectionReportExtractionSchema,\n SectionReportContradictionsSchema,\n SectionReportReviewSchema,\n SectionReportAcceptanceSchema,\n type SectionReport,\n} from './schema.js';\n","#!/usr/bin/env node\nimport { Command, Option } from 'commander';\nimport { init } from './intake/index.js';\nimport { add as sectionAdd } from './sections/index.js';\nimport { reportSection } from './section_report/index.js';\nimport { gather } from './sources/index.js';\nimport {\n discover as runDiscover,\n approve as discoverApprove,\n reject as discoverReject,\n exportUrls as discoverExport,\n} from './discover/index.js';\nimport { auditDensity, extract as claimExtract } from './claims/index.js';\nimport { triage as runTriage } from './triage/index.js';\nimport { map as contradictMap, resolve as contradictResolve } from './contradictions/index.js';\nimport { gate as runGate } from './gates/index.js';\nimport {\n DEFAULT_PROFILE,\n HeuristicReviewer,\n OllamaInternReviewer,\n promote as runPromote,\n review as runReview,\n} from './review/index.js';\nimport {\n build as indexBuild,\n query as indexQuery,\n exportRepoKnowledge,\n syncRepoKnowledge,\n} from './indexer/index.js';\nimport { handoff as coworkHandoff } from './cowork/index.js';\nimport { workspace as synthWorkspace } from './synth/index.js';\nimport { audit as runAudit } from './audit/index.js';\nimport { freeze as runFreeze } from './freeze/index.js';\nimport { invalidateExtraction, invalidateReview } from './invalidate/index.js';\nimport { publish as packPublish } from './pack/publish/index.js';\nimport { ResearchOSError } from './errors.js';\nimport { RESEARCH_OS_VERSION } from './index.js';\n\nfunction reportError(err: unknown): never {\n if (err instanceof ResearchOSError) {\n process.stderr.write(`research-os: ${err.code}: ${err.message}\\n`);\n if (err.hint) process.stderr.write(` hint: ${err.hint}\\n`);\n } else if (err instanceof Error) {\n process.stderr.write(`research-os: ${err.message}\\n`);\n } else {\n process.stderr.write(`research-os: unknown error\\n`);\n }\n process.exit(1);\n}\n\nconst program = new Command();\n\nprogram\n .name('research-os')\n .description('Local-first research control plane for gated source packs and long-running AI synthesis')\n .version(RESEARCH_OS_VERSION);\n\nprogram\n .command('init')\n .description('Create a new research-pack from a topic')\n .argument('<topic>', 'The research question or topic statement')\n .option('-n, --name <slug>', 'Pack directory name (defaults to a slug of the topic)')\n .option('-o, --out <dir>', 'Parent directory in which to create the pack', process.cwd())\n .option('-d, --decision <text>', 'What decision this research informs')\n .option('-a, --audience <text>', 'Who consumes the output', 'self')\n .option('--desired-output <text>', 'Shape of the final artifact')\n .option('--max-runtime-minutes <n>', 'Total runtime budget for the pack', (v) => parseInt(v, 10), 240)\n .option('--force', 'Overwrite an existing pack directory')\n .action(async (topic: string, opts) => {\n try {\n const result = await init({\n topic,\n name: opts.name,\n outDir: opts.out,\n decision: opts.decision,\n audience: opts.audience,\n desiredOutput: opts.desiredOutput,\n maxRuntimeMinutes: opts.maxRuntimeMinutes,\n force: opts.force,\n });\n process.stdout.write(`research-pack created\\n`);\n process.stdout.write(` name: ${result.packName}\\n`);\n process.stdout.write(` path: ${result.packPath}\\n`);\n process.stdout.write(` files: ${result.filesWritten.length}\\n`);\n } catch (err) {\n reportError(err);\n }\n });\n\nconst sectionCmd = program\n .command('section')\n .description('Manage sections inside a research-pack');\n\nsectionCmd\n .command('add')\n .description('Add a new section to the pack')\n .argument('<id>', 'Section id, e.g. \"01-landscape\"')\n .requiredOption('--purpose <text>', 'What this section investigates')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .option('--max-time <n>', 'Section time budget in minutes', (v) => parseInt(v, 10))\n .option('--min-sources <n>', 'Minimum sources required for this section', (v) => parseInt(v, 10))\n .option('--primary-required <n>', 'Primary sources required for this section', (v) => parseInt(v, 10))\n .action(async (id: string, opts) => {\n try {\n const result = await sectionAdd({\n id,\n purpose: opts.purpose,\n packPath: opts.pack,\n maxTimeMinutes: opts.maxTime,\n minSources: opts.minSources,\n primarySourcesRequired: opts.primaryRequired,\n });\n process.stdout.write(`section added\\n`);\n process.stdout.write(` id: ${result.sectionId}\\n`);\n process.stdout.write(` path: ${result.sectionPath}\\n`);\n process.stdout.write(` files: ${result.filesWritten.length}\\n`);\n } catch (err) {\n reportError(err);\n }\n });\n\nsectionCmd\n .command('report')\n .description(\n 'Read-only section roll-up: sources, extraction, contradictions, review, acceptance ratio',\n )\n .argument('<section>', 'Section id, e.g. \"03-source-and-claim-truth\"')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .action(async (section: string, opts) => {\n try {\n const { report, jsonPath, markdownPath } = await reportSection({\n sectionId: section,\n packPath: opts.pack,\n });\n process.stdout.write(`section report: ${report.section_id}\\n`);\n process.stdout.write(` status: ${report.status}\\n`);\n process.stdout.write(`Sources\\n`);\n process.stdout.write(` fetched: ${report.sources.fetched_ok}\\n`);\n process.stdout.write(` source cards: ${report.sources.source_cards}\\n`);\n process.stdout.write(` publishers: ${report.sources.publishers.length}\\n`);\n process.stdout.write(` primary-source waiver: ${report.sources.primary_source_waiver.status}\\n`);\n process.stdout.write(`Extraction\\n`);\n process.stdout.write(` candidate claims: ${report.extraction.candidate_claims}\\n`);\n process.stdout.write(` claims per 1k words: ${report.extraction.claims_per_1k_words.toFixed(2)}\\n`);\n process.stdout.write(` excerpt pages processed: ${report.extraction.excerpt_pages_processed ?? 'n/a'}\\n`);\n process.stdout.write(` excerpt-id failures: ${report.extraction.excerpt_id_failures ?? 'n/a'}\\n`);\n process.stdout.write(` malformed extractor: ${report.extraction.malformed_extractor_outputs ?? 'n/a'}\\n`);\n process.stdout.write(` near-duplicate clusters: ${report.extraction.near_duplicate_clusters}\\n`);\n process.stdout.write(`Contradictions\\n`);\n process.stdout.write(` pairs compared: ${report.contradictions.pairs_compared ?? 'n/a'}\\n`);\n process.stdout.write(` contradiction candidates: ${report.contradictions.contradiction_candidates}\\n`);\n process.stdout.write(` overgeneralization risks: ${report.contradictions.overgeneralization_risks}\\n`);\n process.stdout.write(`Review\\n`);\n if (!report.review.reviewed) {\n process.stdout.write(` (not reviewed yet)\\n`);\n } else {\n process.stdout.write(` accepted_for_synthesis: ${report.review.accepted_for_synthesis}\\n`);\n process.stdout.write(` needs_scope_repair: ${report.review.needs_scope_repair}\\n`);\n process.stdout.write(` needs_source_repair: ${report.review.needs_source_repair}\\n`);\n process.stdout.write(` rejected: ${report.review.rejected}\\n`);\n process.stdout.write(` needs_human_review: ${report.review.needs_human_review}\\n`);\n }\n process.stdout.write(`Acceptance\\n`);\n process.stdout.write(` ratio: ${(report.acceptance.acceptance_ratio * 100).toFixed(1)}% (${report.acceptance.accepted_for_synthesis} / ${report.acceptance.candidate_claims})\\n`);\n process.stdout.write(` accepted per source: ${report.acceptance.accepted_per_source.toFixed(2)}\\n`);\n process.stdout.write(` accepted per 1k words: ${report.acceptance.accepted_per_1k_words.toFixed(2)}\\n`);\n process.stdout.write(` top rejection category: ${report.acceptance.top_rejection_category ?? 'none'}\\n`);\n process.stdout.write(` claim_overproduction: ${report.acceptance.claim_overproduction_fired ? 'yes' : 'no'}\\n`);\n process.stdout.write(` synthesis ready: ${report.acceptance.synthesis_ready ? 'yes' : 'no'}\\n`);\n process.stdout.write(` json: ${jsonPath}\\n`);\n process.stdout.write(` markdown: ${markdownPath}\\n`);\n } catch (err) {\n reportError(err);\n }\n });\n\nprogram\n .command('gather')\n .description('Acquire known sources for a section: direct fetch + extraction')\n .argument('<section>', 'Section id, e.g. \"01-landscape\"')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .option('--url <url>', 'A URL to fetch (repeatable)', (value: string, prev: string[] = []) => {\n prev.push(value);\n return prev;\n })\n .option('--urls-file <path>', 'File of URLs, one per line; blank lines and # comments allowed')\n .option(\n '--approved',\n 'Read URLs from sections/<id>/urls.approved.txt (produced by `research-os discover approve` / `discover export-urls`)',\n false,\n )\n .action(async (section: string, opts) => {\n try {\n let urlsFile = opts.urlsFile as string | undefined;\n if (opts.approved) {\n const path = await import('node:path');\n const candidate = path.join(opts.pack as string, 'sections', section, 'urls.approved.txt');\n urlsFile = urlsFile ?? candidate;\n }\n const result = await gather({\n sectionId: section,\n packPath: opts.pack,\n urls: opts.url,\n urlsFile,\n });\n process.stdout.write(`gather complete\\n`);\n process.stdout.write(` section: ${result.sectionId}\\n`);\n process.stdout.write(` attempted: ${result.attempted}\\n`);\n process.stdout.write(` fetched ok: ${result.fetchedOk}\\n`);\n process.stdout.write(` fetched failed: ${result.fetchedFailed}\\n`);\n process.stdout.write(` extracted ok: ${result.extractedOk}\\n`);\n process.stdout.write(` extracted failed: ${result.extractedFailed}\\n`);\n process.stdout.write(` cards written: ${result.cardsWritten}\\n`);\n process.stdout.write(` receipts appended: ${result.receiptsAppended}\\n`);\n } catch (err) {\n reportError(err);\n }\n });\n\nconst discoverCmd = program\n .command('discover')\n .description(\n 'Propose source URL candidates for a section. Discovery results are LEADS, not evidence — only fetch + receipt + source card make a URL evidence.',\n );\n\ndiscoverCmd\n .command('run')\n .description('Run a discover query against a section, append candidates to the ledger, render report')\n .argument('<section>', 'Section id, e.g. \"04-gates-and-waivers\"')\n .requiredOption('--query <text>', 'Free-text query to ask the discover provider')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .option('--target <n>', 'Soft target candidate count', (v) => parseInt(v, 10), 12)\n .action(async (section: string, opts) => {\n try {\n const result = await runDiscover({\n sectionId: section,\n packPath: opts.pack,\n query: opts.query,\n targetCount: opts.target,\n });\n process.stdout.write(`discover complete\\n`);\n process.stdout.write(` section: ${section}\\n`);\n process.stdout.write(` candidates proposed: ${result.candidatesProposed}\\n`);\n process.stdout.write(` candidates added: ${result.candidatesAdded}\\n`);\n process.stdout.write(` invalid url rejected: ${result.candidatesRejectedInvalidUrl}\\n`);\n process.stdout.write(` candidates ledger: ${result.candidatesPath}\\n`);\n process.stdout.write(` report: ${result.reportPath}\\n`);\n process.stdout.write(` summary: ${result.summaryPath}\\n`);\n if (result.warnings.length > 0) {\n process.stdout.write(`\\nwarnings:\\n`);\n for (const w of result.warnings) process.stdout.write(` - ${w}\\n`);\n }\n } catch (err) {\n reportError(err);\n }\n });\n\ndiscoverCmd\n .command('approve')\n .description('Approve discovered candidates so gather --approved will fetch them')\n .argument('<section>', 'Section id')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .option(\n '--candidate <id>',\n 'Candidate id (repeatable)',\n (v: string, prev: string[] = []) => {\n prev.push(v);\n return prev;\n },\n )\n .option('--top <n>', 'Approve the top N candidates by rank', (v) => parseInt(v, 10))\n .option('--reason <text>', 'Optional reason recorded on the status update')\n .action(async (section: string, opts) => {\n try {\n const result = await discoverApprove({\n sectionId: section,\n packPath: opts.pack,\n candidateIds: opts.candidate,\n topN: opts.top,\n reason: opts.reason,\n });\n process.stdout.write(`discover approve\\n`);\n process.stdout.write(` approved: ${result.approved}\\n`);\n for (const id of result.approvedIds) process.stdout.write(` - ${id}\\n`);\n process.stdout.write(` exported: ${result.exportPath}\\n`);\n } catch (err) {\n reportError(err);\n }\n });\n\ndiscoverCmd\n .command('reject')\n .description('Reject discovered candidates with a recorded reason')\n .argument('<section>', 'Section id')\n .requiredOption(\n '--candidate <id>',\n 'Candidate id (repeatable)',\n (v: string, prev: string[] = []) => {\n prev.push(v);\n return prev;\n },\n )\n .requiredOption('--reason <text>', 'Reason recorded on the status update')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .action(async (section: string, opts) => {\n try {\n const result = await discoverReject({\n sectionId: section,\n packPath: opts.pack,\n candidateIds: opts.candidate,\n reason: opts.reason,\n });\n process.stdout.write(`discover reject\\n`);\n process.stdout.write(` rejected: ${result.rejected}\\n`);\n for (const id of result.rejectedIds) process.stdout.write(` - ${id}\\n`);\n } catch (err) {\n reportError(err);\n }\n });\n\ndiscoverCmd\n .command('export-urls')\n .description('Re-export sections/<id>/urls.approved.txt from the latest approved candidates')\n .argument('<section>', 'Section id')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .action(async (section: string, opts) => {\n try {\n const result = await discoverExport({\n sectionId: section,\n packPath: opts.pack,\n });\n process.stdout.write(`discover export-urls\\n`);\n process.stdout.write(` approved count: ${result.approvedCount}\\n`);\n process.stdout.write(` export path: ${result.exportPath}\\n`);\n } catch (err) {\n reportError(err);\n }\n });\n\nconst claimCmd = program\n .command('claim')\n .description('Manage claims extracted from gathered sources');\n\nclaimCmd\n .command('extract')\n .description('Extract candidate claims from a section\\'s gathered sources')\n .argument('<section>', 'Section id, e.g. \"01-landscape\"')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .action(async (section: string, opts) => {\n try {\n const result = await claimExtract({\n sectionId: section,\n packPath: opts.pack,\n });\n process.stdout.write(`claim extraction complete\\n`);\n process.stdout.write(` section: ${result.sectionId}\\n`);\n process.stdout.write(` extractor: ${result.extractor}\\n`);\n process.stdout.write(` method: ${result.extractionMethod}\\n`);\n process.stdout.write(` sources processed: ${result.sourcesProcessed}\\n`);\n process.stdout.write(` sources skipped: ${result.sourcesSkipped}\\n`);\n process.stdout.write(` sources failed: ${result.sourcesFailed}\\n`);\n process.stdout.write(` excerpt ledgers built: ${result.excerptLedgersBuilt}\\n`);\n process.stdout.write(` claims added: ${result.claimsAdded}\\n`);\n process.stdout.write(` claims deduped: ${result.claimsDeduped}\\n`);\n process.stdout.write(` claims rejected (total ungrounded): ${result.claimsRejectedUngrounded}\\n`);\n // Span-first taxonomy: precise rejection categories. Others\n // (unsupported_claim / scope_missing / scope_widening / cross_source_contam)\n // are reviewer concerns and surface in the review step, not here.\n process.stdout.write(` excerpt_id_missing: ${result.claimsRejectedExcerptIdMissing}\\n`);\n process.stdout.write(` excerpt_id_malformed: ${result.claimsRejectedExcerptIdMalformed}\\n`);\n if (result.failures.length > 0) {\n process.stdout.write(`\\nfailures:\\n`);\n for (const f of result.failures) {\n // Annotate JSON-parse failures so they're visibly distinct from\n // network/transport errors.\n const tag = /not valid JSON/i.test(f.reason) ? '[extractor_invalid_json] ' : '';\n process.stdout.write(` ${f.source_id}: ${tag}${f.reason}\\n`);\n }\n }\n } catch (err) {\n reportError(err);\n }\n });\n\nclaimCmd\n .command('triage')\n .description(\n 'Shape candidate claims before review: dedupe, cap per-source contribution, park weak-scope/low-value claims. Read-only on claims.jsonl.',\n )\n .argument('<section>', 'Section id, e.g. \"03-source-and-claim-truth\"')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .option('--per-source-cap <n>', 'Max claims per source forwarded to review', (v) => parseInt(v, 10), 10)\n .option('--min-assert-chars <n>', 'Asserts shorter than this become parked_low_value', (v) => parseInt(v, 10), 30)\n .action(async (section: string, opts) => {\n try {\n const result = await runTriage({\n sectionId: section,\n packPath: opts.pack,\n perSourceCap: opts.perSourceCap,\n minAssertChars: opts.minAssertChars,\n });\n process.stdout.write(`claim triage complete\\n`);\n process.stdout.write(` section: ${section}\\n`);\n process.stdout.write(` candidate claims: ${result.candidateClaims}\\n`);\n process.stdout.write(` selected_for_review: ${result.selectedCount}\\n`);\n process.stdout.write(` parked (total): ${result.parkedCount}\\n`);\n process.stdout.write(` needs_repair (total): ${result.needsRepairCount}\\n`);\n process.stdout.write(`\\ndecisions:\\n`);\n for (const [d, n] of Object.entries(result.decisions)) {\n process.stdout.write(` ${d}: ${n}\\n`);\n }\n process.stdout.write(`\\n triage jsonl: ${result.triageJsonlPath}\\n`);\n process.stdout.write(` triage markdown: ${result.triageMarkdownPath}\\n`);\n process.stdout.write(` summary json: ${result.summaryJsonPath}\\n`);\n } catch (err) {\n reportError(err);\n }\n });\n\nclaimCmd\n .command('audit-density')\n .description(\n 'Read-only diagnostic of a section claim ledger before review: claims/source, claims per 1k words, near-duplicate clusters, weak/generic scope',\n )\n .argument('<section>', 'Section id, e.g. \"03-source-and-claim-truth\"')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .action(async (section: string, opts) => {\n try {\n const result = await auditDensity({\n sectionId: section,\n packPath: opts.pack,\n });\n const a = result.audit;\n process.stdout.write(`claim density audit complete\\n`);\n process.stdout.write(` section: ${a.section_id}\\n`);\n process.stdout.write(` candidate claims: ${a.candidate_claim_count}\\n`);\n process.stdout.write(` sources: ${a.source_count}\\n`);\n process.stdout.write(` source word total: ${a.total_source_word_count.toLocaleString()}\\n`);\n process.stdout.write(` claims per 1k words: ${a.claims_per_1k_words.toFixed(2)}\\n`);\n process.stdout.write(` weak-scope claims: ${a.weak_scope_count}\\n`);\n process.stdout.write(` generic-scope claims: ${a.generic_scope_count}\\n`);\n process.stdout.write(` near-duplicate clusters:${a.near_duplicate_clusters.length}\\n`);\n process.stdout.write(` flags: ${a.flags.length}\\n`);\n for (const f of a.flags) {\n process.stdout.write(` [${f.severity}] ${f.type}: ${f.message}\\n`);\n }\n process.stdout.write(` json: ${result.jsonPath}\\n`);\n process.stdout.write(` markdown: ${result.markdownPath}\\n`);\n } catch (err) {\n reportError(err);\n }\n });\n\nconst contradictCmd = program\n .command('contradict')\n .description('Map tensions between candidate claims');\n\ncontradictCmd\n .command('map')\n .description('Detect contradiction candidates among a section\\'s candidate claims')\n .argument('<section>', 'Section id, e.g. \"01-landscape\"')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .option(\n '--triaged-only',\n 'Only consider claims that triage selected_for_review; reduces N² pair classification on dense sections',\n false,\n )\n .addOption(\n new Option(\n '--detector <mode>',\n 'Detector to use: auto (default, env-var-driven), heuristic (always fast, no LLM), ollama-intern (require LLM, fail visibly if unavailable)',\n )\n .choices(['auto', 'heuristic', 'ollama-intern'])\n .default('auto'),\n )\n .action(async (section: string, opts) => {\n try {\n const result = await contradictMap({\n sectionId: section,\n packPath: opts.pack,\n triagedOnly: opts.triagedOnly,\n detectorMode: opts.detector,\n });\n process.stdout.write(`${result.detectorAnnouncement}\\n`);\n process.stdout.write(`contradiction map complete\\n`);\n process.stdout.write(` section: ${result.sectionId}\\n`);\n process.stdout.write(` detector: ${result.detector}\\n`);\n process.stdout.write(` method: ${result.detectionMethod}\\n`);\n process.stdout.write(` candidate claims: ${result.candidateClaims}\\n`);\n process.stdout.write(` pairs compared: ${result.pairsCompared}\\n`);\n process.stdout.write(` contradictions added: ${result.contradictionsAdded}\\n`);\n process.stdout.write(` contradictions deduped: ${result.contradictionsDeduped}\\n`);\n if (result.detectorError) {\n process.stdout.write(`\\ndetector error: ${result.detectorError}\\n`);\n }\n } catch (err) {\n reportError(err);\n }\n });\n\ncontradictCmd\n .command('resolve')\n .description('Record resolution status for contradiction candidates in a section')\n .argument('<section>', 'Section id, e.g. \"08-acceptance-suite\"')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .option(\n '--id <id>',\n 'Contradiction ID to resolve (repeatable)',\n (v: string, prev: string[] = []) => { prev.push(v); return prev; },\n )\n .option('--all', 'Resolve all currently-unresolved contradictions in the section', false)\n .requiredOption('--status <status>', 'Resolution status: resolved, preserved, or rejected')\n .requiredOption('--reason <text>', 'Reason for this resolution (min 4 chars)')\n .option('--by <identifier>', 'Who resolved it (recorded in ledger)', 'operator')\n .action(async (section: string, opts) => {\n try {\n if (!opts.all && (!opts.id || opts.id.length === 0)) {\n process.stderr.write('research-os: must provide --id <id> (repeatable) or --all\\n');\n process.exit(1);\n }\n if (opts.status === 'unresolved') {\n process.stderr.write('research-os: --status unresolved is the default; use resolved, preserved, or rejected\\n');\n process.exit(1);\n }\n const result = await contradictResolve({\n sectionId: section,\n packPath: opts.pack,\n contradictionIds: opts.id,\n all: opts.all,\n status: opts.status,\n reason: opts.reason,\n resolvedBy: opts.by,\n });\n process.stdout.write(`contradict resolve complete\\n`);\n process.stdout.write(` section: ${result.sectionId}\\n`);\n process.stdout.write(` applied: ${result.applied}\\n`);\n process.stdout.write(` skipped: ${result.skipped}\\n`);\n process.stdout.write(` ledger: ${result.ledgerPath}\\n`);\n } catch (err) {\n reportError(err);\n }\n });\n\nprogram\n .command('gate')\n .description('Run the section gate engine and emit a structured verdict')\n .argument('<section>', 'Section id, e.g. \"01-landscape\"')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .action(async (section: string, opts) => {\n try {\n const result = await runGate({\n sectionId: section,\n packPath: opts.pack,\n });\n process.stdout.write(`gate verdict: ${result.verdict.toUpperCase()}\\n`);\n process.stdout.write(` section: ${result.section_id}\\n`);\n process.stdout.write(` synthesis eligible: ${result.synthesis_eligible}\\n`);\n process.stdout.write(` failures: ${result.failures.length}\\n`);\n process.stdout.write(` warnings: ${result.warnings.length}\\n`);\n process.stdout.write(` waivers applied: ${result.waivers_applied.length}\\n`);\n process.stdout.write(` blocking reasons: ${result.blocking_reasons.length}\\n`);\n if (result.blocking_reasons.length > 0) {\n process.stdout.write(`\\nblocking:\\n`);\n for (const r of result.blocking_reasons) {\n process.stdout.write(` - ${r}\\n`);\n }\n }\n if (result.next_actions.length > 0) {\n process.stdout.write(`\\nnext actions:\\n`);\n for (const a of result.next_actions) {\n process.stdout.write(` - ${a}\\n`);\n }\n }\n if (!result.synthesis_eligible) process.exitCode = 2;\n } catch (err) {\n reportError(err);\n }\n });\n\nprogram\n .command('review')\n .description('Run the adversarial reviewer pass; emits findings + claim review decisions')\n .argument('<section>', 'Section id, e.g. \"01-landscape\"')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .option(\n '--heuristic-only',\n 'Skip the LLM reviewer; run only the deterministic HeuristicReviewer',\n false,\n )\n .option(\n '--triaged-only',\n 'Only review claims that triage selected_for_review',\n false,\n )\n .option(\n '--llm-paged',\n 'Force the LLM reviewer (paged windows) — alias for the default ladder when ollama is up. Useful as documentation of intent.',\n false,\n )\n .option(\n '--review-window <n>',\n 'Claims per LLM review window (default 30). Smaller windows fit smaller models.',\n (v) => parseInt(v, 10),\n )\n .option(\n '--two-pass-llm',\n 'Two-pass LLM review: general + narrow_critic + heuristic. Findings merged.',\n false,\n )\n .option(\n '--model <name>',\n 'Override OLLAMA_INTERN_MODEL for this run (e.g. qwen3:14b). Applied to BOTH passes when --two-pass-llm.',\n )\n .option(\n '--general-model <name>',\n 'Model for the general LLM reviewer (overrides --model and OLLAMA_INTERN_MODEL).',\n )\n .option(\n '--critic-model <name>',\n 'Model for the narrow_critic LLM reviewer (overrides --model and OLLAMA_INTERN_MODEL).',\n )\n .option(\n '--profile <name>',\n `Review profile name. Non-default profiles are calibration evidence under sections/<id>/reviews/<profile>/ and do NOT update canonical state until promoted via 'review promote'.`,\n DEFAULT_PROFILE,\n )\n .option(\n '--preset <name>',\n 'Reviewer preset name from research.yaml/review_profiles. Fills --general-model, --critic-model, --review-window, --two-pass-llm from the preset; explicit flags still override.',\n )\n .action(async (section: string, opts) => {\n try {\n // Resolve preset (if any) from research.yaml/review_profiles. Explicit\n // CLI flags override preset values; preset only fills the gaps.\n let preset:\n | {\n general_model?: string | null;\n critic_model?: string | null;\n review_window?: number | null;\n mode?: 'general' | 'two_pass';\n }\n | undefined;\n if (opts.preset) {\n const fs = await import('node:fs/promises');\n const path = await import('node:path');\n const yaml = await import('yaml');\n const { ResearchYamlSchema } = await import('./intake/schema.js');\n const yamlPath = path.join(opts.pack as string, 'research.yaml');\n const research = ResearchYamlSchema.parse(\n yaml.parse(await fs.readFile(yamlPath, 'utf8')),\n );\n const found = research.review_profiles[opts.preset as string];\n if (!found) {\n throw new Error(\n `Preset \"${opts.preset}\" not in research.yaml/review_profiles. Known: ${Object.keys(research.review_profiles).join(', ') || '(none)'}`,\n );\n }\n preset = found;\n }\n\n const baseModel = (opts.model as string | undefined) ?? undefined;\n const generalModel =\n (opts.generalModel as string | undefined) ??\n baseModel ??\n preset?.general_model ??\n undefined;\n const criticModel =\n (opts.criticModel as string | undefined) ??\n baseModel ??\n preset?.critic_model ??\n undefined;\n const reviewWindow =\n (opts.reviewWindow as number | undefined) ?? preset?.review_window ?? undefined;\n const twoPass =\n Boolean(opts.twoPassLlm) || (preset?.mode === 'two_pass' ? true : false);\n\n const reviewers = opts.heuristicOnly\n ? [new HeuristicReviewer()]\n : twoPass\n ? [\n new OllamaInternReviewer({\n mode: 'general',\n model: generalModel ?? undefined,\n claimsPerWindow: reviewWindow,\n }),\n new OllamaInternReviewer({\n mode: 'narrow_critic',\n model: criticModel ?? undefined,\n claimsPerWindow: reviewWindow,\n }),\n new HeuristicReviewer(),\n ]\n : reviewWindow || opts.llmPaged || baseModel || generalModel\n ? [\n new OllamaInternReviewer({\n model: generalModel ?? undefined,\n claimsPerWindow: reviewWindow,\n }),\n new HeuristicReviewer(),\n ]\n : undefined;\n const result = await runReview({\n sectionId: section,\n packPath: opts.pack,\n reviewers,\n triagedOnly: opts.triagedOnly,\n multiPass: twoPass,\n profile: opts.profile as string | undefined,\n });\n process.stdout.write(`review complete\\n`);\n process.stdout.write(` section: ${result.sectionId}\\n`);\n process.stdout.write(` reviewer: ${result.reviewer}\\n`);\n process.stdout.write(` method: ${result.reviewMethod}\\n`);\n process.stdout.write(` candidate claims: ${result.candidateClaims}\\n`);\n process.stdout.write(` findings added: ${result.findingsAdded}\\n`);\n process.stdout.write(` findings deduped: ${result.findingsDeduped}\\n`);\n process.stdout.write(` llm findings rejected: ${result.llmFindingsRejected}\\n`);\n process.stdout.write(` blocking findings: ${result.blockingFindings}\\n`);\n process.stdout.write(` promoted to reviewed: ${result.promotedToReviewed}\\n`);\n process.stdout.write(`\\ndecisions:\\n`);\n for (const [d, n] of Object.entries(result.decisions)) {\n process.stdout.write(` ${d}: ${n}\\n`);\n }\n } catch (err) {\n reportError(err);\n }\n });\n\nconst indexCmd = program\n .command('index')\n .description('Build, query, and export the pack-local research-truth index');\n\nindexCmd\n .command('build')\n .description('Build the in-pack SQLite index from canonical artifacts')\n .argument('[section]', 'Optional section id; omit to index every section')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .option('--all', 'Index every section in the pack (default behavior)')\n .action(async (section: string | undefined, opts) => {\n try {\n const result = await indexBuild({\n sectionId: section,\n packPath: opts.pack,\n all: opts.all,\n });\n process.stdout.write(`index build complete\\n`);\n process.stdout.write(` db: ${result.dbPath}\\n`);\n process.stdout.write(` sections indexed: ${result.sectionsIndexed}\\n`);\n process.stdout.write(` sources: ${result.sources}\\n`);\n process.stdout.write(` claims: ${result.claims}\\n`);\n process.stdout.write(` contradictions: ${result.contradictions}\\n`);\n process.stdout.write(` review findings: ${result.reviewFindings}\\n`);\n process.stdout.write(` claim reviews: ${result.claimReviews}\\n`);\n process.stdout.write(` gate results: ${result.gateResults}\\n`);\n process.stdout.write(` fetch receipts: ${result.fetchReceipts}\\n`);\n process.stdout.write(` artifacts tracked: ${result.artifacts}\\n`);\n } catch (err) {\n reportError(err);\n }\n });\n\nindexCmd\n .command('export-repo-knowledge')\n .description('Write a repo-knowledge-compatible facts JSONL from the index')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .option('--out <path>', 'Output path; defaults to evidence/repo-knowledge/research-os-facts.jsonl')\n .action(async (opts) => {\n try {\n const result = await exportRepoKnowledge({\n packPath: opts.pack,\n outPath: opts.out,\n });\n process.stdout.write(`export complete\\n`);\n process.stdout.write(` out: ${result.outPath}\\n`);\n process.stdout.write(` facts: ${result.factCount}\\n`);\n for (const [t, n] of Object.entries(result.byType)) {\n process.stdout.write(` ${t}: ${n}\\n`);\n }\n } catch (err) {\n reportError(err);\n }\n });\n\nindexCmd\n .command('sync-repo-knowledge')\n .description('Sync the index into a locally-installed @mcptoolshop/repo-knowledge (optional, skips cleanly when absent)')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .action(async (opts) => {\n try {\n const result = await syncRepoKnowledge({ packPath: opts.pack });\n process.stdout.write(`sync attempted: ${result.attempted}\\n`);\n process.stdout.write(` ok: ${result.ok}\\n`);\n process.stdout.write(` facts synced: ${result.factsSynced}\\n`);\n process.stdout.write(` reason: ${result.reason}\\n`);\n if (result.attempted && !result.ok) process.exitCode = 2;\n } catch (err) {\n reportError(err);\n }\n });\n\nprogram\n .command('query')\n .description('Query the pack-local research-truth index')\n .argument('<term>', 'Search term (FTS5 syntax accepted)')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .option('--limit <n>', 'Max hits to return', (v) => parseInt(v, 10), 25)\n .option('--type <type>', 'Restrict to one record type (claim, source, contradiction, review_finding, gate_result, fetch_receipt, claim_review, section)')\n .action((term: string, opts) => {\n try {\n const result = indexQuery({\n term,\n packPath: opts.pack,\n limit: opts.limit,\n recordType: opts.type,\n });\n process.stdout.write(`query: ${JSON.stringify(result.term)}\\n`);\n process.stdout.write(`hits: ${result.totalHits}\\n\\n`);\n for (const [type, hits] of Object.entries(result.groupedByType)) {\n process.stdout.write(`== ${type} (${hits.length}) ==\\n`);\n for (const h of hits) {\n process.stdout.write(` [${h.section_id ?? '-'}] ${h.record_id}\\n`);\n process.stdout.write(` artifact: ${h.artifact_path}\\n`);\n process.stdout.write(` snippet: ${h.snippet.replace(/\\s+/g, ' ').slice(0, 240)}\\n`);\n }\n process.stdout.write('\\n');\n }\n } catch (err) {\n reportError(err);\n }\n });\n\nconst coworkCmd = program\n .command('cowork')\n .description('Cowork handoff: render the runtime contract from research truth');\n\ncoworkCmd\n .command('handoff')\n .description('Generate handoffs/cowork-handoff.json + handoffs/cowork-master.md from current pack state')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .action(async (opts) => {\n try {\n const result = await coworkHandoff({ packPath: opts.pack });\n process.stdout.write(`cowork handoff rendered\\n`);\n process.stdout.write(` pack id: ${result.packId}\\n`);\n process.stdout.write(` pack topic: ${result.packTopic}\\n`);\n process.stdout.write(` mode: ${result.mode}\\n`);\n process.stdout.write(` synthesis allowed: ${result.synthesisAllowed}\\n`);\n process.stdout.write(` accepted claims: ${result.acceptedCount}\\n`);\n process.stdout.write(` repair claims: ${result.repairCount}\\n`);\n process.stdout.write(` rejected claims: ${result.blockedCount}\\n`);\n process.stdout.write(` json: ${result.jsonPath}\\n`);\n process.stdout.write(` markdown: ${result.markdownPath}\\n`);\n if (result.warnings.length > 0) {\n process.stdout.write(`\\nwarnings:\\n`);\n for (const w of result.warnings) {\n process.stdout.write(` - ${w}\\n`);\n }\n }\n if (!result.synthesisAllowed) process.exitCode = 0; // not an error — informational\n } catch (err) {\n reportError(err);\n }\n });\n\nconst synthCmd = program\n .command('synth')\n .description('Synthesis workspace: organize accepted research truth for Cowork');\n\nsynthCmd\n .command('workspace')\n .description('Create the synthesis workspace; refuses unless cowork handoff mode is synthesis_ready')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .action(async (opts) => {\n try {\n const result = await synthWorkspace({ packPath: opts.pack });\n if (result.refused) {\n process.stdout.write(`synthesis workspace: REFUSED\\n`);\n process.stdout.write(` mode: ${result.mode}\\n`);\n process.stdout.write(` reason: ${result.refusalReason}\\n`);\n process.exitCode = 2;\n return;\n }\n process.stdout.write(`synthesis workspace ready\\n`);\n process.stdout.write(` mode: ${result.mode}\\n`);\n process.stdout.write(` accepted claims: ${result.acceptedClaims}\\n`);\n process.stdout.write(` claim clusters: ${result.claimClusters}\\n`);\n process.stdout.write(` scope overlaps: ${result.scopeOverlaps}\\n`);\n process.stdout.write(` cross-section contradictions: ${result.crossSectionContradictions}\\n`);\n for (const f of result.filesWritten) process.stdout.write(` wrote: ${f}\\n`);\n } catch (err) {\n reportError(err);\n }\n });\n\nprogram\n .command('audit')\n .description('Aggregate pack-level audit rollups across all sections')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .action(async (opts) => {\n try {\n const result = await runAudit({ packPath: opts.pack });\n process.stdout.write(`pack audit complete\\n`);\n process.stdout.write(` verdict: ${result.verdict}\\n`);\n process.stdout.write(` synthesis allowed: ${result.synthesisAllowed}\\n`);\n process.stdout.write(` orphan claims: ${result.orphans}\\n`);\n process.stdout.write(` stale sources: ${result.staleSources}\\n`);\n process.stdout.write(` weak sources: ${result.weakSources}\\n`);\n process.stdout.write(` unresolved contradictions:${result.unresolvedContradictions}\\n`);\n process.stdout.write(` scope-widening risks: ${result.scopeWideningRisks}\\n`);\n process.stdout.write(` source-diversity gaps: ${result.sourceDiversityGaps}\\n`);\n process.stdout.write(` files written: ${result.filesWritten.length}\\n`);\n if (result.blockingReasons.length > 0) {\n process.stdout.write(`\\nblocking reasons:\\n`);\n for (const b of result.blockingReasons) process.stdout.write(` - ${b}\\n`);\n }\n if (result.warnings.length > 0) {\n process.stdout.write(`\\nwarnings:\\n`);\n for (const w of result.warnings) process.stdout.write(` - ${w}\\n`);\n }\n if (!result.synthesisAllowed) process.exitCode = 2;\n } catch (err) {\n reportError(err);\n }\n });\n\nprogram\n .command('freeze')\n .description('Final integrity lock; refuses unless every condition is met')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .action(async (opts) => {\n try {\n const result = await runFreeze({ packPath: opts.pack });\n if (result.verdict === 'refused') {\n process.stdout.write(`freeze: REFUSED\\n`);\n process.stdout.write(` reasons: ${result.reasonsCount}\\n`);\n if (result.refusalPayload) {\n for (const r of result.refusalPayload.blocking_reasons) {\n process.stdout.write(` - ${r}\\n`);\n }\n if (result.refusalPayload.next_actions.length > 0) {\n process.stdout.write(`\\nnext actions:\\n`);\n for (const a of result.refusalPayload.next_actions) process.stdout.write(` - ${a}\\n`);\n }\n }\n process.stdout.write(` refusal json: ${result.jsonPath}\\n`);\n process.stdout.write(` refusal markdown: ${result.markdownPath}\\n`);\n process.exitCode = 2;\n return;\n }\n process.stdout.write(`freeze: FROZEN\\n`);\n if (result.receiptPayload) {\n process.stdout.write(` pack id: ${result.receiptPayload.pack_id}\\n`);\n process.stdout.write(` frozen at: ${result.receiptPayload.frozen_at}\\n`);\n process.stdout.write(` accepted claims: ${result.receiptPayload.accepted_claim_ids.length}\\n`);\n process.stdout.write(` cited claims: ${result.citedClaimCount}\\n`);\n process.stdout.write(` uncited accepted (info): ${result.uncitedAcceptedClaimCount}\\n`);\n process.stdout.write(` unresolved contradictions: ${result.receiptPayload.unresolved_contradictions.length}\\n`);\n process.stdout.write(` waivers disclosed: ${result.receiptPayload.waivers_disclosed.length}\\n`);\n process.stdout.write(` canonical artifacts hashed: ${result.receiptPayload.canonical_artifact_hashes.length}\\n`);\n process.stdout.write(` synthesis files hashed: ${result.receiptPayload.synthesis_hashes.length}\\n`);\n }\n process.stdout.write(` receipt json: ${result.jsonPath}\\n`);\n process.stdout.write(` receipt markdown: ${result.markdownPath}\\n`);\n } catch (err) {\n reportError(err);\n }\n });\n\nconst invalidate = program\n .command('invalidate')\n .description('Invalidate (archive with a receipt) artifacts produced under a superseded contract');\n\ninvalidate\n .command('extraction')\n .description(\n 'Archive claims/reviews/contradictions/audits/handoffs/synthesis written under the legacy authored-evidence-excerpt contract; replaced by span-first-extraction',\n )\n .requiredOption('--reason <text>', 'Plain-language reason recorded on the invalidation receipt')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .option('--label <slug>', 'Folder label under audits/legacy/', 'pre-span-extraction')\n .option('--new-contract <name>', 'Name recorded for the replacement contract', 'span-first-extraction')\n .option(\n '--superseded-contract <name>',\n 'Name recorded for the contract being retired',\n 'authored-evidence-excerpt',\n )\n .option('--notes <text>', 'Optional free-text notes to include on the receipt')\n .action(async (opts) => {\n try {\n const result = await invalidateExtraction({\n packPath: opts.pack,\n reason: opts.reason,\n label: opts.label,\n newContract: opts.newContract,\n supersededContract: opts.supersededContract,\n notes: opts.notes,\n });\n if (!result.performed) {\n process.stdout.write(`invalidate extraction: no-op\\n`);\n process.stdout.write(` ${result.message}\\n`);\n return;\n }\n process.stdout.write(`invalidate extraction: archived\\n`);\n process.stdout.write(` receipt id: ${result.receiptId}\\n`);\n process.stdout.write(` contract label: ${result.contractLabel}\\n`);\n process.stdout.write(` affected sections: ${result.affectedSections.length}\\n`);\n for (const s of result.affectedSections) process.stdout.write(` - ${s}\\n`);\n process.stdout.write(` archived count: ${result.archivedCount}\\n`);\n process.stdout.write(` archive dir: ${result.archiveDir}\\n`);\n } catch (err) {\n reportError(err);\n }\n });\n\ninvalidate\n .command('review')\n .description(\n 'Archive canonical review artifacts for a section into sections/<id>/legacy/<label>/<timestamp>/. Use to invalidate pre-profile review state before promoting a profile as new canonical truth.',\n )\n .argument('<section>', 'Section id, e.g. \"03-source-and-claim-truth\"')\n .requiredOption('--reason <text>', 'Plain-language reason recorded on the invalidation receipt')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .option('--label <slug>', 'Folder label under sections/<id>/legacy/', 'pre-review-profiles')\n .option('--notes <text>', 'Optional free-text notes recorded on the receipt')\n .action(async (section: string, opts) => {\n try {\n const result = await invalidateReview({\n packPath: opts.pack,\n sectionId: section,\n reason: opts.reason,\n label: opts.label,\n notes: opts.notes,\n });\n if (!result.performed) {\n process.stdout.write(`invalidate review: no-op\\n`);\n process.stdout.write(` ${result.message}\\n`);\n return;\n }\n process.stdout.write(`invalidate review: archived\\n`);\n process.stdout.write(` receipt id: ${result.receiptId}\\n`);\n process.stdout.write(` section: ${result.sectionId}\\n`);\n process.stdout.write(` contract label: ${result.contractLabel}\\n`);\n process.stdout.write(` archived count: ${result.archivedCount}\\n`);\n process.stdout.write(` archive dir: ${result.archiveDir}\\n`);\n } catch (err) {\n reportError(err);\n }\n });\n\nprogram\n .command('review-promote')\n .description(\n 'Promote a review profile to active state: copies the profile artifacts to canonical paths and writes review-active.json. Until promoted, profile runs are calibration evidence, not section truth.',\n )\n .argument('<section>', 'Section id, e.g. \"03-source-and-claim-truth\"')\n .requiredOption('--profile <name>', 'Profile name to promote')\n .option('--pack <dir>', 'Path to the pack root (defaults to cwd)', process.cwd())\n .option(\n '--reason <text>',\n 'Free-text rationale recorded on review-active.json — why this profile is being trusted',\n )\n .option('--calibration-fixture <name>', 'Calibration fixture name')\n .option('--good-fp <text>', 'good-claim false-positive rate string (e.g. \"0/5 (0%)\")')\n .option('--any-flag-recall <text>', 'bad-claim any-flag recall string (e.g. \"9/13 (69%)\")')\n .option('--strict-cat-recall <text>', 'strict-category recall string')\n .option('--unsupported-recall <text>', 'unsupported_claim category recall string')\n .option('--calibration-notes <text>', 'free-text calibration notes')\n .option(\n '--bump-section-status',\n 'Also bump section.status from gated → reviewed if every promoted claim is accepted_for_synthesis',\n false,\n )\n .action(async (section: string, opts) => {\n try {\n const calibration =\n opts.calibrationFixture ||\n opts.goodFp ||\n opts.anyFlagRecall ||\n opts.strictCatRecall ||\n opts.unsupportedRecall ||\n opts.calibrationNotes\n ? {\n fixture: opts.calibrationFixture ?? null,\n good_false_positive_rate: opts.goodFp ?? null,\n bad_any_flag_recall: opts.anyFlagRecall ?? null,\n strict_category_recall: opts.strictCatRecall ?? null,\n unsupported_claim_recall: opts.unsupportedRecall ?? null,\n notes: opts.calibrationNotes ?? null,\n }\n : null;\n const result = await runPromote({\n sectionId: section,\n packPath: opts.pack,\n profile: opts.profile,\n promotionReason: opts.reason,\n calibrationSummary: calibration,\n promoteSectionStatus: opts.bumpSectionStatus,\n });\n process.stdout.write(`review profile promoted\\n`);\n process.stdout.write(` section: ${result.sectionId}\\n`);\n process.stdout.write(` profile: ${result.profile}\\n`);\n process.stdout.write(` promoted_at: ${result.promoted_at}\\n`);\n process.stdout.write(` promoted_method: ${result.promoted_method}\\n`);\n process.stdout.write(` promoted_reviewer: ${result.promoted_reviewer}\\n`);\n process.stdout.write(` status bumped: ${result.section_status_bumped}\\n`);\n process.stdout.write(` canonical files updated: ${result.canonical_files_updated.length}\\n`);\n } catch (err) {\n reportError(err);\n }\n });\n\nconst packCmd = program\n .command('pack')\n .description('Pack-level publication and archive operations');\n\npackCmd\n .command('publish')\n .description(\n 'Export a frozen pack into the research-packs archive format. ' +\n 'Copies the pack, derives pack.manifest.json, generates README.md, ' +\n 'provisions docs/how-to-read-this.md, and verifies the admission contract.',\n )\n .requiredOption('--to <path>', 'Target package directory, e.g. <research-packs>/packages/<name>')\n .option('--from <path>', 'Source frozen pack directory (defaults to cwd)', process.cwd())\n .option('--operator-notes <text>', 'Operator notes recorded in pack.manifest.json', '')\n .option('--force', 'Overwrite an existing non-empty target directory', false)\n .option('--dry-run', 'Print derived manifest and README plan; write nothing', false)\n .action(async (opts) => {\n try {\n const result = await packPublish({\n fromDir: opts.from as string,\n toDir: opts.to as string,\n operatorNotes: opts.operatorNotes as string,\n force: Boolean(opts.force),\n dryRun: Boolean(opts.dryRun),\n });\n if (result.dryRun) {\n process.stdout.write(`pack publish: DRY-RUN — no files written\\n`);\n process.stdout.write(` package name: ${result.packageName}\\n`);\n if (result.dryRunManifest) {\n const m = result.dryRunManifest;\n process.stdout.write(` topic: ${m.topic.slice(0, 80)}\\n`);\n process.stdout.write(` frozen_at: ${m.frozen_at}\\n`);\n process.stdout.write(` sections: ${m.totals.sections}\\n`);\n process.stdout.write(` accepted: ${m.totals.accepted_claims}\\n`);\n process.stdout.write(` receipt sha256:${m.freeze_receipt_sha256.slice(0, 16)}…\\n`);\n }\n return;\n }\n process.stdout.write(`pack publish: DONE\\n`);\n process.stdout.write(` package name: ${result.packageName}\\n`);\n process.stdout.write(` files written: ${result.filesWritten.length}\\n`);\n for (const f of result.filesWritten) process.stdout.write(` ${f}\\n`);\n process.stdout.write(` verify: ${result.verifyPassed ? 'PASS' : 'FAIL'}\\n`);\n if (result.warnings.length > 0) {\n process.stdout.write(`\\nwarnings:\\n`);\n for (const w of result.warnings) process.stdout.write(` - ${w}\\n`);\n }\n if (!result.verifyPassed) process.exitCode = 2;\n } catch (err) {\n reportError(err);\n }\n });\n\nprogram.parseAsync(process.argv);\n","import { existsSync, mkdirSync, writeFileSync, readFileSync, readdirSync } from 'node:fs';\nimport { join, basename, resolve } from 'node:path';\nimport { deriveManifest } from './manifest.js';\nimport { generateReadme } from './readme.js';\nimport { generateHowToReadScaffold } from './how-to-read.js';\nimport { copyDir } from './copy.js';\nimport { verifyPack } from './verify.js';\nimport type { PublishInput, PublishResult } from './types.js';\n\n// Source pack files that must exist before publish begins.\nconst REQUIRED_SOURCE_FILES = [\n 'research.yaml',\n 'audits/freeze-receipt.json',\n 'audits/pack-audit.json',\n 'synthesis/final-report.md',\n 'synthesis/decision-brief.md',\n];\n\nexport async function publish(input: PublishInput): Promise<PublishResult> {\n const fromDir = resolve(input.fromDir);\n const toDir = resolve(input.toDir);\n const packageName = basename(toDir);\n const warnings: string[] = [];\n\n // 1. Validate source pack has required files\n for (const rel of REQUIRED_SOURCE_FILES) {\n if (!existsSync(join(fromDir, rel))) {\n throw new Error(\n `Source pack missing required file: ${rel}\\n Hint: run research-os freeze before publish\\n Pack: ${fromDir}`,\n );\n }\n }\n\n // 2. Refuse if freeze-refusal artifacts exist (pack did not freeze cleanly)\n if (\n existsSync(join(fromDir, 'audits/freeze-refusal.json')) ||\n existsSync(join(fromDir, 'audits/freeze-refusal.md'))\n ) {\n throw new Error(\n `Source pack has freeze-refusal artifacts — pack did not freeze cleanly.\\n Resolve blocking reasons then re-run research-os freeze.\\n Pack: ${fromDir}`,\n );\n }\n\n // 3. Check target: refuse if non-empty without --force\n if (existsSync(toDir)) {\n const entries = readdirSync(toDir);\n if (entries.length > 0 && !input.force) {\n throw new Error(\n `Target directory already exists and is non-empty: ${toDir}\\n Use --force to overwrite.`,\n );\n }\n }\n\n // 4. Derive manifest early — fail fast on bad pack state before writing anything\n const manifest = deriveManifest(fromDir, packageName, input.operatorNotes ?? '');\n\n // 5. Dry-run: print plan without writing\n if (input.dryRun) {\n const finalReportPath = join(fromDir, 'synthesis/final-report.md');\n const finalReport = existsSync(finalReportPath)\n ? readFileSync(finalReportPath, 'utf8')\n : '';\n const readme = generateReadme(manifest, finalReport);\n return {\n packageName,\n filesWritten: [],\n warnings: ['dry-run: no files written'],\n verifyPassed: false,\n dryRun: true,\n dryRunManifest: manifest,\n dryRunReadme: readme,\n };\n }\n\n // 6. Create target directory\n mkdirSync(toDir, { recursive: true });\n\n const filesWritten: string[] = [];\n\n // 7. Copy entire frozen pack to <target>/pack/\n const packTarget = join(toDir, 'pack');\n const packFileCount = copyDir(fromDir, packTarget);\n filesWritten.push(`pack/ (${packFileCount} files)`);\n\n // 8. Copy synthesis/ to <target>/synthesis/ (Lane 1 accessibility)\n const synthSrc = join(fromDir, 'synthesis');\n if (existsSync(synthSrc)) {\n const synthTarget = join(toDir, 'synthesis');\n const synthFileCount = copyDir(synthSrc, synthTarget);\n filesWritten.push(`synthesis/ (${synthFileCount} files)`);\n } else {\n warnings.push(\n 'No synthesis/ directory in source pack — Lane 1 synthesis files not written',\n );\n }\n\n // 9. Write pack.manifest.json\n writeFileSync(\n join(toDir, 'pack.manifest.json'),\n JSON.stringify(manifest, null, 2) + '\\n',\n 'utf8',\n );\n filesWritten.push('pack.manifest.json');\n\n // 10. Generate README.md from final-report.md + manifest\n const finalReportPath = join(fromDir, 'synthesis/final-report.md');\n const finalReport = existsSync(finalReportPath) ? readFileSync(finalReportPath, 'utf8') : '';\n const readme = generateReadme(manifest, finalReport);\n writeFileSync(join(toDir, 'README.md'), readme, 'utf8');\n filesWritten.push('README.md');\n\n // 11. Provision docs/how-to-read-this.md scaffold (preserve if already exists)\n const docsDir = join(toDir, 'docs');\n mkdirSync(docsDir, { recursive: true });\n const howToReadPath = join(docsDir, 'how-to-read-this.md');\n if (existsSync(howToReadPath)) {\n warnings.push(\n 'docs/how-to-read-this.md already exists — not overwritten (operator-authored content preserved)',\n );\n } else {\n const scaffold = generateHowToReadScaffold(manifest);\n writeFileSync(howToReadPath, scaffold, 'utf8');\n filesWritten.push('docs/how-to-read-this.md');\n }\n\n // 12. Run inline admission-contract verification\n const verifyResult = verifyPack(toDir);\n for (const w of verifyResult.softWarnings ?? []) warnings.push(w);\n\n if (!verifyResult.pass) {\n throw new Error(\n `Pack verification FAILED after publish — the published package does not meet the admission contract.\\n` +\n ` ${verifyResult.reason}\\n` +\n ` Target: ${toDir}`,\n );\n }\n\n return {\n packageName,\n filesWritten,\n warnings,\n verifyPassed: true,\n dryRun: false,\n };\n}\n\nexport { verifyPack } from './verify.js';\nexport { deriveManifest } from './manifest.js';\nexport { generateReadme } from './readme.js';\nexport { generateHowToReadScaffold } from './how-to-read.js';\nexport type { PublishInput, PublishResult } from './types.js';\nexport type { PackManifest } from './schema.js';\n","import { createHash } from 'node:crypto';\nimport { readFileSync, existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { parse as parseYaml } from 'yaml';\nimport { z } from 'zod';\nimport { ResearchYamlSchema } from '../../intake/schema.js';\nimport { PackManifestSchema } from './schema.js';\nimport type { PackManifest } from './schema.js';\n\n// Minimal schema for gate-result.json — only the fields manifest derivation needs.\nconst GateResultMinimalSchema = z.object({\n verdict: z.enum(['pass', 'warn', 'fail', 'blocked']),\n synthesis_eligible: z.boolean(),\n});\n\ninterface ClaimReviewLine {\n claim_id: string;\n decision: string;\n created_at: string;\n}\n\ninterface ResolutionLine {\n contradiction_id: string;\n status: string;\n resolved_at: string;\n}\n\ninterface DispositionLine {\n claim_id: string;\n created_at: string;\n}\n\ninterface AuditSectionSummary {\n section_id: string;\n accepted_claims: number;\n}\n\nfunction sha256Bytes(buf: Buffer): string {\n return createHash('sha256').update(buf).digest('hex');\n}\n\nfunction parseJsonl<T>(content: string): T[] {\n return content\n .split('\\n')\n .filter((l) => l.trim().length > 0)\n .map((l) => JSON.parse(l) as T);\n}\n\nfunction readJsonlSafe<T>(filePath: string): T[] {\n if (!existsSync(filePath)) return [];\n return parseJsonl<T>(readFileSync(filePath, 'utf8'));\n}\n\nfunction latestClaimDecisions(reviews: ClaimReviewLine[]): Map<string, string> {\n const m = new Map<string, string>();\n const sorted = [...reviews].sort((a, b) => a.created_at.localeCompare(b.created_at));\n for (const r of sorted) m.set(r.claim_id, r.decision);\n return m;\n}\n\nfunction latestContradictionStatuses(resolutions: ResolutionLine[]): Map<string, string> {\n const m = new Map<string, string>();\n const sorted = [...resolutions].sort((a, b) => a.resolved_at.localeCompare(b.resolved_at));\n for (const r of sorted) m.set(r.contradiction_id, r.status);\n return m;\n}\n\nfunction latestDispositionStatuses(dispositions: DispositionLine[]): Map<string, string> {\n const m = new Map<string, string>();\n const sorted = [...dispositions].sort((a, b) => a.created_at.localeCompare(b.created_at));\n for (const d of sorted) m.set(d.claim_id, 'dispositioned');\n return m;\n}\n\nexport interface ManifestRefusal {\n reason: string;\n}\n\nexport function deriveManifest(\n packDir: string,\n packageName: string,\n operatorNotes = '',\n): PackManifest {\n // research.yaml\n const yamlPath = join(packDir, 'research.yaml');\n if (!existsSync(yamlPath)) throw new Error(`research.yaml not found in ${packDir}`);\n const research = ResearchYamlSchema.parse(parseYaml(readFileSync(yamlPath, 'utf8')));\n if (!research.frozen_at) {\n throw new Error(`Pack is not frozen: research.yaml.frozen_at is null — run research-os freeze first`);\n }\n\n // freeze-receipt.json → sha256 of file bytes → freeze_receipt_sha256; parse for frozen_at\n const receiptPath = join(packDir, 'audits/freeze-receipt.json');\n if (!existsSync(receiptPath)) {\n throw new Error(`audits/freeze-receipt.json not found — pack is not frozen`);\n }\n const receiptBytes = readFileSync(receiptPath);\n const freeze_receipt_sha256 = sha256Bytes(receiptBytes);\n const receipt = JSON.parse(receiptBytes.toString('utf8')) as { frozen_at?: string };\n const frozen_at = receipt.frozen_at ?? research.frozen_at;\n\n // pack-audit.json → per-section accepted_claims for cross-check\n const packAuditPath = join(packDir, 'audits/pack-audit.json');\n if (!existsSync(packAuditPath)) throw new Error(`audits/pack-audit.json not found`);\n const packAudit = JSON.parse(readFileSync(packAuditPath, 'utf8')) as {\n section_summaries?: AuditSectionSummary[];\n };\n const auditSectionMap = new Map<string, number>(\n (packAudit.section_summaries ?? []).map((s) => [s.section_id, s.accepted_claims]),\n );\n\n // Per-section derivation\n const sectionIds = research.sections.map((s) => s.id);\n const sections: PackManifest['sections'] = [];\n let totalAccepted = 0;\n let totalDispositioned = 0;\n let totalPreserved = 0;\n\n for (const sectionId of sectionIds) {\n const sectionDir = join(packDir, 'sections', sectionId);\n\n // claim-reviews.jsonl → latest-decision-wins → count accepted_for_synthesis\n const reviews = readJsonlSafe<ClaimReviewLine>(join(sectionDir, 'claim-reviews.jsonl'));\n const decisionMap = latestClaimDecisions(reviews);\n const acceptedCount = [...decisionMap.values()].filter(\n (d) => d === 'accepted_for_synthesis',\n ).length;\n\n // Cross-check against pack-audit.json section summaries (Pattern 2 — same predicate)\n const auditAccepted = auditSectionMap.get(sectionId);\n if (auditAccepted !== undefined && auditAccepted !== acceptedCount) {\n throw new Error(\n `Section ${sectionId}: accepted_claims mismatch between claim-reviews.jsonl (${acceptedCount})` +\n ` and pack-audit.json (${auditAccepted}). Closure-ledger seam disagreement — investigate before publishing.`,\n );\n }\n\n // audits/<section-id>-gate.json → verdict + synthesis_eligible\n const gateResultPath = join(packDir, 'audits', `${sectionId}-gate.json`);\n if (!existsSync(gateResultPath)) {\n throw new Error(`audits/${sectionId}-gate.json not found — section not gated`);\n }\n const gateResult = GateResultMinimalSchema.parse(\n JSON.parse(readFileSync(gateResultPath, 'utf8')),\n );\n\n // claim-synthesis-dispositions.jsonl → latest-status-wins count\n const dispositions = readJsonlSafe<DispositionLine>(\n join(sectionDir, 'claim-synthesis-dispositions.jsonl'),\n );\n const dispositionMap = latestDispositionStatuses(dispositions);\n totalDispositioned += dispositionMap.size;\n\n // contradiction-resolutions.jsonl → latest-status-wins; assert none unresolved\n const resolutions = readJsonlSafe<ResolutionLine>(\n join(sectionDir, 'contradiction-resolutions.jsonl'),\n );\n const resolutionMap = latestContradictionStatuses(resolutions);\n const stillUnresolved = [...resolutionMap.values()].filter((s) => s === 'unresolved').length;\n if (stillUnresolved > 0) {\n throw new Error(\n `Section ${sectionId} has ${stillUnresolved} unresolved contradictions.` +\n ` Freeze should have blocked this — investigate before publishing.`,\n );\n }\n totalPreserved += [...resolutionMap.values()].filter((s) => s !== 'unresolved').length;\n\n totalAccepted += acceptedCount;\n sections.push({\n id: sectionId,\n accepted_claims: acceptedCount,\n gate: gateResult.verdict,\n synthesis_eligible: gateResult.synthesis_eligible,\n });\n }\n\n const totalsBase = {\n sections: sections.length,\n accepted_claims: totalAccepted,\n dispositioned: totalDispositioned,\n unresolved_contradictions: 0,\n };\n\n return PackManifestSchema.parse({\n name: packageName,\n topic: research.topic,\n frozen_at,\n research_os_version: research.research_os_version,\n sections,\n totals: totalPreserved > 0\n ? { ...totalsBase, preserved_contradiction_records: totalPreserved }\n : totalsBase,\n freeze_receipt_sha256,\n operator_notes: operatorNotes,\n });\n}\n","import { z } from 'zod';\n\n// Mirror of research-packs/scripts/manifest-schema.mjs in TypeScript.\n// Manifests produced by pack publish must validate against both this schema\n// and the MJS schema (verified by the dogfood test via verify-pack.mjs).\n\nexport const SectionSummarySchema = z.object({\n id: z.string().min(1),\n accepted_claims: z.number().int().min(0),\n gate: z.enum(['pass', 'warn', 'fail', 'blocked', 'pass_with_waiver']),\n synthesis_eligible: z.boolean(),\n});\n\nexport const TotalsSchema = z.object({\n sections: z.number().int().min(1),\n accepted_claims: z.number().int().min(0),\n dispositioned: z.number().int().min(0),\n unresolved_contradictions: z.number().int().min(0),\n preserved_contradiction_records: z.number().int().min(0).optional(),\n});\n\nexport const PackManifestSchema = z.object({\n name: z.string().min(1),\n topic: z.string().min(1),\n frozen_at: z.string().datetime(),\n research_os_version: z.string().min(1),\n sections: z.array(SectionSummarySchema).min(1),\n totals: TotalsSchema,\n freeze_receipt_sha256: z.string().regex(/^[a-f0-9]{64}$/, 'Must be a 64-char hex sha256'),\n operator_notes: z.string().default(''),\n});\n\nexport type PackManifest = z.infer<typeof PackManifestSchema>;\nexport type SectionSummary = z.infer<typeof SectionSummarySchema>;\nexport type Totals = z.infer<typeof TotalsSchema>;\n","import type { PackManifest } from './schema.js';\n\n// Port of research-packs/scripts/summarize-pack.mjs generateReadme() to TypeScript.\n// Must produce identical output — verified by the dogfood test.\n\nfunction extractSummary(markdown: string): string {\n const lines = markdown.split('\\n');\n let inSummary = false;\n const summaryLines: string[] = [];\n for (const line of lines) {\n if (/^## Summary\\s*$/.test(line)) { inSummary = true; continue; }\n if (inSummary && /^## /.test(line)) break;\n if (inSummary) summaryLines.push(line);\n }\n return summaryLines.join('\\n').trim();\n}\n\nexport function generateReadme(manifest: PackManifest, finalReport: string): string {\n const m = manifest;\n const frozenDate = m.frozen_at.slice(0, 10);\n const summary = extractSummary(finalReport);\n\n const sectionTable = m.sections\n .map((s) => `| ${s.id} | ${s.accepted_claims} | ${s.gate} | ${s.synthesis_eligible ? 'yes' : 'no'} |`)\n .join('\\n');\n\n const totalsLine =\n m.totals.preserved_contradiction_records != null\n ? `Preserved contradiction records: ${m.totals.preserved_contradiction_records}`\n : `${m.totals.unresolved_contradictions} unresolved contradictions`;\n\n const operatorSection = m.operator_notes\n ? `\\n---\\n\\n## Operator notes\\n\\n${m.operator_notes}\\n`\n : '';\n\n return `# ${m.name}\n\n**Topic:** ${m.topic}\n\n**Frozen:** ${frozenDate} | **research-os version:** ${m.research_os_version} | **Accepted claims:** ${m.totals.accepted_claims} across ${m.totals.sections} sections\n\n---\n\n## Executive summary\n\n${summary}\n\n---\n\n## Sections\n\n| Section | Accepted claims | Gate | Synthesis eligible |\n|---------|-----------------|------|-------------------|\n${sectionTable}\n\n**Totals:** ${m.totals.accepted_claims} accepted, ${m.totals.dispositioned} dispositioned, ${totalsLine}\n\n---\n\n## How to read this pack\n\nThis package is part of the [\\`research-packs\\`](../../README.md) archive.\n\n- **Lane 1 (synthesis):** You are here. See [\\`synthesis/final-report.md\\`](synthesis/final-report.md) for the full citation-clean prose.\n- **Lane 2 (evidence):** [\\`pack/\\`](pack/) — full frozen ledgers, source cards, excerpts, claim reviews, gate results, and \\`audits/freeze-receipt.json\\`.\n- **Lane 3 (method):** [\\`../../docs/\\`](../../docs/) — artifact contract, how-to-read, source quality notes.\n\nTo verify this pack's integrity: \\`node ../../scripts/verify-pack.mjs .\\` from this directory.\n\nSee [\\`docs/how-to-read-this.md\\`](docs/how-to-read-this.md) for pack-specific reading notes.${operatorSection}`;\n}\n","import type { PackManifest } from './schema.js';\n\nexport function generateHowToReadScaffold(manifest: PackManifest): string {\n const frozenDate = manifest.frozen_at.slice(0, 10);\n const contradictionNote =\n manifest.totals.preserved_contradiction_records != null\n ? `This pack has ${manifest.totals.preserved_contradiction_records} preserved contradiction records. ` +\n `These are not active blockers — freeze validated zero unresolved contradictions across all sections. ` +\n `The records are preserved for provenance in \\`pack/sections/<id>/contradiction-resolutions.jsonl\\`.`\n : 'This pack has no preserved contradiction records.';\n\n return `# How to read: ${manifest.name}\n\n<!-- SCAFFOLD: Pre-filled with pack-specific metadata by \\`research-os pack publish\\`.\n Final prose is human-authored. Edit freely — this file is NOT covered by the freeze receipt. -->\n\n**Pack:** \\`${manifest.name}\\`\n**Topic:** ${manifest.topic}\n**Frozen:** ${frozenDate}\n**Accepted claims:** ${manifest.totals.accepted_claims} accepted claims across ${manifest.totals.sections} section${manifest.totals.sections !== 1 ? 's' : ''}\n\n---\n\n## What this pack answers\n\n<!-- human-authored: describe what the synthesis delivers -->\n\n## How the evidence is structured\n\n<!-- human-authored: explain section breakdown, what each section investigated -->\n\n## Interpreting claim IDs\n\nClaims are referenced as \\`[claim:clm_<hex>]\\` in the synthesis prose. To look up a claim:\n\n1. Open \\`pack/sections/<section-id>/claims.jsonl\\`\n2. Find the entry with matching \\`claim_id\\`\n3. The \\`asserts\\` field is the claim; \\`evidence_excerpt\\` is the literal source span\n\nAccepted vs rejected: \\`pack/sections/<section-id>/claim-reviews.jsonl\\` — latest entry per \\`claim_id\\` wins.\n\n## Preserved contradiction records\n\n${contradictionNote}\n\n## Verifying integrity\n\nFrom this directory:\n\n\\`\\`\\`bash\nnode ../../scripts/verify-pack.mjs .\n\\`\\`\\`\n\nExpected output: PASS with artifact count and receipt sha256.\n\nSee [\\`../../docs/how-to-read-a-pack.md\\`](../../docs/how-to-read-a-pack.md) for the general guide.\n`;\n}\n","import { mkdirSync, copyFileSync, readdirSync } from 'node:fs';\nimport { join } from 'node:path';\n\nexport function copyDir(src: string, dst: string): number {\n mkdirSync(dst, { recursive: true });\n let count = 0;\n const entries = readdirSync(src, { withFileTypes: true });\n for (const entry of entries) {\n const srcPath = join(src, entry.name);\n const dstPath = join(dst, entry.name);\n if (entry.isDirectory()) {\n count += copyDir(srcPath, dstPath);\n } else if (entry.isFile()) {\n copyFileSync(srcPath, dstPath);\n count++;\n }\n }\n return count;\n}\n","import { createHash } from 'node:crypto';\nimport { readFileSync, existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { PackManifestSchema } from './schema.js';\n\n// Inline equivalent of research-packs/scripts/verify-pack.mjs.\n// Checks the same admission-contract conditions. The dogfood test uses the\n// MJS script directly; this inline version is used when the research-packs\n// checkout is unavailable or for testing.\n\nconst REQUIRED_FILES = [\n 'pack/audits/freeze-receipt.json',\n 'synthesis/final-report.md',\n 'synthesis/decision-brief.md',\n 'pack.manifest.json',\n 'README.md',\n];\n\nexport interface VerifyResult {\n pass: boolean;\n reason?: string;\n name?: string;\n artifactsVerified?: number;\n softWarnings?: string[];\n}\n\nfunction sha256File(filePath: string): string {\n return createHash('sha256').update(readFileSync(filePath)).digest('hex');\n}\n\nexport function verifyPack(packageDir: string): VerifyResult {\n // Step 1: Check admission-contract files\n for (const rel of REQUIRED_FILES) {\n const full = join(packageDir, rel);\n if (!existsSync(full)) {\n return { pass: false, reason: `MISSING required file: ${rel}` };\n }\n }\n\n // Step 2: Parse and validate pack.manifest.json\n let rawManifest: unknown;\n try {\n rawManifest = JSON.parse(readFileSync(join(packageDir, 'pack.manifest.json'), 'utf8'));\n } catch (e) {\n return { pass: false, reason: `pack.manifest.json parse error: ${(e as Error).message}` };\n }\n const parsed = PackManifestSchema.safeParse(rawManifest);\n if (!parsed.success) {\n const issues = parsed.error.issues\n .map((i) => `${i.path.join('.')}: ${i.message}`)\n .join(', ');\n return { pass: false, reason: `pack.manifest.json schema violation: ${issues}` };\n }\n const m = parsed.data;\n\n // Step 3: Verify freeze_receipt_sha256 matches actual file\n const receiptPath = join(packageDir, 'pack/audits/freeze-receipt.json');\n const actualReceiptHash = sha256File(receiptPath);\n if (actualReceiptHash !== m.freeze_receipt_sha256) {\n return {\n pass: false,\n reason:\n `freeze-receipt.json hash mismatch.\\n manifest: ${m.freeze_receipt_sha256}\\n actual: ${actualReceiptHash}`,\n name: m.name,\n };\n }\n\n // Step 4: Parse freeze receipt and re-verify all fingerprinted artifacts\n let receipt: {\n canonical_artifact_hashes?: Array<{ path: string; sha256: string }>;\n synthesis_hashes?: Array<{ path: string; sha256: string }>;\n };\n try {\n receipt = JSON.parse(readFileSync(receiptPath, 'utf8'));\n } catch (e) {\n return {\n pass: false,\n reason: `freeze-receipt.json parse error: ${(e as Error).message}`,\n name: m.name,\n };\n }\n\n const allFingerprints = [\n ...(receipt.canonical_artifact_hashes ?? []),\n ...(receipt.synthesis_hashes ?? []),\n ];\n\n let verified = 0;\n const softWarnings: string[] = [];\n for (const entry of allFingerprints) {\n const artifactPath = join(packageDir, 'pack', entry.path);\n if (!existsSync(artifactPath)) {\n return {\n pass: false,\n reason: `Fingerprinted artifact missing: pack/${entry.path}`,\n name: m.name,\n };\n }\n const actualHash = sha256File(artifactPath);\n if (actualHash !== entry.sha256) {\n // research.yaml is always modified by freeze AFTER the receipt is written.\n // Its receipt hash reflects the pre-freeze state by design — soft-warn, do not fail.\n if (entry.path === 'research.yaml') {\n softWarnings.push(\n `WARN pack/research.yaml hash reflects pre-freeze state (known: freeze writes frozen_at + status after fingerprinting)`,\n );\n verified++;\n continue;\n }\n return {\n pass: false,\n reason: `Hash mismatch for pack/${entry.path}.\\n receipt: ${entry.sha256}\\n actual: ${actualHash}`,\n name: m.name,\n };\n }\n verified++;\n }\n\n return { pass: true, name: m.name, artifactsVerified: verified, softWarnings };\n}\n"],"mappings":";;;;;;;;;;;;AAAA,IAAa,iBAoBA,iBAOA,uBAOA,mBAOA,oBAOA,uBAOA,sBAOA,qBAUA,wBAUA;AAlFb;AAAA;AAAA;AAAO,IAAM,kBAAN,cAA8B,MAAM;AAAA,MACzC,YACE,SACgB,MAC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EAAE,OAAO,eAAe;AAAA,CAAI;AACrE,gBAAQ,OAAO,MAAM,oBAAoB,EAAE,sBAAsB,MAAM,GAAG,EAAE,CAAC;AAAA,CAAK;AAAA,MACpF;AACA;AAAA,IACF;AACA,YAAQ,OAAO,MAAM;AAAA,CAAsB;AAC3C,YAAQ,OAAO,MAAM,oBAAoB,OAAO,WAAW;AAAA,CAAI;AAC/D,YAAQ,OAAO,MAAM,oBAAoB,OAAO,aAAa,MAAM;AAAA,CAAI;AACvE,eAAW,KAAK,OAAO,aAAc,SAAQ,OAAO,MAAM,OAAO,CAAC;AAAA,CAAI;AACtE,YAAQ,OAAO,MAAM,oBAAoB,OAAO,eAAe,SAAS,MAAM;AAAA,CAAI;AAClF,QAAI,OAAO,SAAS,SAAS,GAAG;AAC9B,cAAQ,OAAO,MAAM;AAAA;AAAA,CAAe;AACpC,iBAAW,KAAK,OAAO,SAAU,SAAQ,OAAO,MAAM,OAAO,CAAC;AAAA,CAAI;AAAA,IACpE;AACA,QAAI,CAAC,OAAO,aAAc,SAAQ,WAAW;AAAA,EAC/C,SAAS,KAAK;AACZ,gBAAY,GAAG;AAAA,EACjB;AACF,CAAC;AAEH,QAAQ,WAAW,QAAQ,IAAI;","names":["z","init_schema","mkdir","readFile","writeFile","existsSync","join","resolve","yamlStringify","init_scaffold","init_schema","init_scaffold","init_schema","mkdir","writeFile","join","URL","receipt","readFile","URL","title","asserts","keyPoints","z","init_schema","mkdir","readFile","writeFile","existsSync","join","init_schema","existsSync","join","resolve","z","init_schema","existsSync","mkdir","readFile","writeFile","dirname","join","excerpts","origin","init_schema","init_schema","init_schema","init_heuristic","DEFAULT_HOST","DEFAULT_MODEL","SYSTEM_PROMPT","init_ollama_intern","init_extractors","init_heuristic","init_ollama_intern","z","init_schema","existsSync","appendFile","mkdir","readFile","writeFile","join","resolve","receipt","init_schema","init_extractors","z","init_schema","existsSync","mkdir","readFile","writeFile","join","resolve","normalize","audit","init_schema","init_schema","init_extractors","init_schema","z","init_schema","init_heuristic","DEFAULT_HOST","DEFAULT_MODEL","DEFAULT_TIMEOUT_MS","SYSTEM_PROMPT","init_ollama_intern","init_heuristic","init_ollama_intern","z","init_schema","existsSync","createHash","mkdir","readFile","writeFile","join","resolve","readClaims","buildMarkdown","init_run","init_schema","createHash","existsSync","appendFile","readFile","writeFile","join","resolve","readTriagedClaimIds","md","init_schema","init_heuristic","init_ollama_intern","z","appendFile","readFile","existsSync","join","map","resolve","candidatesPath","init_schema","z","init_schema","map","buildEffectiveStatuses","map","init_markdown","z","init_schema","existsSync","mkdir","readFile","writeFile","join","resolve","yamlParse","yamlStringify","readSourceCards","readdir","buildEffectiveStatuses","map","loadResearchYaml","init_run","init_schema","init_markdown","init_run","init_markdown","init_schema","existsSync","mkdir","readFile","writeFile","join","z","normalize","EVIDENCE_EXCERPT_JOIN","init_heuristic","asEnum","DEFAULT_HOST","DEFAULT_MODEL","DEFAULT_TIMEOUT_MS","VALID_SEVERITIES","VALID_CONFIDENCES","init_ollama_intern","init_heuristic","init_ollama_intern","init_markdown","createHash","existsSync","appendFile","mkdir","readFile","writeFile","join","resolve","yamlParse","yamlStringify","readJsonl","readSourceCards","readdir","map","loadResearchYaml","readTriagedClaimIds","init_run","init_schema","init_markdown","existsSync","mkdir","readFile","writeFile","appendFile","join","resolve","yamlParse","yamlStringify","init_schema","init_markdown","init_run","init_markdown","init_schema","init_schema","existsSync","dirname","join","init_schema","existsSync","readFile","join","resolve","relative","createHash","yamlParse","readSourceCards","readdir","readGateResult","gate","init_schema","existsSync","resolve","existsSync","mkdir","writeFile","dirname","join","resolve","resolve","readFile","init_schema","z","init_schema","createHash","map","buildEffectiveStatuses","review","gate","z","init_schema","init_markdown","existsSync","mkdir","readFile","writeFile","join","resolve","yamlParse","loadResearchYaml","readJsonl","gate","init_run","init_schema","init_markdown","init_run","init_markdown","init_schema","createHash","latestDecisionByClaim","map","handoff","init_derive","z","init_schema","map","s","init_markdown","existsSync","mkdir","readFile","writeFile","join","resolve","yamlParse","readJsonl","readSourceCards","readdir","handoff","map","relPath","init_run","init_schema","init_derive","init_markdown","init_run","init_derive","init_markdown","init_schema","packId","latestDecisionByClaim","buildEffectiveStatuses","map","buildEffectiveDispositions","review","handoff","buildNextActions","z","HandoffModeSchema","init_schema","init_markdown","existsSync","mkdir","readFile","writeFile","join","resolve","yamlParse","readJsonl","readSourceCards","readdir","readGate","gate","handoff","init_run","init_schema","init_markdown","init_run","init_markdown","init_schema","existsSync","readFile","stat","createHash","join","fileSha256","init_checks","init_markdown","z","init_schema","existsSync","mkdir","readFile","readdir","writeFile","createHash","join","resolve","yamlParse","yamlStringify","packId","handoff","init_run","init_schema","init_checks","init_markdown","init_run","init_markdown","init_schema","z","init_schema","existsSync","mkdir","readFile","readdir","writeFile","dirname","join","relative","resolve","yamlParse","yamlStringify","init_run","init_schema","existsSync","mkdir","rename","writeFile","dirname","join","posix","relative","resolve","sep","z","posixify","moveIfExists","buildReceiptMarkdown","init_review","init_schema","init_run","init_review","init_schema","init_run","init_schema","z","init_schema","asString","asStringOrNull","DEFAULT_HOST","DEFAULT_MODEL","DEFAULT_TIMEOUT_MS","SYSTEM_PROMPT","existsSync","createHash","mkdir","readFile","writeFile","appendFile","join","resolve","yamlParse","query","init_run","init_schema","init_run","init_schema","z","init_schema","existsSync","mkdir","readFile","writeFile","join","resolve","yamlParse","readJsonl","countWords","gate","init_run","init_schema","init_run","init_schema","existsSync","mkdirSync","writeFileSync","readFileSync","readdirSync","join","resolve","createHash","existsSync","join","z","z","z","createHash","existsSync","join","mkdirSync","join","createHash","readFileSync","existsSync","join","createHash","readFileSync","join","existsSync","resolve","existsSync","join","readdirSync","finalReportPath","finalReport","readFileSync","readme","mkdirSync","writeFileSync","resolve","ResearchYamlSchema"]}