mirror of
https://github.com/morluto/rea.git
synced 2026-12-06 15:33:56 +08:00
* refactor: prune internal seams and preserve configuration ownership * fix(setup): keep YAML aliases and inherited registration settings on refresh - Reuse an unchanged YAML collection only while every alias in it still resolves after the edit; otherwise rebuild it so the alias becomes its value. A sibling anchor replaced or moved in the same refresh no longer leaves an unresolved alias in Hermes or Goose output. - Keep a connection selector whose existing value already chooses stdio (for example an inherited Hermes transport: stdio) instead of superseding it; remote selectors are still replaced. Explicit stdio selectors are therefore no longer rewritten (Kimi expectation updated). - When the whole Hermes registration is inherited through a merge, override it with that merge and write only the changed fields. * fix(setup): edit registration fields whose YAML key is an alias A key written as an alias to a string scalar (for example *field with field: &field env) was treated as a source-only key, so any change to its value was refused in Hermes and Goose. Resolve such keys to their string, keep the aliased spelling while its anchor survives the edit, and write the plain key when the same edit rebuilds the anchor. * test(process): bound cleanup-boundary waits and always release gates Both cancellation tests awaited a bare started promise and released their gates only on success, so a missed boundary waited for the outer deadline and could leave cleanup parked. Use awaitAcknowledgement and release and join the cleanup in finally. * fix(setup): repair only aliases an edit leaves unresolved Replace the pre-edit alias survival guess, which expanded aliases to sibling anchors that survive unchanged, with an exact repair: record what each alias in the replaced value resolves to, write the edit, then replace only aliases left without a preceding anchor by that value. - Keep an aliased key's source position, so its anchor stays ahead of later aliases. - Treat an aliased key as its string only when no other key in the map resolves to the same string; an ambiguous one stays guarded. - Override an inherited Hermes registration only when the requested entry keeps every inherited field, so an explicit replacement can drop remote selectors. * fix(setup): repair aliases whose binding an edit changes, keeping comments An alias whose own anchor was removed could resolve to an earlier anchor with the same name and silently change value. Record the node each alias resolved to and repair any alias that no longer resolves to that node. Carry the alias's comments and spacing onto the repaired value. * test(setup): split the Hermes anchor and merge refresh cases * fix(setup): refuse removing an overridden key its merge would restore The merge-retention check skipped keys the mapping also overrides, so dropping such a key (for example a remote url during an explicit stdio replacement) let the retained merge restore it. Check removal before skipping overridden keys, so the edit is refused with the existing message instead of producing a registration that cannot be applied.
309 lines
12 KiB
TypeScript
309 lines
12 KiB
TypeScript
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
|
|
import { stableArtifactInputFailure } from "../artifacts/StableArtifactFailure.js";
|
|
import {
|
|
ArtifactFileCleanupFailure,
|
|
bindArtifactFileCleanup,
|
|
artifactFileCancellationCause,
|
|
} from "../artifacts/ArtifactFileOperation.js";
|
|
import {
|
|
projectAnalysisError,
|
|
projectAnalysisErrorWithoutCapturedOutput,
|
|
} from "../domain/analysisErrorProjection.js";
|
|
import {
|
|
AnalysisError,
|
|
type AnalysisCapturedOutput,
|
|
type AnalysisErrorOptions,
|
|
} from "../domain/analysisErrorBase.js";
|
|
import type { JsonValue } from "../domain/jsonValue.js";
|
|
import {
|
|
AnalysisAccessDeniedError,
|
|
AnalysisArtifactChangedError,
|
|
AnalysisCapabilityUnavailableError,
|
|
AnalysisCancelledError,
|
|
AnalysisInputError,
|
|
AnalysisOutputError,
|
|
AnalysisResourceConstraintError,
|
|
AnalysisTimeoutError,
|
|
} from "../domain/analysisErrorCore.js";
|
|
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
|
|
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
|
|
import { OwnedCommandFailure } from "../process/OwnedCommand.js";
|
|
import type { ProviderProcessSnapshot } from "../process/ProviderProcess.js";
|
|
import {
|
|
DEFAULT_SQLITE_WORKER_TIMEOUT_MS,
|
|
MAX_SQLITE_WORKER_TIMEOUT_MS,
|
|
} from "../domain/sqlite/sqliteDatabase.js";
|
|
import { SQLITE_PROVIDER_IDENTITY } from "../domain/sqlite/SqliteProviderIdentity.js";
|
|
import { SQLITE_DATABASE_LIMITS } from "./SqliteDatabaseLimits.js";
|
|
import { SqliteSnapshotAcquisitionFailure } from "./SqliteDatabaseSnapshot.js";
|
|
|
|
/** Preserve diagnostics independently of worker exit and private-root cleanup. */
|
|
export const capturedSqliteOutput = (
|
|
snapshot: ProviderProcessSnapshot,
|
|
): AnalysisCapturedOutput => ({
|
|
stdout: snapshot.stdout.text,
|
|
stderr: snapshot.stderr.text,
|
|
truncated: snapshot.diagnosticTruncated === true,
|
|
});
|
|
|
|
/** Keep typed cleanup history and one canonical output owner, including after resolution. */
|
|
export const createSqliteCleanupError = (
|
|
resources: readonly string[],
|
|
diagnostics: Readonly<Record<string, JsonValue>>,
|
|
options: Omit<AnalysisErrorOptions, "diagnostics">,
|
|
): ProviderCleanupError => {
|
|
const capturedOutput =
|
|
options.capturedOutput ?? options.cleanupPrimary?.capturedOutput;
|
|
const previous =
|
|
options.cleanupPrimary === undefined
|
|
? null
|
|
: capturedOutput === undefined
|
|
? projectAnalysisError(options.cleanupPrimary)
|
|
: projectAnalysisErrorWithoutCapturedOutput(options.cleanupPrimary);
|
|
return new ProviderCleanupError(
|
|
SQLITE_PROVIDER_IDENTITY.id,
|
|
resources,
|
|
{
|
|
...diagnostics,
|
|
previous_error: previous ?? diagnostics.previous_error ?? null,
|
|
},
|
|
{
|
|
...options,
|
|
operation: "inspect_sqlite_database",
|
|
...(capturedOutput === undefined ? {} : { capturedOutput }),
|
|
},
|
|
);
|
|
};
|
|
|
|
/** The file-set member a filesystem error names, if it is the database, its WAL or its journal. */
|
|
const busyMember = (cause: Error, path: string): string => {
|
|
const failed = "path" in cause ? cause.path : undefined;
|
|
return typeof failed === "string" &&
|
|
[path, `${path}-wal`, `${path}-journal`].includes(failed)
|
|
? failed
|
|
: path;
|
|
};
|
|
|
|
/** Preserve artifact, caller, process, resource and output failure meanings. */
|
|
export const sqliteDatabaseFailure = (
|
|
cause: unknown,
|
|
path: string,
|
|
phase: string,
|
|
signal?: AbortSignal,
|
|
workerTimeoutMs = DEFAULT_SQLITE_WORKER_TIMEOUT_MS,
|
|
): AnalysisError => {
|
|
const operation = "inspect_sqlite_database";
|
|
if (cause instanceof SqliteSnapshotAcquisitionFailure) {
|
|
const failure = sqliteDatabaseFailure(
|
|
cause.operationCause,
|
|
path,
|
|
phase,
|
|
signal,
|
|
workerTimeoutMs,
|
|
);
|
|
const diagnostics = {
|
|
snapshot_acquisition: {
|
|
consistency: "unverified",
|
|
members: cause.completedMembers.map((member) => ({ ...member })),
|
|
},
|
|
};
|
|
failure.retainPrimaryDiagnostics(diagnostics);
|
|
return failure;
|
|
}
|
|
if (cause instanceof AnalysisError) return cause;
|
|
if (cause instanceof ArtifactReaderFailure) {
|
|
if (cause.cleanup !== undefined) {
|
|
const physicalRead =
|
|
cause instanceof ArtifactFileCleanupFailure
|
|
? cause.fileCleanupFailure.outcome
|
|
: undefined;
|
|
let previous: AnalysisError | undefined;
|
|
if (physicalRead?.kind === "failed")
|
|
previous = sqliteDatabaseFailure(
|
|
physicalRead.cause,
|
|
path,
|
|
phase,
|
|
undefined,
|
|
workerTimeoutMs,
|
|
);
|
|
else if (cause.reason === "cancelled")
|
|
previous = new AnalysisCancelledError(operation, {
|
|
cause: artifactFileCancellationCause(cause),
|
|
});
|
|
else if (physicalRead?.kind === "completed") previous = undefined;
|
|
else if (cause.cause !== undefined)
|
|
previous = sqliteDatabaseFailure(
|
|
cause.cause,
|
|
path,
|
|
phase,
|
|
undefined,
|
|
workerTimeoutMs,
|
|
);
|
|
|
|
const error = createSqliteCleanupError(
|
|
cause.cleanup.resources,
|
|
{
|
|
reason: cause.cleanup.reason,
|
|
},
|
|
{
|
|
cause,
|
|
...(previous === undefined ? {} : { cleanupPrimary: previous }),
|
|
},
|
|
);
|
|
bindArtifactFileCleanup(cause, error);
|
|
return error;
|
|
}
|
|
if (cause.reason === "io" && cause.cause !== undefined)
|
|
return sqliteDatabaseFailure(
|
|
cause.cause,
|
|
path,
|
|
phase,
|
|
signal,
|
|
workerTimeoutMs,
|
|
);
|
|
if (cause.reason === "integrity")
|
|
return new AnalysisArtifactChangedError(operation, path, cause.message, {
|
|
cause,
|
|
});
|
|
if (cause.reason === "cancelled")
|
|
return new AnalysisCancelledError(operation, {
|
|
cause: artifactFileCancellationCause(cause),
|
|
});
|
|
return stableArtifactInputFailure(cause, operation);
|
|
}
|
|
if (cause instanceof Error && cause.name === "AbortError")
|
|
return new AnalysisCancelledError(operation, {
|
|
cause:
|
|
signal?.aborted === true && cause.cause === signal.reason
|
|
? signal.reason
|
|
: cause,
|
|
});
|
|
if (cause instanceof OwnedCommandFailure) {
|
|
const projected = ownedCommandFailure(cause, path, workerTimeoutMs);
|
|
if (projected !== undefined) return projected;
|
|
}
|
|
if (phase === "artifact-read" && cause instanceof Error && "code" in cause) {
|
|
if (cause.code === "EACCES" || cause.code === "EPERM")
|
|
return new AnalysisAccessDeniedError(operation, path, cause.code, {
|
|
cause,
|
|
});
|
|
// Windows reports a sharing violation as EBUSY: another process holds the file without read
|
|
// sharing. The unchanged request succeeds once that process releases it. Name the member of the
|
|
// file set that was busy (the database, its WAL or its journal) when the error identifies it.
|
|
if (cause.code === "EBUSY")
|
|
return new AnalysisCapabilityUnavailableError(
|
|
SQLITE_PROVIDER_IDENTITY.id,
|
|
operation,
|
|
`Selected database file set is in use by another process (EBUSY): ${busyMember(cause, path)}`,
|
|
{
|
|
cause,
|
|
retryable: true,
|
|
userMessage:
|
|
"The selected SQLite database is held open by another process without read sharing. Close that application or inspect a copy, then retry.",
|
|
},
|
|
);
|
|
if (
|
|
cause.code === "ENOENT" ||
|
|
cause.code === "ENOTDIR" ||
|
|
cause.code === "ELOOP" ||
|
|
cause.code === "ENAMETOOLONG"
|
|
)
|
|
return new AnalysisInputError(operation, { cause }, [
|
|
{
|
|
path: ["path"],
|
|
reason: "invalid_value",
|
|
message: `Selected database file set could not be read (${String(cause.code)}): ${path}`,
|
|
},
|
|
]);
|
|
}
|
|
return new ProviderAdapterError(SQLITE_PROVIDER_IDENTITY.id, operation, {
|
|
cause,
|
|
diagnostics: {
|
|
phase,
|
|
path,
|
|
reason: cause instanceof Error ? cause.message : String(cause),
|
|
...(cause instanceof OwnedCommandFailure && cause.snapshot !== null
|
|
? {
|
|
failure_kind: cause.reason,
|
|
exit_code: cause.snapshot.exitCode ?? null,
|
|
signal: cause.snapshot.signal ?? null,
|
|
captured_output: { ...capturedSqliteOutput(cause.snapshot) },
|
|
}
|
|
: {}),
|
|
},
|
|
});
|
|
};
|
|
|
|
const ownedCommandFailure = (
|
|
cause: OwnedCommandFailure,
|
|
selectedPath: string,
|
|
workerTimeoutMs: number,
|
|
): AnalysisError | undefined => {
|
|
const operation = "inspect_sqlite_database";
|
|
const capturedOutput =
|
|
cause.snapshot === null ? undefined : capturedSqliteOutput(cause.snapshot);
|
|
const options = {
|
|
cause,
|
|
...(capturedOutput === undefined ? {} : { capturedOutput }),
|
|
};
|
|
// Preserve the same typed primary whether or not owned cleanup also fails.
|
|
const timeout =
|
|
cause.reason === "timeout"
|
|
? new AnalysisTimeoutError(operation, workerTimeoutMs, {
|
|
...options,
|
|
userMessage: `The SQLite worker reached its ${String(workerTimeoutMs)} ms server/provider deadline (worker_timeout_ms). This is not a whole-inspection or MCP client deadline.`,
|
|
remediationAction: `${
|
|
workerTimeoutMs < MAX_SQLITE_WORKER_TIMEOUT_MS
|
|
? `Increase worker_timeout_ms above ${String(workerTimeoutMs)} (integer milliseconds, maximum ${String(MAX_SQLITE_WORKER_TIMEOUT_MS)}), or use rea inspect-sqlite-database <path> --worker-timeout-ms <milliseconds> on the CLI.`
|
|
: `worker_timeout_ms is already at the maximum supported ${String(MAX_SQLITE_WORKER_TIMEOUT_MS)} ms; no higher worker deadline is supported. Report the blocker or narrow the question with caller approval.`
|
|
} This per-call setting needs no server restart. It covers worker startup, queries and reply writing, not snapshot acquisition or final reply reads/cleanup. Allow client headroom for the whole call; increasing only the client deadline does not change the worker budget. Keep the selected database/WAL and requested facts; narrow table/columns/schema_scope/row_limit only if the question permits it. Byte and heap safety limits remain fixed. Resolve incomplete cleanup before retrying; do not repeat the unchanged failed call.`,
|
|
})
|
|
: undefined;
|
|
if (cause.cleanupFailure !== null)
|
|
return createSqliteCleanupError(
|
|
cause.resources,
|
|
{
|
|
reason: cause.cleanupFailure,
|
|
...(timeout === undefined
|
|
? {
|
|
previous_error: {
|
|
failure_kind: cause.reason,
|
|
message: cause.message,
|
|
},
|
|
}
|
|
: {}),
|
|
},
|
|
{
|
|
...options,
|
|
...(timeout === undefined ? {} : { cleanupPrimary: timeout }),
|
|
},
|
|
);
|
|
if (cause.reason === "cancelled")
|
|
return new AnalysisCancelledError(operation, {
|
|
...options,
|
|
cause:
|
|
cause.cancellation === undefined ? cause : cause.cancellation.reason,
|
|
});
|
|
if (timeout !== undefined) return timeout;
|
|
if (cause.reason === "output-limit")
|
|
return new AnalysisOutputError(operation, cause.message, {
|
|
...options,
|
|
userMessage: `SQLite worker diagnostics exceeded the ${String(SQLITE_DATABASE_LIMITS.diagnosticBytes)}-byte capture allowance. This release has no runtime override.`,
|
|
remediationAction: `The SQLite diagnostic capture allowance is ${String(SQLITE_DATABASE_LIMITS.diagnosticBytes)} bytes. This release has no runtime override. worker_timeout_ms does not raise it. Repeating the unchanged request fails the same way.`,
|
|
});
|
|
if (
|
|
cause.snapshot?.stderr.text.includes("JavaScript heap out of memory") ===
|
|
true
|
|
)
|
|
return new AnalysisResourceConstraintError(
|
|
operation,
|
|
"memory",
|
|
"Owned SQLite worker reported JavaScript heap exhaustion.",
|
|
{
|
|
javascript_heap_bytes: 256 * 1024 * 1024,
|
|
},
|
|
{ ...options, diagnostics: { selected_path: selectedPath } },
|
|
);
|
|
return undefined;
|
|
};
|