Merge pull request #461 from morluto/agent/comprehensive-repository-audit

fix: harden evidence lifecycle and MCP contracts
This commit is contained in:
morluto
2026-08-04 03:00:25 +08:00
committed by GitHub
parent 84cc819284
commit 51559245d2
47 changed files with 1452 additions and 404 deletions
+33 -16
View File
@@ -119,13 +119,10 @@ export const inspectAddressContext = async (
inline_comment: inlineComment,
bookmarks:
bookmarks.state === "available"
? {
state: "available",
value: matchingBookmarks(
bookmarks.value,
resolvedAddress(results[1], input.address),
),
}
? matchingBookmarks(
bookmarks.value,
resolvedAddress(results[1], input.address),
)
: bookmarks,
});
};
@@ -200,13 +197,33 @@ const resolvedAddress = (
: fallback;
};
const matchingBookmarks = (value: JsonValue, address: string): JsonValue => {
if (!Array.isArray(value)) return [];
return value.filter(
(bookmark) =>
typeof bookmark === "object" &&
bookmark !== null &&
!Array.isArray(bookmark) &&
bookmark.address === address,
);
const matchingBookmarks = (value: JsonValue, address: string): Facet => {
if (!Array.isArray(value))
return {
state: "unavailable",
reason: "list_bookmarks returned malformed output; expected an array.",
remediation:
"Retry list_bookmarks directly and report the provider output shape if it remains malformed.",
};
if (!value.every(isBookmark))
return {
state: "unavailable",
reason:
"list_bookmarks returned malformed entries; expected address and name strings.",
remediation:
"Retry list_bookmarks directly and report the provider output shape if it remains malformed.",
};
return {
state: "available",
value: value.filter((bookmark) => bookmark.address === address),
};
};
const isBookmark = (
value: JsonValue,
): value is { readonly address: string; readonly name: string } =>
typeof value === "object" &&
value !== null &&
!Array.isArray(value) &&
typeof value.address === "string" &&
typeof value.name === "string";
+3
View File
@@ -34,6 +34,8 @@ export interface EvidenceBundleSnapshot {
readonly bytes: number;
readonly records: number;
readonly unknowns: number;
readonly scope: "session";
readonly survivesSession: false;
readonly uri: string;
}
@@ -60,6 +62,7 @@ export interface BinarySessionPort extends AnalysisOperationPort {
evidenceById(evidenceId: string): Evidence | undefined;
exportEvidenceBundle(): EvidenceBundle;
snapshotEvidenceBundle(): Result<EvidenceBundleSnapshot, EvidenceLimitError>;
releaseEvidenceBundle(bundleDigest: string): boolean;
retainedEvidenceBundle(digest: string): string | undefined;
importEvidenceBundle(
bundle: unknown,
+29 -4
View File
@@ -129,6 +129,8 @@ export abstract class BinarySessionRecords {
bytes: Buffer.byteLength(existing ?? encoded),
records: bundle.records.length,
unknowns: bundle.unknowns.length,
scope: "session",
survivesSession: false,
uri: `rea://evidence-bundle/${digest}`,
});
}
@@ -137,12 +139,23 @@ export abstract class BinarySessionRecords {
return this.#retainedBundles.get(digest);
}
/** Release one immutable bundle so bounded retention has an explicit recovery path. */
releaseEvidenceBundle(bundleDigest: string): boolean {
const encoded = this.#retainedBundles.get(bundleDigest);
if (encoded === undefined) return false;
this.#retainedBundles.delete(bundleDigest);
this.#retainedBundleBytes -= Buffer.byteLength(encoded);
this.#emitSnapshotChanged();
return true;
}
importEvidenceBundle(
bundle: unknown,
): Result<number, EvidenceIntegrityError | EvidenceLimitError> {
const imported = this.#evidence.import(bundle);
if (imported.ok && imported.value > 0) this.#emitSnapshotChanged();
return imported;
if (!imported.ok) return imported;
if (imported.value.changed) this.#emitSnapshotChanged();
return ok(imported.value.recordsAdded);
}
protected abstract activeAnalysisBinding(): ActiveAnalysisBinding | undefined;
@@ -187,7 +200,10 @@ export abstract class BinarySessionRecords {
active === undefined
? undefined
: { target: active.target, profile: active.profile },
(bundle) => this.#evidence.import(bundle),
(bundle) => {
const imported = this.#evidence.import(bundle);
return imported.ok ? ok(imported.value.recordsAdded) : imported;
},
);
if (imported.ok) this.#emitSnapshotChanged();
return imported;
@@ -253,7 +269,16 @@ export abstract class BinarySessionRecords {
}
#emitSnapshotChanged(): void {
for (const listener of this.#snapshotListeners) void listener();
for (const listener of this.#snapshotListeners) {
try {
const notification = listener();
if (notification !== undefined)
void notification.catch(() => undefined);
} catch {
// External resource observers are best-effort; one callback must not
// make a committed evidence mutation appear to fail.
}
}
}
retainInvestigationWorkspace(
+102 -12
View File
@@ -72,6 +72,17 @@ const CLIENT_FEATURE_REQUIREMENTS: Readonly<
type Availability = {
readonly reason: ToolAvailabilityReason;
readonly remediation: string | null;
readonly defaultModeAvailable?: boolean;
readonly modes?: readonly CapabilityMode[];
};
type CapabilityMode = {
readonly name: string;
readonly available: boolean;
readonly missing_operations: readonly string[];
readonly remediation: string | null;
};
type NavigationModeResult = CapabilityMode & {
readonly reason: ToolAvailabilityReason;
};
type AvailabilityContext = {
readonly name: string;
@@ -111,15 +122,20 @@ const ENHANCED_REQUIREMENTS: Readonly<Record<string, readonly string[]>> = {
],
};
const SESSION_COMPOSITION_REQUIREMENTS: Readonly<
Record<string, readonly string[]>
> = {
get_navigation_context: [
"current_document",
"current_address",
"resolve_containing_procedure",
],
};
const NAVIGATION_CONTEXT_MODES = [
{
name: "current_selection",
requirements: [
"current_document",
"current_address",
"resolve_containing_procedure",
],
},
{
name: "explicit_document",
requirements: ["current_address", "resolve_containing_procedure"],
},
] as const;
/** Build stable per-operation availability for discovery and tool visibility. */
export const buildCapabilityInventory = (
@@ -162,6 +178,12 @@ export const buildCapabilityInventory = (
remediation: clientBlocked
? `Use an MCP client that supports: ${clientRequirements.missing_required.join(", ")}.`
: availability.remediation,
...(availability.defaultModeAvailable === undefined
? {}
: { default_mode_available: availability.defaultModeAvailable }),
...(availability.modes === undefined
? {}
: { modes: availability.modes }),
client_requirements: clientRequirements,
effects: { ...contract.effects },
annotations: {
@@ -195,9 +217,8 @@ const clientRequirementsFor = (
};
const availabilityFor = (context: AvailabilityContext): Availability => {
const sessionComposition = SESSION_COMPOSITION_REQUIREMENTS[context.name];
if (sessionComposition !== undefined)
return composedAvailabilityFor(sessionComposition, context.descriptors);
if (context.name === "get_navigation_context")
return navigationContextAvailability(context.descriptors);
const javascriptApplication = javascriptApplicationAvailability(context);
if (javascriptApplication !== null) return javascriptApplication;
const policyDecision = policyAvailability(context);
@@ -406,3 +427,72 @@ const composedAvailabilityFor = (
};
return { reason: "available", remediation: null };
};
const navigationContextAvailability = (
descriptors: ReadonlyMap<string, ProviderDescriptor>,
): Availability => {
const modeResults: NavigationModeResult[] = NAVIGATION_CONTEXT_MODES.map(
(mode) => {
const availability = composedAvailabilityFor(
mode.requirements,
descriptors,
);
return {
name: mode.name,
available: availability.reason === "available",
reason: availability.reason,
missing_operations: mode.requirements.filter((operation) => {
const descriptor = descriptors.get(operation);
return descriptor === undefined || descriptor.available === false;
}),
remediation: availability.remediation,
};
},
);
const modes = modeResults.map(
({ name, available, missing_operations, remediation }) => ({
name,
available,
missing_operations,
remediation,
}),
);
const availableMode = modeResults.find((mode) => mode.available);
const failure = modeResults
.filter((mode) => !mode.available)
.sort(
(left, right) =>
navigationFailurePriority(left.reason) -
navigationFailurePriority(right.reason),
)[0];
const specificFailureRemediation =
failure?.reason === "provider_missing" ? undefined : failure?.remediation;
return {
reason:
availableMode === undefined
? (failure?.reason ?? "provider_missing")
: "available",
remediation:
availableMode === undefined
? (specificFailureRemediation ??
`Configure a provider for one of: ${modes
.flatMap((mode) => mode.missing_operations)
.join(", ")}.`)
: null,
defaultModeAvailable: modes[0]?.available ?? false,
modes,
};
};
const navigationFailurePriority = (reason: ToolAvailabilityReason): number => {
switch (reason) {
case "unsupported_host":
return 0;
case "provider_unavailable":
return 1;
case "provider_missing":
return 2;
default:
return 3;
}
};
+5 -1
View File
@@ -26,7 +26,11 @@ export const importEvidenceBundleCommand = async (
const ledger = createLedger();
const imported = ledger.import(loaded.value);
return imported.ok
? ok({ imported: imported.value, total: ledger.export().records.length })
? ok({
imported: imported.value.recordsAdded,
unknowns_added: imported.value.unknownsAdded,
total: ledger.export().records.length,
})
: imported;
};
+16 -2
View File
@@ -29,7 +29,15 @@ export interface EvidenceLedgerLimits {
type EvidenceLedgerFailure = EvidenceIntegrityError | EvidenceLimitError;
type RecordResult = Result<"added" | "duplicate", EvidenceLedgerFailure>;
type ImportResult = Result<number, EvidenceLedgerFailure>;
/** Describes the state changes made by one atomic bundle import. */
export interface EvidenceImportDelta {
readonly recordsAdded: number;
readonly unknownsAdded: number;
readonly changed: boolean;
}
type ImportResult = Result<EvidenceImportDelta, EvidenceLedgerFailure>;
/** Bounded, session-owned set of immutable evidence records. */
export class EvidenceLedger {
@@ -98,6 +106,7 @@ export class EvidenceLedger {
pending.set(evidence.evidence_id, evidence);
}
const pendingUnknowns = new Map(this.#unknownRevisions);
let unknownsAdded = 0;
for (const unknown of bundle.unknowns) {
const key = unknownRevisionKey(unknown);
const existing = pendingUnknowns.get(key);
@@ -107,6 +116,7 @@ export class EvidenceLedger {
)
return err(new EvidenceIntegrityError("Conflicting unknown revision"));
pendingUnknowns.set(key, unknown);
if (existing === undefined) unknownsAdded += 1;
}
const checked = this.#validateCandidate(pending, pendingUnknowns);
if (!checked.ok) {
@@ -123,7 +133,11 @@ export class EvidenceLedger {
}
const added = pending.size - this.#records.size;
this.#commit(pending, pendingUnknowns, checked.value);
return ok(added);
return ok({
recordsAdded: added,
unknownsAdded,
changed: added > 0 || unknownsAdded > 0,
});
}
/** Export records in deterministic, semantically irrelevant ID order. */