refactor: compose investigation record ownership (#845)

This commit is contained in:
N0zoM1z0
2026-10-07 12:10:45 +08:00
committed by GitHub
parent bc2cd8b874
commit ce73c3fed2
27 changed files with 627 additions and 127 deletions
@@ -0,0 +1,67 @@
import type { Evidence } from "../../domain/evidence.js";
import type { EvidenceBundle } from "../../domain/evidenceBundle.js";
import type { EvidenceIntegrityError } from "../../domain/evidenceErrors.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import type { UnknownRegistryError } from "../../domain/unknownRegistryError.js";
import type {
RecordUnknownInput,
ResidualUnknown,
UnknownStatus,
UpdateUnknownInput,
} from "../../domain/residualUnknown.js";
import type { Result } from "../../domain/result.js";
/** Detached investigation Evidence reads without target execution or lifecycle authority. */
export interface EvidenceReader {
hasEvidence(evidenceId: string): boolean;
evidenceById(evidenceId: string): Evidence | undefined;
exportEvidenceBundle(): EvidenceBundle;
}
/** Idempotent investigation Evidence writes without target execution. */
export interface EvidenceWriter {
recordEvidence(
evidence: Evidence,
): Result<"added" | "duplicate", EvidenceIntegrityError>;
}
/** Atomic derived Evidence and linked Unknown writes. */
export interface EvidenceUnknownWriter {
recordEvidenceWithUnknown(
evidence: Evidence,
input: RecordUnknownInput,
): Result<ResidualUnknown | null, AnalysisError>;
}
/** Optimistic Unknown revisions and consistency verification. */
export interface UnknownRegistryPort {
recordUnknown(
input: RecordUnknownInput,
): Result<ResidualUnknown, AnalysisError>;
updateUnknown(
input: UpdateUnknownInput,
): Result<ResidualUnknown, AnalysisError>;
listUnknowns(filters?: {
readonly status?: UnknownStatus;
readonly severity?: ResidualUnknown["severity"];
readonly domain?: string;
}): ResidualUnknown[];
verifyUnknownResolution(unknownId: string): Result<
{
readonly valid: boolean;
readonly truthVerified: boolean;
readonly unknown: ResidualUnknown;
},
UnknownRegistryError
>;
}
/** Compatibility record surface; binary execution and snapshots remain separate. */
export interface InvestigationRecordPort
extends
EvidenceReader,
EvidenceWriter,
EvidenceUnknownWriter,
UnknownRegistryPort {
importEvidenceBundle(bundle: unknown): Result<number, EvidenceIntegrityError>;
}
@@ -0,0 +1,145 @@
import { describe, expect, it } from "vitest";
import {
ANALYSIS_SNAPSHOT_TARGET as target,
ANALYSIS_SNAPSHOT_PROVIDER as provider,
} from "../../domain/analysisSnapshot.fixture.js";
import { createEvidence } from "../../domain/evidence.js";
import { createEvidenceBundle } from "../../domain/evidenceBundle.js";
import {
recordUnknownInputSchema,
updateUnknownInputSchema,
} from "../../domain/residualUnknown.js";
import { unknownMutationEvidence } from "../UnknownEvidence.js";
import { InvestigationRecords } from "./InvestigationRecords.js";
const unknownInput = (question: string) =>
recordUnknownInputSchema.parse({
question,
severity: "medium",
domain: "investigation",
required_authority: "analyst-inference",
required_confidence: "derived",
required_environment: null,
recommended_probes: [],
relationships: [],
});
const evidence = createEvidence(undefined, provider, {
operation: "inspect-fixture",
parameters: {},
result: true,
confidence: "derived",
authority: "analyst-inference",
});
describe("investigation record ownership", () => {
it("keeps identity, detached reads and independent stores without a binary target", () => {
const records = new InvestigationRecords();
expect(records.recordEvidence(evidence)).toEqual({
ok: true,
value: "added",
});
expect(records.recordEvidence(evidence)).toEqual({
ok: true,
value: "duplicate",
});
const read = records.evidenceById(evidence.evidence_id);
if (read === undefined) throw new Error("Missing recorded Evidence");
Reflect.set(read, "operation", "forged");
expect(records.evidenceById(evidence.evidence_id)).toEqual(evidence);
expect(new InvestigationRecords().hasEvidence(evidence.evidence_id)).toBe(
false,
);
});
it("preserves explicit Unknown subjects and target-free atomic mutation subjects", () => {
const records = new InvestigationRecords();
const input = unknownInput("Which target supplies this observation?");
const bound = records.recordUnknown(input, target);
expect(bound).toMatchObject({
ok: true,
value: {
scope_digest: target.sha256,
mutation_evidence_ids: [
unknownMutationEvidence(target, input).evidence_id,
],
},
});
const independent = records.recordEvidenceWithUnknown(evidence, input);
expect(independent).toMatchObject({
ok: true,
value: {
scope_digest: null,
mutation_evidence_ids: [
unknownMutationEvidence(undefined, input).evidence_id,
],
},
});
const mutation = records.evidenceById(
unknownMutationEvidence(undefined, input).evidence_id,
);
expect(mutation?.subject).toBeNull();
expect(records.listUnknowns()).toHaveLength(2);
});
it("rolls back Evidence when the linked Unknown fails validation", () => {
const records = new InvestigationRecords();
const invalid = {
...unknownInput("Is the missing Evidence present?"),
supporting_evidence_ids: [`ev_${"f".repeat(64)}`],
};
expect(records.recordEvidenceWithUnknown(evidence, invalid).ok).toBe(false);
expect(records.hasEvidence(evidence.evidence_id)).toBe(false);
expect(records.exportEvidenceBundle()).toEqual(createEvidenceBundle([]));
});
it("preserves optimistic revisions and the explicit update subject", () => {
const records = new InvestigationRecords();
const created = records.recordUnknown(
unknownInput("Can this revision be updated?"),
target,
);
if (!created.ok) throw created.error;
const input = updateUnknownInputSchema.parse({
...created.value,
expected_revision: created.value.revision,
status: "investigating",
});
const updated = records.updateUnknown(input, target);
expect(updated).toMatchObject({
ok: true,
value: { revision: 2, scope_digest: target.sha256 },
});
const bundle = records.exportEvidenceBundle();
expect(
bundle.records.find(({ operation }) => operation === "update_unknown")
?.subject?.digest.sha256,
).toBe(target.sha256);
expect(records.updateUnknown(input, target).ok).toBe(false);
expect(records.exportEvidenceBundle()).toEqual(bundle);
});
it("reports Unknown-only bundle changes and clears the single record owner", () => {
const source = new InvestigationRecords();
expect(
source.recordUnknown(
unknownInput("Can imported Unknowns notify observers?"),
).ok,
).toBe(true);
const bundle = source.exportEvidenceBundle();
const records = new InvestigationRecords();
expect(
records.mergeEvidenceBundle(createEvidenceBundle(bundle.records)).ok,
).toBe(true);
expect(records.mergeEvidenceBundle(bundle)).toEqual({
ok: true,
value: { recordsAdded: 0, unknownsAdded: 1, changed: true },
});
expect(records.mergeEvidenceBundle(bundle)).toEqual({
ok: true,
value: { recordsAdded: 0, unknownsAdded: 0, changed: false },
});
records.clear();
expect(records.exportEvidenceBundle()).toEqual(createEvidenceBundle([]));
});
});
@@ -0,0 +1,142 @@
import type { BinaryTarget } from "../../domain/binaryTarget.js";
import { createEvidence, type Evidence } from "../../domain/evidence.js";
import type { EvidenceBundle } from "../../domain/evidenceBundle.js";
import type { EvidenceIntegrityError } from "../../domain/evidenceErrors.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import type { UnknownRegistryError } from "../../domain/unknownRegistryError.js";
import type {
RecordUnknownInput,
ResidualUnknown,
UnknownStatus,
UpdateUnknownInput,
} from "../../domain/residualUnknown.js";
import type { Result } from "../../domain/result.js";
import { EvidenceLedger, type EvidenceImportDelta } from "../EvidenceLedger.js";
import {
UNKNOWN_REGISTRY_PROVIDER,
unknownEvidenceLinks,
unknownMutationEvidence,
} from "../UnknownEvidence.js";
import type {
EvidenceReader,
EvidenceWriter,
EvidenceUnknownWriter,
UnknownRegistryPort,
} from "./InvestigationRecordPort.js";
/** One investigation's validated record owner, independent of binary execution. */
export class InvestigationRecords
implements
EvidenceReader,
EvidenceWriter,
EvidenceUnknownWriter,
UnknownRegistryPort
{
readonly #evidence = new EvidenceLedger();
/** Record immutable Evidence idempotently; reject conflicting content. */
recordEvidence(
evidence: Evidence,
): Result<"added" | "duplicate", EvidenceIntegrityError> {
return this.#evidence.record(evidence);
}
/** Check one semantic Evidence ID without exposing stored values. */
hasEvidence(evidenceId: string): boolean {
return this.#evidence.has(evidenceId);
}
/** Return a detached Evidence value for one semantic ID. */
evidenceById(evidenceId: string): Evidence | undefined {
return this.#evidence.get(evidenceId);
}
/** Export a detached deterministic bundle of Evidence and Unknown revisions. */
exportEvidenceBundle(): EvidenceBundle {
return this.#evidence.export();
}
/** Atomically merge a bundle and report changes for the owner's post-commit observers. */
mergeEvidenceBundle(
bundle: unknown,
): Result<EvidenceImportDelta, EvidenceIntegrityError> {
return this.#evidence.import(bundle);
}
/** Clear records when the owning runtime applies its existing lifecycle policy. */
clear(): void {
this.#evidence.clear();
}
/** Record an Unknown with an explicitly supplied Evidence subject, if any. */
recordUnknown(
input: RecordUnknownInput,
target?: BinaryTarget,
): Result<ResidualUnknown, AnalysisError> {
const recorded = this.#evidence.recordUnknown(
input,
unknownMutationEvidence(target, input),
);
return recorded;
}
/** Commit derived Evidence and its Unknown atomically without an implicit subject. */
recordEvidenceWithUnknown(
evidence: Evidence,
input: RecordUnknownInput,
): Result<ResidualUnknown | null, AnalysisError> {
const recorded = this.#evidence.recordWithUnknown(
evidence,
input,
unknownMutationEvidence(undefined, input),
);
return recorded;
}
/** Update an optimistic revision with an explicitly supplied Evidence subject. */
updateUnknown(
input: UpdateUnknownInput,
target?: BinaryTarget,
): Result<ResidualUnknown, AnalysisError> {
const evidence = createEvidence(target, UNKNOWN_REGISTRY_PROVIDER, {
predicateType: "rea.residual-unknown-mutation",
operation: "update_unknown",
parameters: {
unknown_id: input.unknown_id,
expected_revision: input.expected_revision,
},
result: { action: "update", status: input.status },
confidence: "derived",
authority: "analyst-inference",
evidenceLinks: unknownEvidenceLinks(input),
limitations: [
"Registry mutation evidence records analyst intent, not proof of the answer.",
],
});
const updated = this.#evidence.updateUnknown(input, evidence);
return updated;
}
/** Return detached current Unknown revisions matching the selected filters. */
listUnknowns(
filters: {
readonly status?: UnknownStatus;
readonly severity?: ResidualUnknown["severity"];
readonly domain?: string;
} = {},
): ResidualUnknown[] {
return this.#evidence.listUnknowns(filters);
}
/** Verify registry consistency without asserting the answer is true. */
verifyUnknownResolution(unknownId: string): Result<
{
readonly valid: boolean;
readonly truthVerified: boolean;
readonly unknown: ResidualUnknown;
},
UnknownRegistryError
> {
return this.#evidence.verifyUnknownResolution(unknownId);
}
}