From bbf5d73af7a2a64d1af704b97930e2167541bb5a Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 23 Jul 2026 16:57:22 +0000 Subject: [PATCH 1/3] =?UTF-8?q?chore(release):=20add=20CHANGELOG,=20bump?= =?UTF-8?q?=20to=200.2.0,=20tag=E2=86=92release=20CI?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Version had drifted to 0.1.7 with no tags past v0.1.0a3 and no changelog. Establish release hygiene: - CHANGELOG.md (Keep a Changelog + SemVer), starting at 0.2.0 which captures the cross-run substrate, Hamilton lineage, Layer-2 metrics, and the measure catalog shipped on this branch. - Bump pyproject 0.1.7 -> 0.2.0. - release.yml: on a v* tag, verify the tag matches pyproject, build sdist+wheel, and open a GitHub Release whose notes are the matching CHANGELOG section. - Document the release flow in CONTRIBUTING. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01Joez4MiYjd6owPcRQNcKrv --- .github/workflows/release.yml | 58 +++++++++++++++++++++++++++++++++++ CHANGELOG.md | 40 ++++++++++++++++++++++++ CONTRIBUTING.md | 15 +++++++++ pyproject.toml | 2 +- 4 files changed, 114 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/release.yml create mode 100644 CHANGELOG.md diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..0a38534 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,58 @@ +name: Release + +# Cut a GitHub Release when a version tag is pushed. The release notes are the +# matching section of CHANGELOG.md, and the built sdist + wheel are attached. +# Flow: bump pyproject version -> stamp the CHANGELOG section -> merge to main +# -> `git tag vX.Y.Z && git push origin vX.Y.Z`. +on: + push: + tags: ["v*"] + +permissions: + contents: write + +jobs: + release: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: astral-sh/setup-uv@v3 + with: + enable-cache: true + - name: Set up Python + run: uv python install 3.12 + + - name: Guard — tag matches pyproject version + # A tag whose version disagrees with pyproject is a mistake; fail loudly + # rather than publish a mislabelled release. + run: | + tag_version="${GITHUB_REF_NAME#v}" + proj_version="$(uv run python -c 'import tomllib,pathlib; print(tomllib.loads(pathlib.Path("pyproject.toml").read_text())["project"]["version"])')" + if [ "$tag_version" != "$proj_version" ]; then + echo "::error::tag $GITHUB_REF_NAME -> $tag_version but pyproject version is $proj_version" + exit 1 + fi + + - name: Build sdist + wheel + run: uv build + + - name: Extract changelog section + # Print the body of the "## []" section, stopping at the next + # "## [" header. Falls back to a stub if the section is missing. + run: | + version="${GITHUB_REF_NAME#v}" + awk -v ver="$version" ' + index($0, "## [" ver "]") == 1 { flag=1; next } + flag && index($0, "## [") == 1 { exit } + flag { print } + ' CHANGELOG.md > release-notes.md + if [ ! -s release-notes.md ]; then + echo "Release $version. See CHANGELOG.md." > release-notes.md + fi + + - name: Create GitHub release + uses: softprops/action-gh-release@v2 + with: + body_path: release-notes.md + files: dist/* + fail_on_unmatched_files: true diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..448e7eb --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,40 @@ +# Changelog + +All notable changes to insight-kit are documented here. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +While the project is pre-1.0 (Alpha), minor versions may carry breaking changes; +each such change is called out under **Changed** or **Removed**. + +Releases up to and including `0.1.7` predate this file; their history lives in +the git log. This changelog starts at `0.2.0`. + +## [Unreleased] + +## [0.2.0] - 2026-07-23 + +### Added + +- **Cross-run workspace substrate** (`platform.gate.workspace`): a run manifest + (`new_run_dir`, `seal_run`, `list_runs`, `reindex_runs`), claim-history queries + (`claim_history`, `claim_by_id`), and standing-verdict resolution + (`standing_refutations`). Claims now accumulate and are auditable across runs, + not just within one. +- **Republish guard** (`guard_republished_claims`): surfaces current-run claims + whose `claim_id` carries a standing refutation from a sealed run, emitting a + critic-tier claim and applying a high-severity critique. Surface-never-block: + the guard returns findings rather than raising. +- **Hamilton graph lineage**: the adapter stamps each metric claim's upstream + closure, and the gate exposes `lineage_of` / `trace_to_rows` to read the + provenance chain back from a sealed bundle. +- **Layer-2 derived metrics**: a metric computed from other metrics' values + lands as `payload` provenance and records the upstream claims it was derived + from as `input_claims` (claim→claim data lineage), so a derived number still + traces back to what produced it. +- **Measure catalog** (`integrations.hamilton.catalog`): a static semantic layer + read from the compiled Hamilton graph and `@tag` metadata (no execution, no + data). Distinguishes base from derived measures, advertises the `claim_id` + each will emit, and is self-authoring — `authoring_guide()` / `format_catalog()` + carry the `ik_*` tag contract and the composition rule an agent needs to add a + measure. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ca1d886..caf0bba 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -101,6 +101,21 @@ gitleaks pre-commit hook catches most secrets, but machine-specific paths (`/Users/...`, sibling-repo names) should be parameterized via env vars or fixtures. +## Releasing + +Releases are cut from tags by `.github/workflows/release.yml`. To ship a version: + +1. Bump `version` in `pyproject.toml`. +2. Move the accumulated notes under `## [Unreleased]` in `CHANGELOG.md` into a + new `## [X.Y.Z] - YYYY-MM-DD` section (leave `## [Unreleased]` empty above it). +3. Merge to `main`. +4. Tag and push: `git tag vX.Y.Z && git push origin vX.Y.Z`. + +The workflow verifies the tag matches `pyproject`, builds the sdist + wheel, and +opens a GitHub Release whose notes are the matching `CHANGELOG.md` section with +the artifacts attached. SemVer applies; pre-1.0, a minor may carry a breaking +change (called out under **Changed**/**Removed** in the changelog). + ## License By contributing, you agree your contributions are licensed under the diff --git a/pyproject.toml b/pyproject.toml index 9ef0035..9d6ea58 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "insight-kit" -version = "0.1.7" +version = "0.2.0" description = "Provenance-first agent insights kit — Run + Claim + DAG primitives for traceable analyst/critic loops." readme = "README.md" license = { text = "MIT" } From b04c4cc83af2e9f347b668378c20e8bd1dcaaaa9 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 23 Jul 2026 17:05:35 +0000 Subject: [PATCH 2/3] feat(workspace): refutation contagion guard (guard_refuted_inputs) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The republish guard answers "was THIS claim refuted?". guard_refuted_inputs extends that one edge outward: "does this claim's input_claims chain reach anything refuted?". - A claim is refuted-at-the-source when its claim_id carries a standing refutation from a sealed run (source "standing") or a non-guard critic refutes its record in the current run (source "in_run"). - Taint propagates transitively along input_claims (a DAG). A claim that is itself refuted-at-the-source is a taint SOURCE, not a contagion finding — the republish guard / the refuting critic already surfaces it. - Per contaminated draft/published claim: emit a marked contagion critic refuting it (carrying the ancestor provenance + the input_claims path) and apply a high-severity critique (V16 record-then-enforce). - Idempotent: deterministic per-target critic id, and the guard's own critics are excluded from the in_run seed so a contagion critic can never re-seed its own target and shrink the findings list. Surface-never-block. Exports guard_refuted_inputs + ContagionFinding from the gate. 7 tests cover standing + in_run sources, transitive propagation, published downgrade, supported-ancestor clears, clean-chain no-op, idempotency, and the self-reseed regression. Full suite 931 passed. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01Joez4MiYjd6owPcRQNcKrv --- CHANGELOG.md | 7 + src/insight_kit/platform/gate/__init__.py | 9 +- src/insight_kit/platform/gate/workspace.py | 244 +++++++++++++++++++++ tests/platform/gate/test_workspace.py | 174 +++++++++++++++ uv.lock | 2 +- 5 files changed, 433 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 448e7eb..1cd537b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,13 @@ the git log. This changelog starts at `0.2.0`. whose `claim_id` carries a standing refutation from a sealed run, emitting a critic-tier claim and applying a high-severity critique. Surface-never-block: the guard returns findings rather than raising. +- **Refutation contagion** (`guard_refuted_inputs`): extends the republish guard + one edge outward — flags current-run claims that *derive* (transitively, via + `input_claims`) from a refuted claim, whether the refutation is standing + (cross-run) or in-run. Emits a marked contagion critic and critique per + contaminated claim; idempotent and surface-never-block like the republish + guard. A refuted number no longer taints only itself — everything computed + from it is flagged too. - **Hamilton graph lineage**: the adapter stamps each metric claim's upstream closure, and the gate exposes `lineage_of` / `trace_to_rows` to read the provenance chain back from a sealed bundle. diff --git a/src/insight_kit/platform/gate/__init__.py b/src/insight_kit/platform/gate/__init__.py index a27acc1..c539552 100644 --- a/src/insight_kit/platform/gate/__init__.py +++ b/src/insight_kit/platform/gate/__init__.py @@ -41,8 +41,9 @@ Cross-run workspace substrate (I.workspace): dated run dirs, runs.jsonl manifest, claim history queries, persistent refuted-claim republish guard: new_run_dir, seal_run, list_runs, reindex_runs, claim_history, claim_by_id, - standing_refutations, guard_republished_claims, ClaimSighting, RunEntry, - RepublishFinding, RunNotSealedError, WorkspaceNotFoundError + standing_refutations, guard_republished_claims, guard_refuted_inputs + (refutation contagion along input_claims), ClaimSighting, RunEntry, + RepublishFinding, ContagionFinding, RunNotSealedError, WorkspaceNotFoundError Key types: ClaimTier, FieldEntry, CoverageInfo, SelectionParams, IntentPayload, RealizedPayload @@ -138,12 +139,14 @@ ) from insight_kit.platform.gate.workspace import ( ClaimSighting, + ContagionFinding, RepublishFinding, RunEntry, RunNotSealedError, WorkspaceNotFoundError, claim_by_id, claim_history, + guard_refuted_inputs, guard_republished_claims, list_runs, new_run_dir, @@ -164,6 +167,7 @@ "ClaimSighting", "ClaimTier", "ComposeError", + "ContagionFinding", "CoverageInfo", "CrossCheckResult", "FieldEntry", @@ -203,6 +207,7 @@ "emit_reconciliation_critique", "endpoint_index_path", "finalizeRun", + "guard_refuted_inputs", "guard_republished_claims", "ik_acquire", "ik_claim_emit", diff --git a/src/insight_kit/platform/gate/workspace.py b/src/insight_kit/platform/gate/workspace.py index a5b60e7..852b345 100644 --- a/src/insight_kit/platform/gate/workspace.py +++ b/src/insight_kit/platform/gate/workspace.py @@ -700,3 +700,247 @@ def guard_republished_claims( ) return findings + + +# --------------------------------------------------------------------------- +# guard_refuted_inputs — refutation contagion along input_claims (T29 + V16) +# --------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class ContagionFinding: + """One claim contaminated by deriving from a refuted claim. + + The contaminated claim was NOT itself refuted — it inherited the taint + through its input_claims chain, and would otherwise pass unflagged. path + is the record_id chain from the contaminated record up to the refuted + ancestor (both ends inclusive). source is why the ancestor counts as + refuted: "standing" (a standing refutation carried from a sealed run) or + "in_run" (a non-guard critic refuted it in THIS run). critic_record_id is + the guard's critic claim (None if its emit was rejected — the critique + still applied). downgrade_required mirrors the republish guard: True when + the V16 gate fired on the contaminated record (published tier / board). + """ + + claim_id: str + record_id: str + tier: str + refuted_ancestor_claim_id: str + refuted_ancestor_record_id: str + source: str + path: list[str] + critic_record_id: str | None + downgrade_required: bool + + +def _is_contagion_critic(record: dict[str, Any]) -> bool: + """True for a critic this guard emitted (marked guard="refuted_inputs"). + + Such critics refute the very claims this guard flags, so they must be + excluded when building the in_run refuted set — otherwise a contagion + critic would re-seed its own target and the findings list would shrink on + re-invocation, breaking idempotency. + """ + entry = (record.get("fields") or {}).get("guard") + return isinstance(entry, dict) and entry.get("value") == "refuted_inputs" + + +def _contagion_critic_claim_id(claim_id: str, ancestor_record_id: str, record_id: str) -> str: + """Deterministic gate-valid claim_id for a contagion critic. + + Seeded distinctly ("contagion|…") from the republish guard so the two + guards never mint the same id for one target. Salted with the tainted + ancestor and the target record so the id is stable across re-invocations + (idempotency) yet distinct per (contaminated record, ancestor). + """ + match = _NAMESPACE_RE.match(claim_id) + namespace = match.group(0) if match else "IK" + seed = f"contagion|{claim_id}|{ancestor_record_id}|{record_id}" + return mint_claim_id(namespace, "X", seed, digits=9) + + +def guard_refuted_inputs( + workspace_dir: Path | str, + *, + run_state: RunState, + run_dir: Path | str, +) -> list[ContagionFinding]: + """Flag current-run claims that DERIVE from a refuted claim (contagion). + + The republish guard answers "was THIS claim refuted?". This guard extends + that one edge outward: "does this claim's input_claims chain reach anything + refuted?". A claim is refuted-at-the-source when either + + * its claim_id carries a standing refutation from a SEALED run + (source "standing"), or + * a non-guard critic in the CURRENT run refutes its record (source + "in_run"). + + Taint propagates transitively along input_claims (a DAG): if U is refuted + and D lists U in input_claims, D is contaminated; if E derives from D, E is + contaminated too. A claim that is ITSELF refuted-at-the-source is not a + contagion finding — the republish guard or the refuting critic already + surfaces it — it only acts as a source of taint for its descendants. + + For each contaminated draft/published claim the guard, mirroring + guard_republished_claims: + + 1. emits a critic-tier claim refuting the contaminated record, carrying + the refuted ancestor's provenance and the input_claims path, and + 2. applies a severity=high critique via apply_critique (V16 record-then- + enforce); a CritiqueGateError surfaces as downgrade_required=True. + + Idempotent: the contagion critic's claim_id is deterministic per + (contaminated record, ancestor), and the guard's own critics are excluded + from the in_run refuted set, so a re-invocation reuses the existing critic, + re-critiques nothing, spends no fix-round budget, and returns an equal + findings list. + + SURFACE, NEVER BLOCK: returns findings; raises nothing for a contagion hit. + """ + run_dir = Path(run_dir) + standing = standing_refutations(workspace_dir) + + # Snapshot — emitting contagion critics appends to run_state.records. + snapshot = list(run_state.records) + + # Index every current-run claim record once. + record_by_id: dict[str, dict[str, Any]] = {} + for ref in snapshot: + if ref.record_type != "claim": + continue + record_by_id[ref.record_id] = read_record(run_dir, ref.record_id) + + # Refuted seed: record_ids that count as refuted-at-the-source, mapped to + # why. standing is assigned first (it wins over in_run for the same id); + # in_run skips this guard's own critics so a contagion critic can't re-seed + # its own target. + seed_source: dict[str, str] = {} + for rid, record in record_by_id.items(): + if str(record.get("claim_id")) in standing: + seed_source[rid] = "standing" + for record in record_by_id.values(): + if record.get("tier") != "critic" or _is_contagion_critic(record): + continue + for target_id in record.get("refutes") or []: + seed_source.setdefault(target_id, "in_run") + + # Transitive reach: memoized DFS up input_claims, returning the shortest + # path from a record to its nearest refuted ancestor (both inclusive), or + # None. Deterministic — inputs visited in sorted order. input_claims is a + # DAG (claims reference earlier-emitted claims); on_stack guards the + # pathological cycle defensively. + memo: dict[str, list[str] | None] = {} + + def _reach(rid: str, on_stack: frozenset[str]) -> list[str] | None: + if rid in memo: + return memo[rid] + if rid in on_stack: + return None + record = record_by_id.get(rid) + if record is None: + memo[rid] = None + return None + best: list[str] | None = None + for up in sorted(record.get("input_claims") or []): + if up in seed_source: + cand: list[str] | None = [rid, up] + else: + sub = _reach(up, on_stack | {rid}) + cand = [rid, *sub] if sub is not None else None + if cand is not None and (best is None or len(cand) < len(best)): + best = cand + memo[rid] = best + return best + + # Idempotency lookup: stored claim_id -> record_id for the snapshot. + record_id_by_claim_id: dict[str, str] = { + str(rec.get("claim_id")): rid for rid, rec in record_by_id.items() + } + + findings: list[ContagionFinding] = [] + for rid, record in record_by_id.items(): + tier = str(record.get("tier")) + if tier not in _GUARDED_TIERS or rid in seed_source: + continue + path = _reach(rid, frozenset()) + if path is None: + continue + + ancestor_rid = path[-1] + ancestor_claim_id = str(record_by_id[ancestor_rid].get("claim_id")) + source = seed_source[ancestor_rid] + claim_id = str(record.get("claim_id")) + audience = record.get("audience") + reason = ( + f"claim_id {claim_id} derives (via input_claims) from refuted claim " + f"{ancestor_claim_id} [{source}]; the derivation is contaminated until the " + "ancestor's refutation is superseded" + ) + + critic_claim_id = _contagion_critic_claim_id(claim_id, ancestor_rid, rid) + existing_critic_id = record_id_by_claim_id.get(critic_claim_id) + if existing_critic_id is not None: + critic_record_id: str | None = existing_critic_id + downgrade_required = tier == "published" or audience == "board" + else: + try: + critic_ref = ik_claim_emit( + critic_claim_id, + { + "checked": claim_id, + "guard": "refuted_inputs", + "refuted_ancestor_claim_id": ancestor_claim_id, + "refuted_ancestor_record_id": ancestor_rid, + "source": source, + "path": list(path), + "reason": reason, + "passed": False, + }, + tier="critic", + refutes=[rid], + run_state=run_state, + run_dir=run_dir, + ) + critic_record_id = critic_ref.record_id + except LayerAValidationError: + critic_record_id = None + + downgrade_required = False + saved_rounds = run_state.critiqueRounds + try: + gate_result = apply_critique( + run_state=run_state, + record_id=rid, + record_type="claim", + tier=tier, + audience=audience, + critique=CritiqueState.open( + severity="high", + reason=reason, + critic_id=critic_record_id, + target_record_id=rid, + ), + run_dir=run_dir, + ) + downgrade_required = bool(gate_result.get("downgraded")) + except CritiqueGateError: + downgrade_required = True + finally: + run_state.critiqueRounds = saved_rounds + + findings.append( + ContagionFinding( + claim_id=claim_id, + record_id=rid, + tier=tier, + refuted_ancestor_claim_id=ancestor_claim_id, + refuted_ancestor_record_id=ancestor_rid, + source=source, + path=list(path), + critic_record_id=critic_record_id, + downgrade_required=downgrade_required, + ) + ) + + return findings diff --git a/tests/platform/gate/test_workspace.py b/tests/platform/gate/test_workspace.py index 964a6ff..8630ab9 100644 --- a/tests/platform/gate/test_workspace.py +++ b/tests/platform/gate/test_workspace.py @@ -26,6 +26,7 @@ claim_by_id, claim_history, emit_reconciliation_critique, + guard_refuted_inputs, guard_republished_claims, ik_claim_emit, list_runs, @@ -761,3 +762,176 @@ def test_nonexistent_workspace_raises_typed_error(tmp_path: Path) -> None: rs = RunState(run_dir=run_dir) with pytest.raises(WorkspaceNotFoundError): guard_republished_claims(missing, run_state=rs, run_dir=run_dir) + + +# --------------------------------------------------------------------------- +# 19. guard_refuted_inputs — refutation contagion along input_claims +# --------------------------------------------------------------------------- + + +class TestGuardRefutedInputs: + def test_derived_from_standing_refutation_is_flagged(self, tmp_path: Path) -> None: + # r1 refuted DEMO-D-010 (a base measure). The current run republishes it + # AND stands a derived metric on it. + _sealed_run(tmp_path, "r1", "DEMO-D-010", verdict="refuted") + run_dir, rs = _current_run(tmp_path) + base = ik_claim_emit("DEMO-D-010", {"metric": 5}, run_state=rs, run_dir=run_dir) + derived = ik_claim_emit( + "DEMO-D-020", + {"metric": 2}, + input_claims=[base.record_id], + run_state=rs, + run_dir=run_dir, + ) + + findings = guard_refuted_inputs(tmp_path, run_state=rs, run_dir=run_dir) + + # Only the DERIVED claim is a contagion finding: the republished base is + # the republish guard's job, and here acts only as a taint source. + assert len(findings) == 1 + f = findings[0] + assert f.claim_id == "DEMO-D-020" + assert f.record_id == derived.record_id + assert f.refuted_ancestor_claim_id == "DEMO-D-010" + assert f.refuted_ancestor_record_id == base.record_id + assert f.source == "standing" + assert f.path == [derived.record_id, base.record_id] + assert f.tier == "draft" + assert f.downgrade_required is False + assert f.critic_record_id is not None + + critic = read_record(run_dir, f.critic_record_id) + assert critic["tier"] == "critic" + assert critic["refutes"] == [derived.record_id] + assert critic["fields"]["guard"]["value"] == "refuted_inputs" + assert critic["fields"]["checked"]["value"] == "DEMO-D-020" + assert critic["fields"]["refuted_ancestor_claim_id"]["value"] == "DEMO-D-010" + assert critic["fields"]["source"]["value"] == "standing" + assert critic["fields"]["path"]["value"] == [derived.record_id, base.record_id] + assert critic["fields"]["passed"]["value"] is False + + # V16 record-then-enforce: the critique landed on the derived record. + event_log = run_dir / "records" / derived.record_id / "events" / "critique.jsonl" + assert event_log.exists() + + def test_in_run_refutation_propagates_transitively(self, tmp_path: Path) -> None: + # No standing refutation; a genuine critic refutes the base THIS run. + # The taint must reach both the direct and the transitive derivative. + run_dir, rs = _current_run(tmp_path) + base = ik_claim_emit("DEMO-D-010", {"metric": 5}, run_state=rs, run_dir=run_dir) + mid = ik_claim_emit( + "DEMO-D-020", {"metric": 2}, input_claims=[base.record_id], run_state=rs, run_dir=run_dir + ) + top = ik_claim_emit( + "DEMO-D-030", {"metric": 1}, input_claims=[mid.record_id], run_state=rs, run_dir=run_dir + ) + ik_claim_emit( + "DEMO-X-900", + {"passed": False}, + tier="critic", + refutes=[base.record_id], + run_state=rs, + run_dir=run_dir, + ) + + findings = guard_refuted_inputs(tmp_path, run_state=rs, run_dir=run_dir) + flagged = {f.claim_id: f for f in findings} + + # base is directly refuted -> NOT a contagion finding; mid + top inherit. + assert set(flagged) == {"DEMO-D-020", "DEMO-D-030"} + assert flagged["DEMO-D-020"].source == "in_run" + assert flagged["DEMO-D-020"].path == [mid.record_id, base.record_id] + assert flagged["DEMO-D-030"].path == [top.record_id, mid.record_id, base.record_id] + assert flagged["DEMO-D-030"].refuted_ancestor_record_id == base.record_id + + def test_clean_chain_no_findings_no_critic(self, tmp_path: Path) -> None: + run_dir, rs = _current_run(tmp_path) + base = ik_claim_emit("DEMO-D-010", {"metric": 5}, run_state=rs, run_dir=run_dir) + ik_claim_emit( + "DEMO-D-020", {"metric": 2}, input_claims=[base.record_id], run_state=rs, run_dir=run_dir + ) + before = len(rs.records) + + findings = guard_refuted_inputs(tmp_path, run_state=rs, run_dir=run_dir) + + assert findings == [] + assert len(rs.records) == before # no critic emitted + + def test_idempotent_reinvocation(self, tmp_path: Path) -> None: + _sealed_run(tmp_path, "r1", "DEMO-D-010", verdict="refuted") + run_dir, rs = _current_run(tmp_path) + base = ik_claim_emit("DEMO-D-010", {"metric": 5}, run_state=rs, run_dir=run_dir) + ik_claim_emit( + "DEMO-D-020", {"metric": 2}, input_claims=[base.record_id], run_state=rs, run_dir=run_dir + ) + + first = guard_refuted_inputs(tmp_path, run_state=rs, run_dir=run_dir) + records_after_first = len(rs.records) + rounds_after_first = rs.critiqueRounds + second = guard_refuted_inputs(tmp_path, run_state=rs, run_dir=run_dir) + + assert [f.record_id for f in first] == [f.record_id for f in second] + assert [f.critic_record_id for f in first] == [f.critic_record_id for f in second] + assert len(rs.records) == records_after_first # no second critic emission + assert rs.critiqueRounds == rounds_after_first # no fix-round budget spent + + def test_published_derivative_requires_downgrade(self, tmp_path: Path) -> None: + _sealed_run(tmp_path, "r1", "DEMO-D-010", verdict="refuted") + run_dir, rs = _current_run(tmp_path, publishable=True) + base = ik_claim_emit( + "DEMO-D-010", {"metric": 5}, run_state=rs, run_dir=run_dir, input_data=b"rows" + ) + ik_claim_emit( + "DEMO-D-020", + {"metric": 2}, + tier="published", + input_claims=[base.record_id], + run_state=rs, + run_dir=run_dir, + input_data=b"rows2", + ) + + findings = guard_refuted_inputs(tmp_path, run_state=rs, run_dir=run_dir) + f = next(f for f in findings if f.claim_id == "DEMO-D-020") + + assert f.tier == "published" + assert f.downgrade_required is True + + def test_supported_ancestor_is_not_contagious(self, tmp_path: Path) -> None: + # r1 refuted, r2 supported -> the ancestor's refutation is cleared, so a + # derivative in the current run must NOT be flagged. + _sealed_run(tmp_path, "r1", "DEMO-D-010", verdict="refuted") + _sealed_run(tmp_path, "r2", "DEMO-D-010", verdict="supported") + run_dir, rs = _current_run(tmp_path) + base = ik_claim_emit("DEMO-D-010", {"metric": 5}, run_state=rs, run_dir=run_dir) + ik_claim_emit( + "DEMO-D-020", {"metric": 2}, input_claims=[base.record_id], run_state=rs, run_dir=run_dir + ) + + assert guard_refuted_inputs(tmp_path, run_state=rs, run_dir=run_dir) == [] + + def test_guard_critic_does_not_reseed_itself(self, tmp_path: Path) -> None: + # Regression for the self-reseed idempotency hole: the contagion critic + # refutes the derived claim, but must be excluded from the in_run seed so + # a re-invocation does not reclassify the derived claim as a source and + # shrink the findings list. + run_dir, rs = _current_run(tmp_path) + base = ik_claim_emit("DEMO-D-010", {"metric": 5}, run_state=rs, run_dir=run_dir) + ik_claim_emit( + "DEMO-D-020", {"metric": 2}, input_claims=[base.record_id], run_state=rs, run_dir=run_dir + ) + ik_claim_emit( + "DEMO-X-900", + {"passed": False}, + tier="critic", + refutes=[base.record_id], + run_state=rs, + run_dir=run_dir, + ) + + first = guard_refuted_inputs(tmp_path, run_state=rs, run_dir=run_dir) + second = guard_refuted_inputs(tmp_path, run_state=rs, run_dir=run_dir) + + assert {f.claim_id for f in first} == {"DEMO-D-020"} + assert {f.claim_id for f in second} == {"DEMO-D-020"} # unchanged: no shrink + assert [f.critic_record_id for f in first] == [f.critic_record_id for f in second] diff --git a/uv.lock b/uv.lock index e8ead18..fbb2c7d 100644 --- a/uv.lock +++ b/uv.lock @@ -435,7 +435,7 @@ wheels = [ [[package]] name = "insight-kit" -version = "0.1.7" +version = "0.2.0" source = { editable = "." } dependencies = [ { name = "duckdb" }, From 623cfc5b33be07b7c3d0a974abc1122cacb107c2 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 23 Jul 2026 17:12:22 +0000 Subject: [PATCH 3/3] feat(skills): analyst + critic-council skills over a harness-agnostic method MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Package insight-kit's usage as directly-invocable Claude Code skills, keeping the method separate from the binding so a pi binding can reuse it. - docs/method/: the harness-agnostic method. analyst-loop.md (discover → compose → run → seal → verify) and critic-council.md (mechanical vs semantic audit, perspective-diverse lenses, majority-refute kill rule, verdicts as gated critic claims + contagion propagation). - .claude/skills/insight-kit-analyst/: producer binding + a verify_run.py self-check helper (provenance + lineage + standing-refutation report). - .claude/skills/insight-kit-critic/: critic-council binding — dispatches the archetypes, applies the kill rule, records verdicts via ik_claim_emit and propagates them with guard_refuted_inputs. - .claude/agents/ik-critic-{correctness,methodology,staleness,support}.md: the four archetype lenses as first-class subagents, each returning a stance. Producer and critic are deliberately different agents — a producer must not grade its own homework. Gate logic stays L1 Python; archetype prompts stay data; the binding stays thin. verify_run.py exercised against a sealed growth_demo run. Full suite 931 passed. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01Joez4MiYjd6owPcRQNcKrv --- .claude/agents/ik-critic-correctness.md | 37 ++++++ .claude/agents/ik-critic-methodology.md | 41 +++++++ .claude/agents/ik-critic-staleness.md | 36 ++++++ .claude/agents/ik-critic-support.md | 39 ++++++ .claude/skills/insight-kit-analyst/SKILL.md | 113 ++++++++++++++++++ .../insight-kit-analyst/scripts/verify_run.py | 85 +++++++++++++ .claude/skills/insight-kit-critic/SKILL.md | 88 ++++++++++++++ CHANGELOG.md | 8 ++ docs/method/analyst-loop.md | 94 +++++++++++++++ docs/method/critic-council.md | 80 +++++++++++++ 10 files changed, 621 insertions(+) create mode 100644 .claude/agents/ik-critic-correctness.md create mode 100644 .claude/agents/ik-critic-methodology.md create mode 100644 .claude/agents/ik-critic-staleness.md create mode 100644 .claude/agents/ik-critic-support.md create mode 100644 .claude/skills/insight-kit-analyst/SKILL.md create mode 100644 .claude/skills/insight-kit-analyst/scripts/verify_run.py create mode 100644 .claude/skills/insight-kit-critic/SKILL.md create mode 100644 docs/method/analyst-loop.md create mode 100644 docs/method/critic-council.md diff --git a/.claude/agents/ik-critic-correctness.md b/.claude/agents/ik-critic-correctness.md new file mode 100644 index 0000000..a425bce --- /dev/null +++ b/.claude/agents/ik-critic-correctness.md @@ -0,0 +1,37 @@ +--- +name: ik-critic-correctness +description: >- + Correctness lens of the insight-kit critic council. Given a sealed run and a + target claim, recompute the number from its traced inputs and check the + identity holds. Returns a refute/pass stance. Dispatched by the + insight-kit-critic skill; not usually invoked directly. +tools: Read, Bash, Grep, Glob +--- + +You are the **Correctness** lens of the insight-kit critic council. Your one job +is to answer: **does this number reconcile against its own traced inputs?** + +The lens is defined in `docs/method/critic-council.md` — read it. You are one of +several independent lenses; do not try to cover the others' concerns. + +Method: +1. Read the target claim record and its lineage. Use `lineage_of(run_dir, + record_id)` and `trace_to_rows(run_dir, record_id)` (via `uv run python`). + Treat the lineage as ground truth — do not question *where* it says the + inputs are, only whether the value follows from them. +2. Recompute: + - **Base claim** (registered_input): recompute the aggregation from the + captured `input_rows` and compare to the claimed value. + - **Derived claim** (payload, has `input_claims`): read the upstream claims' + values and recompute the derivation (e.g. a ratio) from them. +3. A mismatch beyond trivial float tolerance is a refutation. If the inputs + cannot be traced at all, that is also a refutation (an unverifiable number). + +Default to `refute` when you genuinely cannot confirm the identity. + +Return EXACTLY this, nothing else: + +``` +STANCE: refute | pass +REASON: +``` diff --git a/.claude/agents/ik-critic-methodology.md b/.claude/agents/ik-critic-methodology.md new file mode 100644 index 0000000..5478a84 --- /dev/null +++ b/.claude/agents/ik-critic-methodology.md @@ -0,0 +1,41 @@ +--- +name: ik-critic-methodology +description: >- + Methodology lens of the insight-kit critic council. Given a sealed run and a + target claim, judge whether its grain, filters, window, and definition are + sound for what it asserts. Returns a refute/pass stance. Dispatched by the + insight-kit-critic skill; not usually invoked directly. +tools: Read, Bash, Grep, Glob +--- + +You are the **Methodology** lens of the insight-kit critic council. Your one job +is to answer: **is the way this number was computed sound for what it claims?** + +The lens is defined in `docs/method/critic-council.md` — read it. You are one of +several independent lenses; leave arithmetic to the correctness lens and +staleness to the staleness lens. + +Method: +1. Read the target claim's fields: its `statement`, `selection` (grain, filters, + date window, baseline), and — for a derived claim — the grain of every + measure in its `input_claims`. +2. Look for a methodology defect: + - **Grain mismatch** — a derived metric composing measures at different + grains, or a value reported at a grain the data doesn't support. + - **Filter that changes the population** — a filter that silently narrows or + widens who/what is counted versus what the statement implies. + - **Window mismatch** — a date window or baseline that doesn't match the + statement's claim ("last 30 days" computed over 45). + - **Definition drift** — the prose statement doesn't mean what the computed + definition actually measures. +3. Any of these is a refutation. A clean, self-consistent definition passes. + +Default to `refute` when the definition is ambiguous enough that a reader could +reasonably misread what the number means. + +Return EXACTLY this, nothing else: + +``` +STANCE: refute | pass +REASON: +``` diff --git a/.claude/agents/ik-critic-staleness.md b/.claude/agents/ik-critic-staleness.md new file mode 100644 index 0000000..df8be5a --- /dev/null +++ b/.claude/agents/ik-critic-staleness.md @@ -0,0 +1,36 @@ +--- +name: ik-critic-staleness +description: >- + Staleness / contamination lens of the insight-kit critic council. Given a + sealed run and a target claim, check whether it or any of its input_claims + ancestors is standing-refuted. Returns a refute/pass stance. Dispatched by the + insight-kit-critic skill; not usually invoked directly. +tools: Read, Bash, Grep, Glob +--- + +You are the **Staleness / contamination** lens of the insight-kit critic +council. Your one job is to answer: **is this claim contradicted — directly, or +through what it derives from?** + +The lens is defined in `docs/method/critic-council.md` — read it. This lens is +almost entirely mechanical: you are reading standing facts, not forming an +opinion. Trust them. + +Method (via `uv run python`): +1. `standing_refutations(workspace_dir)` — is the target's `claim_id` in the + returned map? If so, it was refuted in a prior sealed run and republished + without a superseding verdict → refute. +2. `guard_refuted_inputs(workspace_dir, run_state=rs, run_dir=run_dir)` on the + run — does any finding name the target `record_id`? If so, it derives (via + `input_claims`) from a refuted claim → refute, and report the `source` + (standing / in_run) and the refuted ancestor from the finding. +3. If neither the claim nor any ancestor carries a standing refutation, pass. + +There is little to be uncertain about here; report exactly what the guards say. + +Return EXACTLY this, nothing else: + +``` +STANCE: refute | pass +REASON: +``` diff --git a/.claude/agents/ik-critic-support.md b/.claude/agents/ik-critic-support.md new file mode 100644 index 0000000..d997d90 --- /dev/null +++ b/.claude/agents/ik-critic-support.md @@ -0,0 +1,39 @@ +--- +name: ik-critic-support +description: >- + Support lens of the insight-kit critic council. Given a sealed run and a + target claim, judge whether it actually backs the conclusion it is attached + to, or is merely decorative. Returns a refute/pass stance. Dispatched by the + insight-kit-critic skill; not usually invoked directly. +tools: Read, Bash, Grep, Glob +--- + +You are the **Support** lens of the insight-kit critic council. Your one job is +to answer: **does this claim actually establish the conclusion it is cited for, +or is it there to lend borrowed weight?** + +The lens is defined in `docs/method/critic-council.md` — read it. You are not +checking whether the number is arithmetically right (correctness lens) or +current (staleness lens); you are checking whether it *earns its place* in the +argument it appears in. + +Method: +1. Follow the claim's role: its `cites` chain, the narrative/report section it + appears in, and any conclusion the surrounding text draws from it. +2. Ask whether the claim, on its own, supports that conclusion: + - Does the metric measure what the conclusion needs it to measure? + - Is a causal or directional conclusion being drawn from a number that is + only descriptive or correlational? + - Is the claim cited to imply a magnitude/trend it doesn't actually show? +3. A claim used to prop up a conclusion it does not establish is a refutation. + A claim whose conclusion follows from it passes. + +Default to `refute` when the leap from the number to the conclusion is larger +than the number can carry on its own. + +Return EXACTLY this, nothing else: + +``` +STANCE: refute | pass +REASON: +``` diff --git a/.claude/skills/insight-kit-analyst/SKILL.md b/.claude/skills/insight-kit-analyst/SKILL.md new file mode 100644 index 0000000..d239ed3 --- /dev/null +++ b/.claude/skills/insight-kit-analyst/SKILL.md @@ -0,0 +1,113 @@ +--- +name: insight-kit-analyst +description: >- + Produce a governed, provenance-tracked metric or number with insight-kit — + the discover → compose → run → seal → verify loop over a Hamilton DAG. Use + this whenever the task is to compute a metric, KPI, ratio, or analytical + number that needs to be trustworthy and auditable: authoring a new measure, + running an analysis through the gate, emitting a claim, or turning a "what is + X" data question into a defensible answer. Trigger it even when the user does + not say "insight-kit" — any request to compute a business number that someone + will act on (CAC, ARPU, payback, conversion, MER, retention, a board figure) + belongs here rather than an ad-hoc pandas snippet, because the whole point is + that the number carries its own lineage back to the rows or upstream claims it + came from. Do NOT use this for auditing or refuting numbers someone else + produced — that is the insight-kit-critic skill. +--- + +# insight-kit: the analyst loop + +Produce a number that carries its own provenance. Every claim this loop emits is +typed, content-addressed, and traceable back to the rows (or the upstream +claims) it came from — so a reader, or a critic, can verify it without trusting +you. Never hand-carry a number that skips the gate. + +The full, harness-agnostic method is in `docs/method/analyst-loop.md`. Read it +if anything below is unclear. The loop is **discover → compose → run → seal → +verify**. `growth_demo` (`src/insight_kit/examples/growth_demo/dag.py`) is the +worked example — mirror its measures when authoring your own. + +## 1. Discover — read the semantic layer first + +Never rebuild a measure that already exists. Read what you can stand on, at what +grain, statically (no execution, no data): + +```python +from insight_kit.integrations.hamilton import catalog, format_catalog +from insight_kit.examples.growth_demo import dag # ← your module(s) + +print(format_catalog(catalog([dag]))) +``` + +`format_catalog` prints the measures (with grain, `claim_id`, base vs derived) +**and** the `@tag` authoring contract, so this one brief tells you both what +exists and how to add one. If a measure at the grain you need already exists, +reference it — don't recompute. + +## 2. Compose — only if the measure doesn't exist + +Author a Hamilton node tagged as a measure. The tag contract and composition +rule come from `authoring_guide()` (also printed by `format_catalog`). The rule +that matters most: + +> **To derive from existing measures, name them as parameters of your node.** +> Hamilton binds each parameter to the upstream node of the same name, and the +> adapter records those measures as `input_claims` (claim→claim provenance) +> automatically. Only compose measures that share the same grain. + +A derived (Layer-2) measure — inputs are other measures' *values*, not rows — +lands as `payload` provenance, backed by its `input_claims` edge rather than a +row fingerprint. That is correct, not a gap. + +## 3. Run — execute through the gate-backed driver + +```python +from insight_kit.platform.gate import RunState, new_run_dir +from insight_kit.integrations.hamilton import build_driver + +run_dir = new_run_dir(workspace_dir) +rs = RunState(run_dir=run_dir) +dr = build_driver(rs, run_dir, [dag]) +dr.execute(["cac_payback_ratio"], inputs={...}) # upstream measures emit too +``` + +Hamilton runs topologically, so upstream measures emit before the downstream +metric. Ask for the final metric; its inputs are gated transitively. + +## 4. Guard, then seal + +Run the two standing guards on the **live** run_state before sealing — they +surface, never block, so read their findings and stop if anything is flagged: + +```python +from insight_kit.platform.gate import ( + guard_republished_claims, guard_refuted_inputs, seal_run, +) + +republished = guard_republished_claims(workspace_dir, run_state=rs, run_dir=run_dir) +contaminated = guard_refuted_inputs(workspace_dir, run_state=rs, run_dir=run_dir) +# If either returns findings, the number stands on refuted ground — address it, +# do not publish over it. + +seal_run(workspace_dir, run_dir, rs) +``` + +## 5. Verify — mechanical self-check + +This step is deterministic (the bundle can't lie), so running it on your own +work is fine — it reports facts, it does not grade quality. Use the bundled +helper: + +```bash +uv run python .claude/skills/insight-kit-analyst/scripts/verify_run.py +``` + +It prints each claim's provenance source and lineage trace and flags any claim +carrying a standing refutation (exit 1 if so). For a single claim, `lineage_of` +/ `trace_to_rows` give the chain directly. + +## What this loop does NOT do + +It does not decide whether the number is *right* or *meaningful* — that is a +judgment call, and a producer must not grade its own homework. Hand a sealed run +to the **insight-kit-critic** skill for the adversarial, semantic audit. diff --git a/.claude/skills/insight-kit-analyst/scripts/verify_run.py b/.claude/skills/insight-kit-analyst/scripts/verify_run.py new file mode 100644 index 0000000..80589a2 --- /dev/null +++ b/.claude/skills/insight-kit-analyst/scripts/verify_run.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python +"""Mechanical self-verify for a sealed insight-kit run. + +Reads facts back out of a sealed run bundle — it does NOT judge whether a number +is *right* (that is the critic's job). For every claim in the run it reports the +provenance source and resolves the lineage trace, then checks each claim_id +against the workspace's standing refutations. Deterministic: the bundle can't +lie, so the producing agent may run this on its own work. + +Usage: + uv run python verify_run.py + +Exit code 0 when every claim's provenance resolves and none carries a standing +refutation; 1 otherwise (so it can gate a pipeline step). + +Note: the republish and contagion guards (guard_republished_claims / +guard_refuted_inputs) act on a LIVE run_state and are meant to run in-flow just +BEFORE sealing. This post-seal script uses standing_refutations for the +read-only staleness equivalent. +""" + +from __future__ import annotations + +import sys +from pathlib import Path + +from insight_kit.platform.gate import list_runs, standing_refutations +from insight_kit.platform.gate.lineage import LineageNotRecordedError, lineage_of +from insight_kit.platform.gate.store import read_record + + +def verify(workspace_dir: Path, run_id: str) -> int: + run_dir = workspace_dir / "runs" / run_id + entry = next((e for e in list_runs(workspace_dir) if e.run_id == run_id), None) + if entry is None: + print(f"FAIL: no sealed run {run_id!r} in workspace {workspace_dir}") + return 1 + + standing = standing_refutations(workspace_dir) + ok = True + print(f"run {run_id}: {len(entry.claims)} claim sightings\n") + + for s in entry.claims: + rec = read_record(run_dir, s.record_id) + source = rec.get("data_fingerprint_source") or "-" + inputs = rec.get("input_claims") or [] + line = f" {s.claim_id} tier={s.tier} provenance={source}" + if inputs: + line += f" input_claims={len(inputs)}" + + # Lineage must resolve for a metric claim; a claim emitted outside a + # driver run legitimately has none, which we report rather than fail on. + try: + trace = lineage_of(run_dir, s.record_id) + line += f" node={trace.node} upstream={len(trace.upstream_closure)}" + if trace.is_overridden: + line += f" OVERRIDDEN({len(trace.overridden)})" + except LineageNotRecordedError: + line += " (no lineage — non-driver emit)" + except ValueError: + pass # not a claim record; skip lineage + + if s.claim_id in standing: + line += " << STANDING REFUTATION" + ok = False + + print(line) + + print() + if ok: + print("OK: every claim resolved; no standing refutations in this run.") + return 0 + print("FAIL: at least one claim carries a standing refutation — do not publish over it.") + return 1 + + +def main() -> int: + if len(sys.argv) != 3: + print(__doc__) + return 2 + return verify(Path(sys.argv[1]), sys.argv[2]) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/.claude/skills/insight-kit-critic/SKILL.md b/.claude/skills/insight-kit-critic/SKILL.md new file mode 100644 index 0000000..8999285 --- /dev/null +++ b/.claude/skills/insight-kit-critic/SKILL.md @@ -0,0 +1,88 @@ +--- +name: insight-kit-critic +description: >- + Adversarially audit the claims in a sealed insight-kit run — the critic + council. Use this whenever the task is to review, verify, challenge, sanity- + check, or sign off on numbers/metrics/claims that someone else (another agent + or an earlier run) produced: "is this figure right?", "can we trust this + number?", "review this analysis before it goes to the board", "did anything + break this metric?". Trigger it even without the words "insight-kit" or + "critic" — any request to VET a produced number, rather than produce one, + belongs here. The council runs a perspective-diverse panel of skeptics + (correctness, methodology, staleness, support), applies a majority-refute + rule, and records each verdict as a first-class gated critic claim, then + propagates refutations to everything downstream. Do NOT use this to compute a + new number — that is the insight-kit-analyst skill. The producer of a claim + must never be its critic: run this as a DIFFERENT agent from whoever produced + the run. +--- + +# insight-kit: the critic council + +Audit a sealed run adversarially. You are **not** the agent that produced these +claims — your job is to try to break them, and to record why they survive or +fall as gated provenance, not as chat. + +The full, harness-agnostic method is in `docs/method/critic-council.md`. Read it +before you start; it defines the lenses and the kill rule that the archetype +agents below implement. + +## First: separate mechanical from semantic + +Two things look like "audit" but aren't the same: + +- **Mechanical** facts are deterministic — `lineage_of`, `trace_to_rows`, the + standing guards. The sealed bundle can't lie. **Consume these as ground + truth**; do not re-derive provenance. They tell you *what* the claim is and + where it came from. +- **Semantic** judgment — is the number right, sound, current, and load-bearing? + — is what the council spends its effort on. + +## Run the council + +For each claim under review (start with published/board-audience claims, then +drafts that feed them), dispatch the four archetype agents as **independent** +subagents — in parallel where possible — each applying one lens: + +- `ik-critic-correctness` — does it reconcile against its traced inputs? +- `ik-critic-methodology` — is the grain/filter/window/definition sound? +- `ik-critic-staleness` — is it (or an ancestor) standing-refuted / contaminated? +- `ik-critic-support` — does it actually back the conclusion it is cited for? + +Give each subagent the workspace dir, the sealed run dir, and the target +`claim_id` / `record_id`. Each returns a stance — `refute` or `pass` — with a +one-line reason. They are prompted to default to `refute` under genuine +uncertainty: a claim should earn survival. + +## Apply the kill rule + +Combine stances by **majority-refute**: a majority of lenses refuting means the +claim does not survive. On a high-stakes (published / board) claim, even a tie +or a single strong refutation should block — surface it rather than wave it +through. The reasons are the audit trail; keep them. + +## Record the verdict as gated provenance + +Do not leave the verdict in prose. For each claim, emit critic-tier claims: + +```python +from insight_kit.platform.gate import ik_claim_emit, guard_refuted_inputs + +# one per refuting lens (or a single combined critic citing the lens reasons): +ik_claim_emit( + "-X-###", # critic-tier id (X token) + {"passed": False, "reason": ": "}, + tier="critic", + refutes=[target_record_id], # a critic MUST declare supports or refutes + run_state=rs, run_dir=run_dir, +) +# for a lens that clears the claim, use supports=[target_record_id] instead. + +# then propagate: everything derived from a refuted claim is flagged too. +contaminated = guard_refuted_inputs(workspace_dir, run_state=rs, run_dir=run_dir) +``` + +Running `guard_refuted_inputs` after emitting the direct verdicts is what makes +a refutation *propagate* — otherwise it dies on one node while downstream +metrics keep standing on it. Report the surviving claims, the refuted claims +with reasons, and the contamination the guard surfaced. diff --git a/CHANGELOG.md b/CHANGELOG.md index 1cd537b..abfe336 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,6 +39,14 @@ the git log. This changelog starts at `0.2.0`. lands as `payload` provenance and records the upstream claims it was derived from as `input_claims` (claim→claim data lineage), so a derived number still traces back to what produced it. +- **Agent skills + method spec**: a harness-agnostic method (`docs/method/`) for + the producer loop (discover → compose → run → seal → verify) and the critic + council (perspective-diverse lenses, majority-refute, verdicts as gated + critic claims), bound to Claude Code as two directly-invocable skills + (`.claude/skills/insight-kit-analyst`, `.claude/skills/insight-kit-critic`) and + four archetype agents (`.claude/agents/ik-critic-*`). Gate logic stays L1 + Python, archetype prompts stay data, the binding stays thin — so a `pi` + binding can reuse the same spec. Includes a `verify_run.py` self-check helper. - **Measure catalog** (`integrations.hamilton.catalog`): a static semantic layer read from the compiled Hamilton graph and `@tag` metadata (no execution, no data). Distinguishes base from derived measures, advertises the `claim_id` diff --git a/docs/method/analyst-loop.md b/docs/method/analyst-loop.md new file mode 100644 index 0000000..150b22c --- /dev/null +++ b/docs/method/analyst-loop.md @@ -0,0 +1,94 @@ +# The analyst loop (harness-agnostic) + +This is the canonical method an agent follows to produce a governed, provenance- +tracked number with insight-kit. It is written once here, independent of any +harness; each binding (the Claude Code `insight-kit-analyst` skill, the `pi` +extension) is a thin adapter that walks an agent through these same steps. + +The loop is **discover → compose → run → seal → verify**. The guiding idea: +never hand-carry a number. Every claim the loop produces is typed, content- +addressed, and carries its own provenance, so a reader (or a critic) can trace +it back to the rows or the upstream claims it came from without trusting the +agent that produced it. + +## 1. Discover — read the semantic layer before writing anything + +An analyst composing a metric needs to know what it can *stand on*: which +measures already exist, at what grain, and which are base (computed from data) +versus derived (computed from other measures). Read that from the compiled +Hamilton graph — statically, no execution, no data: + +```python +from insight_kit.integrations.hamilton import catalog, format_catalog +from insight_kit.examples.growth_demo import dag # your module(s) here + +cat = catalog([dag]) +print(format_catalog(cat)) # measures + grain + claim_ids + the authoring contract +``` + +`format_catalog` prints the authoring contract by default, so the same brief +tells you both *what exists* and *how to add one*. Reuse before you rebuild: if +a measure already exists at the grain you need, reference it — don't recompute. + +## 2. Compose — only if the measure you need doesn't exist + +Author a Hamilton node tagged as a measure. The tag contract and the +composition rule are in `authoring_guide()` (also appended to `format_catalog`). +The one rule that matters most: **to derive from existing measures, name them +as parameters of your new node.** Hamilton binds each parameter to the upstream +node of the same name, and the adapter records those measures as `input_claims` +(claim→claim provenance) automatically. Only compose measures that share the +same grain. + +A derived (Layer-2) measure has no live input rows of its own — its inputs are +the *values* of upstream claims — so it lands as `payload` provenance and its +backing is the `input_claims` edge, not a row fingerprint. That is correct and +expected; the number still traces back through the claims it was computed from. + +## 3. Run — execute through the gate-backed driver + +```python +from insight_kit.platform.gate import RunState, new_run_dir +from insight_kit.integrations.hamilton import build_driver + +run_dir = new_run_dir(workspace_dir) # a fresh dated run under the workspace +rs = RunState(run_dir=run_dir) +dr = build_driver(rs, run_dir, [dag]) +dr.execute(["cac_payback_ratio"], inputs={...}) # upstream measures emit too +``` + +Hamilton executes topologically, so upstream measures emit their claims before +the downstream metric that derives from them. Ask for the final metric; the +inputs it needs are pulled (and gated) transitively. + +## 4. Seal — freeze the run into the workspace + +```python +from insight_kit.platform.gate import seal_run +seal_run(workspace_dir, run_dir, rs) +``` + +Sealing writes the immutable bundle and the manifest row. Once sealed, the run +is a stable target for lineage reads and for a critic to audit. + +## 5. Verify — mechanical self-check (the bundle can't lie) + +This step is deterministic — it is *not* a judgment call, so it is fine for the +producing agent to run it on its own work. It reads facts back out of the sealed +bundle and runs the two standing guards: + +- `lineage_of(run_dir, record_id)` / `trace_to_rows(...)` — confirm each claim's + provenance chain resolves (a derived claim traces up its `input_claims`; a base + claim traces to its rows). +- `guard_republished_claims(workspace, ...)` — did this run republish a claim + that was refuted before, without a superseding verdict? +- `guard_refuted_inputs(workspace, ...)` — does any claim in this run *derive* + from something refuted (refutation contagion)? + +Both guards **surface, never block**: they return findings. If a guard returns +findings, the number is standing on contaminated ground — stop and address it +before presenting the result, don't publish over it. + +What this step deliberately does **not** do is decide whether the number is +*right* or *meaningful*. That is a judgment call, and a producer must not grade +its own homework — it belongs to a separate critic (see `critic-council.md`). diff --git a/docs/method/critic-council.md b/docs/method/critic-council.md new file mode 100644 index 0000000..a289958 --- /dev/null +++ b/docs/method/critic-council.md @@ -0,0 +1,80 @@ +# The critic council (harness-agnostic) + +This is the canonical method for adversarially auditing the claims in a sealed +run. It is written once here, independent of any harness; each binding (the +Claude Code `insight-kit-critic` skill and its archetype agents, a future `pi` +extension) is a thin adapter that runs this same council. + +## Why a separate critic at all + +insight-kit splits "audit" into two things that look alike but aren't: + +- **Mechanical audit** is deterministic — `lineage_of`, `trace_to_rows`, the + gate's typing/provenance enforcement, and the two standing guards. No + judgment, no LLM. The sealed bundle can't lie, so the *producer* may run this + on its own work (it's step 5 of the analyst loop). +- **Semantic audit** is judgment — *is this the right metric? is the definition + sound? is it stale or contradicted? does it actually support the conclusion it + is cited for?* An agent blessing its own claim here is marking its own + homework, which is exactly the failure mode the gate's `supports`/`refutes` + edges and `standing_refutations` exist to prevent. + +So the critic is a **different agent from the producer**, and it consumes the +mechanical lineage as ground truth — it does not recompute provenance, it spends +its judgment only on the semantic question. + +## The council: diverse lenses, not redundant votes + +A single skeptic misses failure modes it isn't looking for. The council is a +**perspective-diverse panel** — each archetype applies a distinct lens, so together +they cover ways a claim can be wrong that any one of them would miss. Run them +independently (in parallel where the harness allows), then combine. + +Each archetype reads the sealed run and the claim under review, and returns a +stance: `refute` (with a reason) or `pass` (with a reason). Default to `refute` +when genuinely uncertain — a claim should earn survival, not get it by default. + +### Archetypes + +1. **Correctness** — does the number reconcile? Recompute the claim from its + traced inputs (rows for a base claim, `input_claims` values for a derived + one) and check the identity holds. This lens leans on the mechanical lineage; + it refutes on an arithmetic/aggregation mismatch. +2. **Methodology** — is the grain, filter set, window, and definition sound for + what the claim asserts? Refutes on grain mismatch, a filter that silently + changes the population, a window that doesn't match the statement, or a + definition that doesn't mean what the prose says. +3. **Staleness / contamination** — is this claim contradicted? Check + `standing_refutations` for the claim_id, and run `guard_refuted_inputs` to see + whether it derives from anything refuted. Refutes if the claim or any of its + `input_claims` ancestors carries a standing refutation. +4. **Support** — does this claim actually back the conclusion it is attached to? + Follow `cites` / the narrative it supports. Refutes if the claim is decorative + — cited to lend weight to a conclusion it does not, on its own, establish. + +Add or drop lenses to fit the claim; these four are the default panel. The point +is diversity of failure-mode coverage, not the exact count. + +## The kill rule + +Combine the stances with a **majority-refute** rule: if a majority of the lenses +refute, the claim does not survive. A tie or a single-lens refutation on a +high-stakes (published / board) claim should also block — surface it rather than +wave it through. Record *why*: the surviving/rejecting reasons are the audit +trail. + +## Recording the verdict — as first-class gated provenance, not chat + +The council's verdict is itself a claim, so it must be gated, not left as prose: + +- For each refuting lens, emit a **critic-tier claim** that `refutes` the target + record (or `supports`, for a lens that clears it). This is the `ik_claim_emit` + `refutes=[...]` / `supports=[...]` edge — a critic-tier claim must declare at + least one such target. +- After emitting the direct verdicts, run `guard_refuted_inputs` so a refutation + **propagates**: everything downstream that derived from the refuted claim is + flagged too, instead of the refutation dying on one node. + +The result is an auditable verdict with the same provenance guarantees as the +claims it judges — a later reader can see who refuted what, why, and what the +refutation contaminated.