codemem 0.50.0-beta.2 → 0.50.0-beta.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +268 -56
- package/dist/index.js.map +1 -1
- package/package.json +5 -5
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { ACCOUNT_CONNECTION_MIGRATION_STATEMENTS, ACCOUNT_UNLINK_MIGRATION_STATEMENTS, ALLOWED_MEMORY_KINDS, AUTH_LINK_AUTHORITY_CUTOVER_SQL, ContextOnlyReplayError, CoordinatorAccountLinkError, DEDUP_KEY_BACKFILL_JOB, DEFAULT_COORDINATOR_DB_PATH, DEFAULT_RAW_EVENT_FLUSH_MAX_EVENTS, DedupKeyBackfillRunner, DeviceIdentityError, EXTRACTION_BENCHMARK_QUALITY_WEIGHTS, FILE_CONTEXT_TRANSPORT_MAX_BYTES, FILE_CONTEXT_TRANSPORT_PROFILE, LEGACY_OWNER_RESOLUTION_SCHEMA_STATEMENTS, MUTATING_TOOL_NAMES, MemoryStore, ObserverClient, ObserverOutputError, ObserverOutputTransportError, OwnerProfileEnrollmentError, PROMPT_TRANSPORT_PROTOCOL_RANGE, REF_BACKFILL_JOB, RawEventIngestValidationError, RawEventSweeper, RefBackfillRunner, RemoteCoordinatorRequestError, SCOPE_BACKFILL_JOB, SESSION_CONTEXT_BACKFILL_JOB, SUMMARY_DEDUP_BACKFILL_JOB, ScopeBackfillRunner, SessionContextBackfillRunner, SummaryDedupBackfillRunner, SyncRetentionRunner, TRUSTED_HOOK_MAPPER_OPTIONS, VERSION, VectorModelMigrationRunner, aiBackfillStructuredContent, applyBootstrapSnapshot, applyDistillRule, arePromptTransportProtocolRangesCompatible, atomicReplaceConfigFile, backfillMemoryDedupKeys, backfillNarrativeFromBody, backfillTagsText, backfillVectors, buildBaseUrl, buildDirectPeerAuthHeaders, buildDistillReport, buildPiFlushSignalFromEvent, buildRawEventEnvelopeFromHook, buildRawEventEnvelopeFromPiEvent, buildTieredObserverSelection, buildViewerIdentityTarget, classifyPromptTransportFailure, clonePromptPackAttempt, collectOperationalStatus, compareMemoryRoleReports, connect, connectReadOnly, coordinatorAuthControllerReviewAction, coordinatorAuthStageBaselineSql, coordinatorCreateGroupAction, coordinatorCreateScopeAction, coordinatorD1BaselineMigrations, coordinatorD1ConditionalBaselineMigrations, coordinatorDisableDeviceAction, coordinatorEnableDeviceAction, coordinatorEnrollDeviceAction, coordinatorGrantIdentityGroupAction, coordinatorGrantScopeMembershipAction, coordinatorImportInviteAction, coordinatorListBootstrapGrantsAction, coordinatorListDevicesAction, coordinatorListGroupsAction, coordinatorListJoinRequestsAction, coordinatorListLegacyTeamCompletionsAction, coordinatorListRemovedDevicesAction, coordinatorListScopeMembershipsAction, coordinatorListScopesAction, coordinatorQualifyOwnerAction, coordinatorRemoveDeviceAction, coordinatorRenameDeviceAction, coordinatorReviewInviteAction, coordinatorReviewJoinRequestAction, coordinatorRevokeBootstrapGrantAction, coordinatorRevokeDeviceAction, coordinatorRevokeScopeMembershipAction, coordinatorUpdateScopeAction, createBetterSqliteCoordinatorApp, createCoordinatorRefreshLifecycle, createFileContextRunner, deactivateLowSignalMemories, dedupNearDuplicateMemories, describePiObserverStatus, detectInstallKind, diagnoseLegacyTeamSetupCompletion, dispatchFileContextTransport, draftDistillRule, enrollOwnerProfile, ensureDeviceIdentity, ensureSchemaBootstrapped, estimateExtractionModelCost, expandUserPath, exportMemories, extractApplyPatchPaths, extractionReplayObserverIdentity, fetchAllSnapshotPages, fingerprintPublicKey, flushRawEvents, formatHostPort, getAttributionDiagnostics, getCodememConfigPath, getExtractionBenchmarkProfile, getExtractionModelPricing, getInjectionEvalScenarioPack, getInjectionEvalScenarioPrompts, getMaintenanceJob, getMemoryArtifactReport, getMemoryRoleReport, getRawEventRelinkPlan, getRawEventRelinkReport, getRawEventStatus, getSessionExtractionEval, getSessionExtractionEvalScenario, getUpdateStatus, getWorkspaceCodememConfigPath, hasPendingDedupKeyBackfill, hasPendingRefBackfill, hasPendingScopeBackfill, hasPendingSessionContextBackfill, hasPendingSummaryDedupBackfill, hasUnsyncedSharedMemoryChanges, importMemories, importPiSessions, ingestRawEvents, initDatabase, isAutomaticRecallMeasurement, isCoordinatorControllerAttestationReference, isEmbeddingDisabled, isExplicitUpdateInstallEligible, isReleaseVersionForChannel, judgeDistillReport, legacyTeamCandidateId, linkCoordinatorAccount, linkCoordinatorAccountHeadless, listMaintenanceJobs, listPerPeerScopeSyncState, listRetentionScopeIds, loadObserverConfig, loadPublicKey, loadRuntimeSigningPublicKey, loadSqliteVec, mdnsEnabled, mutateCodememConfigFile, normalizeCoordinatorAccountLinkOrigin, normalizePromptTransportProtocolRange, observerBaseUrlForProviderOverride, parseControllerHistoryEvidence, parseFileContextTransportRequest, peerProjectFilterChangeOnlyNarrows, planReplicationOpsAgePrune, probeCodememViewerLiveness, probeCodememViewerLiveness as probeCodememViewerLiveness$1, probeRequiredNativeRuntime, projectMatchesFilter, promptPackArtifactFingerprint, pruneReplicationOpsUntilCaughtUp, rawEventsGate, readAccountLinkDevice, readCodememConfigFile, readCodememConfigFileAtPath, readCoordinatorAccountLinkStatus, readCoordinatorOwnerReviewLocalEvidence, readCoordinatorSyncConfig, readImportPayload, readPeerProjectFilterAuthority, recordAutomaticRecall, recordPromptPackArtifacts, recordPromptPackTerminal, refreshCoordinatorForDaemon, rememberPeerProjectFilterManagement, removePeerFromThisDevice, renderUnifiedDiff, replayBatchExtraction, replayBatchExtractionWithTierRouting, requestJson, resolveCodememConfigPath, resolveComparablePath, resolveDbPath, resolveHookProject, resolveKeyPaths, resolvePiAgentDir, resolvePiObserverConfig, resolveProject, resolveProjectRoot, retryRawEventFailures, runDeviceRejoin, runSyncDaemon, runSyncPass, scanSecretsRetroactive, schema, scoreExtractionBenchmarkOutput, searchPiSessions, setPeerProjectFilterChecked, syncPassPreflight, tryUpdateRetrievalDelivery, updatePeerAddresses, upgradeCoordinatorAccountSchemaFile, upgradeCoordinatorAuthSchemaFile, upgradeCoordinatorOwnerResolutionSchemaFile, vacuumDatabase, viewerUrl, withDiagnosticStoreSnapshot, writeCodememConfigFile } from "@codemem/core";
|
|
2
|
+
import { ACCOUNT_CONNECTION_MIGRATION_STATEMENTS, ACCOUNT_UNLINK_MIGRATION_STATEMENTS, ALLOWED_MEMORY_KINDS, AUTH_LINK_AUTHORITY_CUTOVER_SQL, ContextOnlyReplayError, CoordinatorAccountLinkError, DEDUP_KEY_BACKFILL_JOB, DEFAULT_COORDINATOR_DB_PATH, DEFAULT_LEDGER_RETENTION_BATCH_SIZE, DEFAULT_RAW_EVENT_FLUSH_MAX_EVENTS, DedupKeyBackfillRunner, DeviceIdentityError, EXTRACTION_BENCHMARK_QUALITY_WEIGHTS, FILE_CONTEXT_TRANSPORT_MAX_BYTES, FILE_CONTEXT_TRANSPORT_PROFILE, LEGACY_OWNER_RESOLUTION_SCHEMA_STATEMENTS, LedgerRetentionRunner, MUTATING_TOOL_NAMES, MemoryStore, NON_SELECTED_EXPOSURE_RETENTION_DAYS, ObserverClient, ObserverOutputError, ObserverOutputTransportError, OwnerProfileEnrollmentError, PROMPT_TRANSPORT_PROTOCOL_RANGE, REF_BACKFILL_JOB, RawEventIngestValidationError, RawEventSweeper, RefBackfillRunner, RemoteCoordinatorRequestError, SCOPE_BACKFILL_JOB, SESSION_CONTEXT_BACKFILL_JOB, SUMMARY_DEDUP_BACKFILL_JOB, ScopeBackfillRunner, SessionContextBackfillRunner, SummaryDedupBackfillRunner, SyncAttemptRetentionRunner, SyncRetentionRunner, TRUSTED_HOOK_MAPPER_OPTIONS, VERSION, VectorModelMigrationRunner, aiBackfillStructuredContent, applyBootstrapSnapshot, applyDistillRule, arePromptTransportProtocolRangesCompatible, atomicReplaceConfigFile, backfillMemoryDedupKeys, backfillNarrativeFromBody, backfillTagsText, backfillVectors, buildBaseUrl, buildDirectPeerAuthHeaders, buildDistillReport, buildPiFlushSignalFromEvent, buildRawEventEnvelopeFromHook, buildRawEventEnvelopeFromPiEvent, buildTieredObserverSelection, buildViewerIdentityTarget, classifyPromptTransportFailure, clonePromptPackAttempt, collectOperationalStatus, compareMemoryRoleReports, connect, connectReadOnly, coordinatorAuthControllerReviewAction, coordinatorAuthStageBaselineSql, coordinatorCreateGroupAction, coordinatorCreateScopeAction, coordinatorD1BaselineMigrations, coordinatorD1ConditionalBaselineMigrations, coordinatorDisableDeviceAction, coordinatorEnableDeviceAction, coordinatorEnrollDeviceAction, coordinatorGrantIdentityGroupAction, coordinatorGrantScopeMembershipAction, coordinatorImportInviteAction, coordinatorListBootstrapGrantsAction, coordinatorListDevicesAction, coordinatorListGroupsAction, coordinatorListJoinRequestsAction, coordinatorListLegacyTeamCompletionsAction, coordinatorListRemovedDevicesAction, coordinatorListScopeMembershipsAction, coordinatorListScopesAction, coordinatorQualifyOwnerAction, coordinatorRemoveDeviceAction, coordinatorRenameDeviceAction, coordinatorReviewInviteAction, coordinatorReviewJoinRequestAction, coordinatorRevokeBootstrapGrantAction, coordinatorRevokeDeviceAction, coordinatorRevokeScopeMembershipAction, coordinatorUpdateScopeAction, createBetterSqliteCoordinatorApp, createCoordinatorRefreshLifecycle, createFileContextRunner, deactivateLowSignalMemories, dedupNearDuplicateMemories, describePiObserverStatus, detectInstallKind, diagnoseLegacyTeamSetupCompletion, dispatchFileContextTransport, draftDistillRule, enrollOwnerProfile, ensureDeviceIdentity, ensureSchemaBootstrapped, estimateExtractionModelCost, expandUserPath, exportMemories, extractApplyPatchPaths, extractionReplayObserverIdentity, fetchAllSnapshotPages, fingerprintPublicKey, flushRawEvents, formatHostPort, getAttributionDiagnostics, getCodememConfigPath, getExtractionBenchmarkProfile, getExtractionModelPricing, getInjectionEvalScenarioPack, getInjectionEvalScenarioPrompts, getMaintenanceJob, getMemoryArtifactReport, getMemoryRoleReport, getRawEventRelinkPlan, getRawEventRelinkReport, getRawEventStatus, getSessionExtractionEval, getSessionExtractionEvalScenario, getUpdateStatus, getWorkspaceCodememConfigPath, hasPendingDedupKeyBackfill, hasPendingRefBackfill, hasPendingScopeBackfill, hasPendingSessionContextBackfill, hasPendingSummaryDedupBackfill, hasUnsyncedSharedMemoryChanges, importMemories, importPiSessions, ingestRawEvents, initDatabase, isAutomaticRecallMeasurement, isCoordinatorControllerAttestationReference, isEmbeddingDisabled, isExplicitUpdateInstallEligible, isReleaseVersionForChannel, judgeDistillReport, legacyTeamCandidateId, linkCoordinatorAccount, linkCoordinatorAccountHeadless, listMaintenanceJobs, listPerPeerScopeSyncState, listRetentionScopeIds, loadObserverConfig, loadPublicKey, loadRuntimeSigningPublicKey, loadSqliteVec, mdnsEnabled, mutateCodememConfigFile, normalizeCoordinatorAccountLinkOrigin, normalizePromptTransportProtocolRange, observerBaseUrlForProviderOverride, parseControllerHistoryEvidence, parseFileContextTransportRequest, peerProjectFilterChangeOnlyNarrows, planReplicationOpsAgePrune, probeCodememViewerLiveness, probeCodememViewerLiveness as probeCodememViewerLiveness$1, probeRequiredNativeRuntime, projectMatchesFilter, promptPackArtifactFingerprint, pruneReplicationOpsUntilCaughtUp, rawEventsGate, readAccountLinkDevice, readCodememConfigFile, readCodememConfigFileAtPath, readCoordinatorAccountLinkStatus, readCoordinatorOwnerReviewLocalEvidence, readCoordinatorSyncConfig, readImportPayload, readPeerProjectFilterAuthority, recordAutomaticRecall, recordPromptPackArtifacts, recordPromptPackTerminal, refreshCoordinatorForDaemon, rememberPeerProjectFilterManagement, removePeerFromThisDevice, renderUnifiedDiff, replayBatchExtraction, replayBatchExtractionWithTierRouting, requestJson, resolveCodememConfigPath, resolveComparablePath, resolveDbPath, resolveHookProject, resolveKeyPaths, resolvePiAgentDir, resolvePiObserverConfig, resolveProject, resolveProjectRoot, retrievalLedgerStats, retryRawEventFailures, runDeviceRejoin, runLedgerRetentionPass, runSyncDaemon, runSyncPass, sanitizeHookPayload, scanSecretsRetroactive, schema, scoreExtractionBenchmarkOutput, searchPiSessions, setPeerProjectFilterChecked, syncPassPreflight, tryUpdateRetrievalDelivery, updatePeerAddresses, upgradeCoordinatorAccountSchemaFile, upgradeCoordinatorAuthSchemaFile, upgradeCoordinatorOwnerResolutionSchemaFile, vacuumDatabase, viewerUrl, withDiagnosticStoreSnapshot, writeCodememConfigFile } from "@codemem/core";
|
|
3
3
|
import { Command, Option } from "commander";
|
|
4
4
|
import omelette from "omelette";
|
|
5
5
|
import { appendFileSync, closeSync, constants, copyFileSync, existsSync, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, realpathSync, renameSync, rmSync, rmdirSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
|
|
@@ -413,7 +413,7 @@ function spoolLiveHookPayload(dir, payload, logPrefix) {
|
|
|
413
413
|
const finalName = `zz-hook-live-${wallTime}-z${monotonicTime}-${suffix}`;
|
|
414
414
|
const tmpPath = join(dir, tmpName);
|
|
415
415
|
try {
|
|
416
|
-
writeFileSync(tmpPath, JSON.stringify(payload), { encoding: "utf8" });
|
|
416
|
+
writeFileSync(tmpPath, JSON.stringify(sanitizeHookPayload(payload)), { encoding: "utf8" });
|
|
417
417
|
renameSync(tmpPath, join(dir, finalName));
|
|
418
418
|
} catch {
|
|
419
419
|
try {
|
|
@@ -745,7 +745,7 @@ function createHookIngestSpool(cfg) {
|
|
|
745
745
|
logHookEvent(`${cfg.logPrefix} failed to create spool dir`);
|
|
746
746
|
return false;
|
|
747
747
|
}
|
|
748
|
-
const payloadText = JSON.stringify(payload);
|
|
748
|
+
const payloadText = JSON.stringify(sanitizeHookPayload(payload));
|
|
749
749
|
const tmpName = `.hook-tmp-${process.pid}-${Date.now()}-${randomInt(1e3, 1e4)}.json`;
|
|
750
750
|
const tmpPath = join(dir, tmpName);
|
|
751
751
|
try {
|
|
@@ -1092,7 +1092,8 @@ function extractModifiedPathsFromHook(payload) {
|
|
|
1092
1092
|
* or when SessionEnd just cleared the state. Failures are swallowed —
|
|
1093
1093
|
* hook commands must never crash on state I/O errors.
|
|
1094
1094
|
*/
|
|
1095
|
-
function trackHookSessionState(
|
|
1095
|
+
function trackHookSessionState(nativePayload) {
|
|
1096
|
+
const payload = sanitizeHookPayload(nativePayload);
|
|
1096
1097
|
const sessionRaw = payload.session_id;
|
|
1097
1098
|
if (typeof sessionRaw !== "string") return null;
|
|
1098
1099
|
const sessionId = sessionRaw.trim();
|
|
@@ -2695,7 +2696,8 @@ async function spoolClaudeHttpFailure(runtime, httpResult) {
|
|
|
2695
2696
|
* Ingest one Claude hook payload through the Viewer queue or local spool.
|
|
2696
2697
|
* Boundary events retain locked direct ingestion as the terminal fallback.
|
|
2697
2698
|
*/
|
|
2698
|
-
async function ingestClaudeHookPayload(
|
|
2699
|
+
async function ingestClaudeHookPayload(nativePayload, opts, deps = {}) {
|
|
2700
|
+
const payload = sanitizeHookPayload(nativePayload);
|
|
2699
2701
|
try {
|
|
2700
2702
|
trackHookSessionState(payload);
|
|
2701
2703
|
} catch {}
|
|
@@ -3123,7 +3125,7 @@ async function ingestCodexHookPayload(payload, opts, deps = {}) {
|
|
|
3123
3125
|
const httpIngest = deps.httpIngest ?? tryHttpIngest$1;
|
|
3124
3126
|
const resolveDb = deps.resolveDb ?? resolveDbPath;
|
|
3125
3127
|
const port = typeof opts.port === "number" ? opts.port : Number.parseInt(opts.port, 10);
|
|
3126
|
-
const ingestPayload = normalizePayloadForIngest(payload);
|
|
3128
|
+
const ingestPayload = normalizePayloadForIngest(sanitizeHookPayload(payload));
|
|
3127
3129
|
let cachedDbPath = null;
|
|
3128
3130
|
const getDbPath = () => {
|
|
3129
3131
|
if (cachedDbPath === null) cachedDbPath = resolveDb(resolveDbOpt(opts));
|
|
@@ -8151,6 +8153,15 @@ function renderAttributionDiagnostics(report) {
|
|
|
8151
8153
|
...report.limitations.map((limitation) => `- ${limitation}`)
|
|
8152
8154
|
].join("\n");
|
|
8153
8155
|
}
|
|
8156
|
+
function renderRetrievalLedger(ledger) {
|
|
8157
|
+
const oldest = ledger.oldest_retrieval_attempt_started_at ?? "none";
|
|
8158
|
+
return [
|
|
8159
|
+
"Retrieval ledger",
|
|
8160
|
+
` Attempts: ${ledger.retrieval_attempts.toLocaleString()} (${ledger.expired_retrieval_attempts.toLocaleString()} past retention), oldest ${oldest}`,
|
|
8161
|
+
` Exposures: ${ledger.retrieval_exposures.toLocaleString()} (${ledger.non_selected_retrieval_exposures.toLocaleString()} not selected, ${ledger.stale_non_selected_retrieval_exposures.toLocaleString()} of them older than ${NON_SELECTED_EXPOSURE_RETENTION_DAYS} days)`,
|
|
8162
|
+
` Outcome evidence: ${ledger.outcome_evidence.toLocaleString()} (${ledger.expired_outcome_evidence.toLocaleString()} past retention)`
|
|
8163
|
+
].join("\n");
|
|
8164
|
+
}
|
|
8154
8165
|
var statsAction = (opts) => {
|
|
8155
8166
|
const store = new MemoryStore(resolveDbPath(resolveDbOpt(opts)));
|
|
8156
8167
|
try {
|
|
@@ -8159,7 +8170,10 @@ var statsAction = (opts) => {
|
|
|
8159
8170
|
console.log(opts.json ? JSON.stringify(report, null, 2) : renderAttributionDiagnostics(report));
|
|
8160
8171
|
return;
|
|
8161
8172
|
}
|
|
8162
|
-
const result =
|
|
8173
|
+
const result = {
|
|
8174
|
+
...store.stats(),
|
|
8175
|
+
retrieval_ledger: retrievalLedgerStats(store.db)
|
|
8176
|
+
};
|
|
8163
8177
|
if (opts.json) {
|
|
8164
8178
|
console.log(JSON.stringify(result, null, 2));
|
|
8165
8179
|
return;
|
|
@@ -8176,6 +8190,7 @@ var statsAction = (opts) => {
|
|
|
8176
8190
|
`Vectors: ${db.vector_rows.toLocaleString()} (${fmtPct(db.vector_coverage)} coverage)`,
|
|
8177
8191
|
`Raw events: ${db.raw_events.toLocaleString()}`
|
|
8178
8192
|
].join("\n"));
|
|
8193
|
+
p.log.step(renderRetrievalLedger(result.retrieval_ledger));
|
|
8179
8194
|
if (result.usage.events.length > 0) {
|
|
8180
8195
|
const provenanceByEvent = new Map(result.usage.provenance.events.map((event) => [event.event, event]));
|
|
8181
8196
|
const lines = result.usage.events.map((event) => formatUsageEvent(event, provenanceByEvent.get(event.event)));
|
|
@@ -8681,7 +8696,7 @@ function createMemoryExtractionReplayCommand() {
|
|
|
8681
8696
|
`Observer: ${result.observer.provider}/${result.observer.model}`,
|
|
8682
8697
|
`Tier: ${result.observer.tier ?? "manual"}`,
|
|
8683
8698
|
`OpenAI Responses: ${result.observer.openaiUseResponses ? "yes" : "no"}`,
|
|
8684
|
-
`Reasoning effort: ${result.observer
|
|
8699
|
+
`Reasoning effort: ${formatTransmittedReasoningEffort(result.observer)}`,
|
|
8685
8700
|
`Classification: ${result.classification.status}`,
|
|
8686
8701
|
`Pass: ${result.evaluation.pass ? "yes" : "no"}`
|
|
8687
8702
|
].join("\n"));
|
|
@@ -8690,13 +8705,7 @@ function createMemoryExtractionReplayCommand() {
|
|
|
8690
8705
|
p.log.warn("Failure reasons:");
|
|
8691
8706
|
for (const reason of result.evaluation.failureReasons) p.log.message(` - ${reason}`);
|
|
8692
8707
|
}
|
|
8693
|
-
p.log.info(
|
|
8694
|
-
`Fresh summaries: ${result.evaluation.counts.summaries}`,
|
|
8695
|
-
`Fresh observations: ${result.evaluation.counts.observations}`,
|
|
8696
|
-
`Summary thread coverage: ${result.evaluation.coverage.summaryThreadCoverage}`,
|
|
8697
|
-
`Observation thread coverage: ${result.evaluation.coverage.observationThreadCoverage}`,
|
|
8698
|
-
`Total thread coverage: ${result.evaluation.coverage.totalThreadCoverage}`
|
|
8699
|
-
].join("\n"));
|
|
8708
|
+
p.log.info(replayCoverageLines(result).join("\n"));
|
|
8700
8709
|
p.outro("done");
|
|
8701
8710
|
} catch (error) {
|
|
8702
8711
|
if (error instanceof ContextOnlyReplayError) {
|
|
@@ -8737,6 +8746,76 @@ function reconcileExtractionBenchmarkStatus(input) {
|
|
|
8737
8746
|
initialQuality: input.initialQuality
|
|
8738
8747
|
};
|
|
8739
8748
|
}
|
|
8749
|
+
/** Transports whose requests never carry a max output token limit. */
|
|
8750
|
+
var UNSENT_REQUEST_LIMIT_TRANSPORTS = /* @__PURE__ */ new Set(["codex_consumer", "opencode_v2"]);
|
|
8751
|
+
/** The effort a replayed request sent, and the requested effort when it was not sent. */
|
|
8752
|
+
function formatTransmittedReasoningEffort(observer) {
|
|
8753
|
+
if (observer.reasoningEffort) return observer.reasoningEffort;
|
|
8754
|
+
if (!observer.requestedReasoningEffort) return "not transmitted";
|
|
8755
|
+
const reason = observer.reasoningEffortFallbackReason;
|
|
8756
|
+
return `not transmitted (requested ${observer.requestedReasoningEffort}${reason ? `; ${reason}` : ""})`;
|
|
8757
|
+
}
|
|
8758
|
+
function benchmarkEffortFields(observer) {
|
|
8759
|
+
return {
|
|
8760
|
+
reasoningEffort: observer.reasoningEffort,
|
|
8761
|
+
requestedReasoningEffort: observer.requestedReasoningEffort,
|
|
8762
|
+
reasoningEffortFallbackApplied: observer.reasoningEffortFallbackApplied,
|
|
8763
|
+
reasoningEffortFallbackReason: observer.reasoningEffortFallbackReason
|
|
8764
|
+
};
|
|
8765
|
+
}
|
|
8766
|
+
/** Applied reasoning settings across runs, plus what was requested and how often it fell back. */
|
|
8767
|
+
function summarizeBenchmarkReasoningReport(runs, observer) {
|
|
8768
|
+
const requested = new Set(runs.map((run) => run.requestedReasoningEffort));
|
|
8769
|
+
return {
|
|
8770
|
+
...summarizeBenchmarkReasoning(runs, observer),
|
|
8771
|
+
requestedReasoningEffort: requested.size > 1 ? "mixed" : runs[0]?.requestedReasoningEffort ?? observer.reasoningEffort,
|
|
8772
|
+
reasoningEffortFallbackRuns: runs.filter((run) => run.reasoningEffortFallbackApplied).length
|
|
8773
|
+
};
|
|
8774
|
+
}
|
|
8775
|
+
function formatBenchmarkReasoningEffort(summary) {
|
|
8776
|
+
const applied = summary.reasoningEffort ?? "not transmitted";
|
|
8777
|
+
if (summary.reasoningEffortFallbackRuns === 0) return applied;
|
|
8778
|
+
return `${applied} (requested ${summary.requestedReasoningEffort}; ${summary.reasoningEffortFallbackRuns} run(s) used the service default)`;
|
|
8779
|
+
}
|
|
8780
|
+
function replayCoverageLines(result) {
|
|
8781
|
+
return [
|
|
8782
|
+
`Prompt: ${formatPromptBudget(result.observer.promptBudget)}`,
|
|
8783
|
+
`Fresh summaries: ${result.evaluation.counts.summaries}`,
|
|
8784
|
+
`Fresh observations: ${result.evaluation.counts.observations}`,
|
|
8785
|
+
`Summary thread coverage: ${result.evaluation.coverage.summaryThreadCoverage}`,
|
|
8786
|
+
`Observation thread coverage: ${result.evaluation.coverage.observationThreadCoverage}`,
|
|
8787
|
+
`Total thread coverage: ${result.evaluation.coverage.totalThreadCoverage}`
|
|
8788
|
+
];
|
|
8789
|
+
}
|
|
8790
|
+
/** One call's prompt lengths, for example "instructions 10419, content 12000 -> 3000 (clipped) of budget 12000". */
|
|
8791
|
+
function formatPromptBudget(budget) {
|
|
8792
|
+
if (!budget) return "not measured";
|
|
8793
|
+
const clipped = budget.contentClipped ? " (clipped)" : "";
|
|
8794
|
+
const over = budget.instructionsOverBudget ? "; instructions exceed the budget" : "";
|
|
8795
|
+
const sections = budget.sections ? `; sections ${budget.sections.map((section) => `${section.name} ${section.chars} -> ${section.sentChars}`).join(", ")}` : "";
|
|
8796
|
+
return `instructions ${budget.instructionChars}, content ${budget.contentChars} -> ${budget.sentContentChars}${clipped} of budget ${budget.maxChars}${over}${sections}`;
|
|
8797
|
+
}
|
|
8798
|
+
/** The budget across benchmark runs and how many runs clipped content or overran it. */
|
|
8799
|
+
function formatBenchmarkPromptBudget(runs) {
|
|
8800
|
+
const budgets = runs.flatMap((run) => run.promptBudget ? [run.promptBudget] : []);
|
|
8801
|
+
if (budgets.length === 0) return "not measured";
|
|
8802
|
+
const limits = new Set(budgets.map((budget) => budget.maxChars));
|
|
8803
|
+
const clipped = budgets.filter((budget) => budget.contentClipped).length;
|
|
8804
|
+
const over = budgets.filter((budget) => budget.instructionsOverBudget).length;
|
|
8805
|
+
return `${limits.size === 1 ? String(budgets[0]?.maxChars) : "mixed"}; content clipped in ${clipped}/${budgets.length} run(s); instructions over budget in ${over}`;
|
|
8806
|
+
}
|
|
8807
|
+
function benchmarkRunObserver(observer) {
|
|
8808
|
+
return {
|
|
8809
|
+
provider: observer.provider,
|
|
8810
|
+
model: observer.model,
|
|
8811
|
+
transport: observer.transport,
|
|
8812
|
+
requestedModel: observer.requestedModel,
|
|
8813
|
+
resolvedModel: observer.resolvedModel,
|
|
8814
|
+
modelFallbackApplied: observer.modelFallbackApplied,
|
|
8815
|
+
modelFallbackReason: observer.modelFallbackReason,
|
|
8816
|
+
promptBudget: observer.promptBudget
|
|
8817
|
+
};
|
|
8818
|
+
}
|
|
8740
8819
|
function summarizeBenchmarkReasoning(runs, fallback) {
|
|
8741
8820
|
const source = runs[0] ?? fallback;
|
|
8742
8821
|
const reasoningEfforts = new Set(runs.map((run) => run.reasoningEffort));
|
|
@@ -8951,6 +9030,7 @@ function createMemoryExtractionBenchmarkCommand() {
|
|
|
8951
9030
|
const outputFailures = [];
|
|
8952
9031
|
const runs = [];
|
|
8953
9032
|
const contextOnlySkips = [];
|
|
9033
|
+
const callFailures = [];
|
|
8954
9034
|
for (let iteration = 1; iteration <= repetitions; iteration += 1) for (const batch of benchmark.batches) {
|
|
8955
9035
|
const scenarioId = batch.scenarioId ?? benchmark.scenarioId;
|
|
8956
9036
|
let selectedObserver = extractionReplayObserverIdentity(observer, null);
|
|
@@ -8980,7 +9060,10 @@ function createMemoryExtractionBenchmarkCommand() {
|
|
|
8980
9060
|
});
|
|
8981
9061
|
continue;
|
|
8982
9062
|
}
|
|
8983
|
-
if (!(error instanceof ObserverOutputError) && !(error instanceof ObserverOutputTransportError))
|
|
9063
|
+
if (!(error instanceof ObserverOutputError) && !(error instanceof ObserverOutputTransportError)) {
|
|
9064
|
+
callFailures.push(benchmarkCallFailure(error, iteration, batch));
|
|
9065
|
+
continue;
|
|
9066
|
+
}
|
|
8984
9067
|
if (opts.observerTierRouting !== true) selectedObserver = extractionReplayObserverIdentity(observer, null);
|
|
8985
9068
|
const failureCost = estimateBenchmarkAttemptCost(selectedObserver.model, error.telemetry.totalUsage);
|
|
8986
9069
|
outputFailures.push({
|
|
@@ -9077,18 +9160,12 @@ function createMemoryExtractionBenchmarkCommand() {
|
|
|
9077
9160
|
status: reconciled.status,
|
|
9078
9161
|
reason: reconciled.reason,
|
|
9079
9162
|
tier: result.observer.tier ?? "manual",
|
|
9080
|
-
|
|
9081
|
-
model: result.observer.model,
|
|
9082
|
-
transport: result.observer.transport,
|
|
9083
|
-
requestedModel: result.observer.requestedModel,
|
|
9084
|
-
resolvedModel: result.observer.resolvedModel,
|
|
9085
|
-
modelFallbackApplied: result.observer.modelFallbackApplied,
|
|
9086
|
-
modelFallbackReason: result.observer.modelFallbackReason,
|
|
9163
|
+
...benchmarkRunObserver(result.observer),
|
|
9087
9164
|
requestedOutputMode: result.observer.requestedOutputMode,
|
|
9088
9165
|
actualOutputMode: result.observer.actualOutputMode,
|
|
9089
9166
|
outputValidation: result.observer.outputValidation,
|
|
9090
9167
|
openaiUseResponses: result.observer.openaiUseResponses,
|
|
9091
|
-
|
|
9168
|
+
...benchmarkEffortFields(result.observer),
|
|
9092
9169
|
reasoningSummary: result.observer.reasoningSummary,
|
|
9093
9170
|
maxOutputTokens: result.observer.maxOutputTokens,
|
|
9094
9171
|
temperature: result.observer.temperature,
|
|
@@ -9164,22 +9241,21 @@ function createMemoryExtractionBenchmarkCommand() {
|
|
|
9164
9241
|
knownElapsedRuns: knownElapsedRuns.length,
|
|
9165
9242
|
totalKnownElapsedMs: knownElapsedRuns.reduce((sum, run) => sum + (run.telemetry.totalElapsedMs ?? 0), 0),
|
|
9166
9243
|
output: summarizeExtractionBenchmarkReporting(attempts),
|
|
9167
|
-
outputFailures
|
|
9244
|
+
outputFailures,
|
|
9245
|
+
callFailed: callFailures.length,
|
|
9246
|
+
callFailures
|
|
9168
9247
|
};
|
|
9248
|
+
if (callFailures.length > 0) process.exitCode = 1;
|
|
9169
9249
|
const uniqueObserverKeys = Array.from(new Set(attempts.map((run) => `${run.provider}::${run.model}::${run.transport}`)));
|
|
9170
9250
|
const firstObserver = attempts[0];
|
|
9171
|
-
const benchmarkReasoning =
|
|
9172
|
-
reasoningEffort: observer.reasoningEffort,
|
|
9173
|
-
reasoningSummary: observer.reasoningSummary
|
|
9174
|
-
});
|
|
9251
|
+
const benchmarkReasoning = summarizeBenchmarkReasoningReport(attempts, observer);
|
|
9175
9252
|
const observerSummary = opts.observerTierRouting === true ? {
|
|
9176
9253
|
provider: uniqueObserverKeys.length === 1 ? firstObserver?.provider ?? observer.provider : "mixed",
|
|
9177
9254
|
model: uniqueObserverKeys.length === 1 ? firstObserver?.model ?? observer.model : "mixed",
|
|
9178
9255
|
transport: uniqueObserverKeys.length === 1 ? firstObserver?.transport ?? "unknown" : "mixed",
|
|
9179
9256
|
tierRouting: true,
|
|
9180
9257
|
openaiUseResponses: uniqueObserverKeys.length === 1 ? firstObserver?.openaiUseResponses ?? observer.openaiUseResponses : null,
|
|
9181
|
-
|
|
9182
|
-
reasoningSummary: benchmarkReasoning.reasoningSummary,
|
|
9258
|
+
...benchmarkReasoning,
|
|
9183
9259
|
maxOutputTokens: uniqueObserverKeys.length === 1 ? firstObserver?.maxOutputTokens ?? null : null,
|
|
9184
9260
|
temperature: uniqueObserverKeys.length === 1 ? firstObserver?.temperature ?? null : null,
|
|
9185
9261
|
transcriptBudget: transcriptBudget ?? null,
|
|
@@ -9190,8 +9266,7 @@ function createMemoryExtractionBenchmarkCommand() {
|
|
|
9190
9266
|
transport: firstObserver?.transport ?? observer.getStatus().runtime,
|
|
9191
9267
|
tierRouting: false,
|
|
9192
9268
|
openaiUseResponses: observer.openaiUseResponses,
|
|
9193
|
-
|
|
9194
|
-
reasoningSummary: benchmarkReasoning.reasoningSummary,
|
|
9269
|
+
...benchmarkReasoning,
|
|
9195
9270
|
maxOutputTokens: firstObserver?.maxOutputTokens ?? null,
|
|
9196
9271
|
temperature: firstObserver?.temperature ?? null,
|
|
9197
9272
|
transcriptBudget: transcriptBudget ?? null,
|
|
@@ -9219,11 +9294,12 @@ function createMemoryExtractionBenchmarkCommand() {
|
|
|
9219
9294
|
`Transport: ${observerSummary.transport}`,
|
|
9220
9295
|
`Tier routing: ${opts.observerTierRouting === true ? "yes" : "no"}`,
|
|
9221
9296
|
`OpenAI Responses: ${observerSummary.openaiUseResponses === null ? "mixed" : observerSummary.openaiUseResponses ? "yes" : "no"}`,
|
|
9222
|
-
`Reasoning effort: ${observerSummary
|
|
9297
|
+
`Reasoning effort: ${formatBenchmarkReasoningEffort(observerSummary)}`,
|
|
9223
9298
|
`Reasoning summary: ${observerSummary.reasoningSummary ?? "not transmitted"}`,
|
|
9224
|
-
`Max output tokens: ${observerSummary.transport
|
|
9299
|
+
`Max output tokens: ${UNSENT_REQUEST_LIMIT_TRANSPORTS.has(observerSummary.transport) ? "not transmitted" : observerSummary.maxOutputTokens ?? "mixed"}`,
|
|
9225
9300
|
`Temperature: ${observerSummary.transport === "mixed" ? "mixed" : observerSummary.temperature ?? "not transmitted"}`,
|
|
9226
9301
|
`Transcript budget override: ${transcriptBudget ?? "default"}`,
|
|
9302
|
+
`Prompt budget: ${formatBenchmarkPromptBudget(attempts)}`,
|
|
9227
9303
|
`Repetitions: ${summary.repetitions}`,
|
|
9228
9304
|
`Context-only skips: ${summary.contextOnlySkipped} (${summary.scheduledTotal} scheduled; ${summary.total} observer attempts)`,
|
|
9229
9305
|
`Shape-quality passes: ${summary.shapeQualityPasses}/${summary.shapeQualityTotal}`,
|
|
@@ -9247,12 +9323,8 @@ function createMemoryExtractionBenchmarkCommand() {
|
|
|
9247
9323
|
const missingRequired = run.quality?.requiredRecall.missingLabelIds.join(",") || "none";
|
|
9248
9324
|
p.log.message(` [${run.batchId}#${run.iteration}] ${run.status.padEnd(18)} ${run.complexity.padEnd(10)} tier=${run.tier.padEnd(6)} expected=${(run.expectedTier ?? "n/a").padEnd(6)} mode=${run.requestedOutputMode}/${run.actualOutputMode} valid=${run.outputValidation} disposition=${run.quality?.summaryDisposition.actual ?? "n/a"}/${run.expectedSummaryDisposition} span=${String(run.analysis.eventSpan).padEnd(3)} prompts=${run.analysis.promptCount} tools=${String(run.analysis.toolCount).padEnd(2)} transcript=${run.analysis.transcriptLength} ${run.provider}/${run.model} [${run.transport}] initial=${run.initial.summaries}s/${run.initial.observations}o final=${run.summaries}s/${run.observations}o quality=${qualityLabel} coverage=${run.quality?.weightedQualityCoverage?.toFixed(3) ?? "n/a"} required_missing=${missingRequired} cost=${costLabel} latency=${latencyLabel} schema_loss=${run.initial.diagnostics?.dataLoss === true ? "yes" : "no"} fallback=${run.modelFallbackApplied ? "yes" : "no"} repair=${run.repairApplied ? "yes" : "no"} retry=${run.retryAttempted ? run.retryReason ?? "yes" : "no"} — ${run.label}`);
|
|
9249
9325
|
}
|
|
9250
|
-
|
|
9251
|
-
|
|
9252
|
-
const latencyLabel = failure.telemetry.totalElapsedMs == null ? "n/a" : `${failure.telemetry.totalElapsedMs}ms`;
|
|
9253
|
-
p.log.error(` [${failure.batchId}#${failure.iteration}] output_failure tier=${failure.tier ?? "n/a"} expected=${failure.expectedTier ?? "n/a"} mode=${failure.requestedOutputMode}/${failure.actualOutputMode} model=${failure.model ?? "unresolved"} cost=${costLabel} latency=${latencyLabel} — ${failure.reason}`);
|
|
9254
|
-
}
|
|
9255
|
-
p.outro("done");
|
|
9326
|
+
logBenchmarkFailures(outputFailures, callFailures);
|
|
9327
|
+
p.outro(callFailures.length > 0 ? `done with ${callFailures.length} failed call(s)` : "done");
|
|
9256
9328
|
} catch (error) {
|
|
9257
9329
|
const message = error instanceof Error ? error.message : "Extraction benchmark failed";
|
|
9258
9330
|
if (opts.json) emitJsonError("extraction_benchmark_failed", message);
|
|
@@ -9342,6 +9414,27 @@ function createMemoryCommand() {
|
|
|
9342
9414
|
function createMemoryDiagnosticsCommand() {
|
|
9343
9415
|
return new Command("memory").configureHelp(helpStyle).description("Inspect memory quality and session links").addCommand(createMemoryRoleReportCommand().name("roles")).addCommand(createMemoryRoleCompareCommand().name("compare")).addCommand(createMemoryArtifactReportCommand().name("artifacts")).addCommand(createMemoryRelinkReportCommand().name("relink")).addCommand(createMemoryRelinkPlanCommand());
|
|
9344
9416
|
}
|
|
9417
|
+
/** Text-mode lines for batches whose output or observer call failed. */
|
|
9418
|
+
function logBenchmarkFailures(outputFailures, callFailures) {
|
|
9419
|
+
for (const failure of outputFailures.toSorted((left, right) => left.iteration - right.iteration || left.batchId - right.batchId)) {
|
|
9420
|
+
const costLabel = failure.cost.total == null ? "n/a" : `$${failure.cost.total.totalCostUsd.toFixed(6)}`;
|
|
9421
|
+
const latencyLabel = failure.telemetry.totalElapsedMs == null ? "n/a" : `${failure.telemetry.totalElapsedMs}ms`;
|
|
9422
|
+
p.log.error(` [${failure.batchId}#${failure.iteration}] output_failure tier=${failure.tier ?? "n/a"} expected=${failure.expectedTier ?? "n/a"} mode=${failure.requestedOutputMode}/${failure.actualOutputMode} model=${failure.model ?? "unresolved"} cost=${costLabel} latency=${latencyLabel} — ${failure.reason}`);
|
|
9423
|
+
}
|
|
9424
|
+
for (const failure of callFailures) p.log.error(` [${failure.batchId}#${failure.iteration}] call_failure ${failure.error} — ${failure.message}`);
|
|
9425
|
+
}
|
|
9426
|
+
var MAX_CALL_FAILURE_MESSAGE_CHARS = 500;
|
|
9427
|
+
function benchmarkCallFailure(error, iteration, batch) {
|
|
9428
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
9429
|
+
return {
|
|
9430
|
+
iteration,
|
|
9431
|
+
batchId: batch.batchId,
|
|
9432
|
+
purpose: batch.purpose,
|
|
9433
|
+
status: "call_failure",
|
|
9434
|
+
error: error instanceof Error ? error.name : "Error",
|
|
9435
|
+
message: message.slice(0, MAX_CALL_FAILURE_MESSAGE_CHARS)
|
|
9436
|
+
};
|
|
9437
|
+
}
|
|
9345
9438
|
function createExtractionDiagnosticsCommand() {
|
|
9346
9439
|
return new Command("extraction").configureHelp(helpStyle).description("Evaluate memory extraction").addCommand(createMemoryExtractionReportCommand().name("report")).addCommand(createMemoryExtractionReplayCommand().name("replay")).addCommand(createMemoryExtractionBenchmarkCommand().name("benchmark"));
|
|
9347
9440
|
}
|
|
@@ -9556,20 +9649,42 @@ function createVectorMigrationRunner(dbPath, signal) {
|
|
|
9556
9649
|
tickBudgetMs: 5e3
|
|
9557
9650
|
});
|
|
9558
9651
|
}
|
|
9559
|
-
function
|
|
9560
|
-
const
|
|
9561
|
-
const dbPath = resolveDbPath(options.dbPath ?? void 0);
|
|
9562
|
-
const store = new MemoryStore(dbPath);
|
|
9563
|
-
const syncConfig = readWorkerSyncConfig(options.configPath);
|
|
9564
|
-
const runners = [];
|
|
9565
|
-
const walCheckpointTimer = setInterval(() => {
|
|
9652
|
+
function startWalCheckpointTimer(store, logger) {
|
|
9653
|
+
const timer = setInterval(() => {
|
|
9566
9654
|
try {
|
|
9567
9655
|
checkpointWalWithoutBlocking(store.db, logger);
|
|
9568
9656
|
} catch (error) {
|
|
9569
9657
|
logger.warn(`WAL checkpoint failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
9570
9658
|
}
|
|
9571
9659
|
}, 3e5);
|
|
9572
|
-
|
|
9660
|
+
timer.unref();
|
|
9661
|
+
return timer;
|
|
9662
|
+
}
|
|
9663
|
+
function createRetentionRunners(dbPath, syncConfig, logger, signal) {
|
|
9664
|
+
const runners = [];
|
|
9665
|
+
if (syncConfig.syncRetentionEnabled) runners.push(new SyncRetentionRunner({
|
|
9666
|
+
dbPath,
|
|
9667
|
+
signal
|
|
9668
|
+
}));
|
|
9669
|
+
runners.push(new LedgerRetentionRunner({
|
|
9670
|
+
dbPath,
|
|
9671
|
+
signal,
|
|
9672
|
+
logger
|
|
9673
|
+
}));
|
|
9674
|
+
runners.push(new SyncAttemptRetentionRunner({
|
|
9675
|
+
dbPath,
|
|
9676
|
+
signal,
|
|
9677
|
+
logger
|
|
9678
|
+
}));
|
|
9679
|
+
return runners;
|
|
9680
|
+
}
|
|
9681
|
+
function startMaintenanceWorkerRuntime(options = {}) {
|
|
9682
|
+
const logger = options.logger ?? defaultLogger;
|
|
9683
|
+
const dbPath = resolveDbPath(options.dbPath ?? void 0);
|
|
9684
|
+
const store = new MemoryStore(dbPath);
|
|
9685
|
+
const syncConfig = readWorkerSyncConfig(options.configPath);
|
|
9686
|
+
const runners = [];
|
|
9687
|
+
const walCheckpointTimer = startWalCheckpointTimer(store, logger);
|
|
9573
9688
|
if (!isEmbeddingDisabled()) runners.push(createVectorMigrationRunner(dbPath, options.signal));
|
|
9574
9689
|
runners.push(createSequentialBackfillCoordinator(store, [
|
|
9575
9690
|
{
|
|
@@ -9622,10 +9737,7 @@ function startMaintenanceWorkerRuntime(options = {}) {
|
|
|
9622
9737
|
signal: options.signal,
|
|
9623
9738
|
logger
|
|
9624
9739
|
}));
|
|
9625
|
-
|
|
9626
|
-
dbPath,
|
|
9627
|
-
signal: options.signal
|
|
9628
|
-
}));
|
|
9740
|
+
runners.push(...createRetentionRunners(dbPath, syncConfig, logger, options.signal));
|
|
9629
9741
|
for (const runner of runners) runner.start();
|
|
9630
9742
|
logger.step("Maintenance worker started");
|
|
9631
9743
|
return {
|
|
@@ -9689,6 +9801,96 @@ function createEmbeddingsCommand(name = "embeddings") {
|
|
|
9689
9801
|
}
|
|
9690
9802
|
createEmbeddingsCommand("embed");
|
|
9691
9803
|
//#endregion
|
|
9804
|
+
//#region src/commands/prune-retrieval-ledger.ts
|
|
9805
|
+
function createDatabasePruneRetrievalLedgerCommand() {
|
|
9806
|
+
const cmd = new Command("prune-retrieval-ledger").configureHelp(helpStyle).description(`Delete retrieval history and outcome evidence past their retention date, and candidates an attempt did not select after ${NON_SELECTED_EXPOSURE_RETENTION_DAYS} days (pinned rows are kept)`).option("--dry-run", "show what is past retention without deleting").option("--batch-size <n>", "retrieval attempts deleted per transaction", String(DEFAULT_LEDGER_RETENTION_BATCH_SIZE));
|
|
9807
|
+
addDbOption(cmd);
|
|
9808
|
+
addJsonOption(cmd);
|
|
9809
|
+
return cmd.action(runPruneRetrievalLedger);
|
|
9810
|
+
}
|
|
9811
|
+
function parseBatchSize(raw) {
|
|
9812
|
+
const value = raw.trim();
|
|
9813
|
+
if (!/^\d+$/.test(value)) return null;
|
|
9814
|
+
const parsed = Number.parseInt(value, 10);
|
|
9815
|
+
return parsed >= 1 && parsed <= 1e4 ? parsed : null;
|
|
9816
|
+
}
|
|
9817
|
+
function describeStats(stats) {
|
|
9818
|
+
return [
|
|
9819
|
+
`Retrieval attempts: ${stats.retrieval_attempts.toLocaleString()} (${stats.expired_retrieval_attempts.toLocaleString()} past retention, removed with their candidates)`,
|
|
9820
|
+
`Retrieval exposures: ${stats.retrieval_exposures.toLocaleString()}`,
|
|
9821
|
+
` Not selected: ${stats.non_selected_retrieval_exposures.toLocaleString()} (${stats.stale_non_selected_retrieval_exposures.toLocaleString()} older than ${NON_SELECTED_EXPOSURE_RETENTION_DAYS} days)`,
|
|
9822
|
+
`Outcome evidence: ${stats.outcome_evidence.toLocaleString()} (${stats.expired_outcome_evidence.toLocaleString()} past retention)`
|
|
9823
|
+
].join("\n");
|
|
9824
|
+
}
|
|
9825
|
+
async function pruneUntilDone(db, batchSize) {
|
|
9826
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
9827
|
+
const totals = {
|
|
9828
|
+
retrieval_attempts: 0,
|
|
9829
|
+
non_selected_retrieval_exposures: 0,
|
|
9830
|
+
outcome_evidence: 0,
|
|
9831
|
+
batches: 0
|
|
9832
|
+
};
|
|
9833
|
+
for (;;) {
|
|
9834
|
+
const pass = await runLedgerRetentionPass(db, {
|
|
9835
|
+
now,
|
|
9836
|
+
batchSize
|
|
9837
|
+
});
|
|
9838
|
+
totals.retrieval_attempts += pass.retrievalAttemptsPurged;
|
|
9839
|
+
totals.non_selected_retrieval_exposures += pass.nonSelectedExposuresPurged;
|
|
9840
|
+
totals.outcome_evidence += pass.outcomeEvidencePurged;
|
|
9841
|
+
totals.batches += pass.batches;
|
|
9842
|
+
const progressed = pass.retrievalAttemptsPurged + pass.nonSelectedExposuresPurged + pass.outcomeEvidencePurged > 0;
|
|
9843
|
+
if (pass.complete || !progressed) return totals;
|
|
9844
|
+
}
|
|
9845
|
+
}
|
|
9846
|
+
function reportFailure$1(opts, code, message, exitCode) {
|
|
9847
|
+
if (opts.json) {
|
|
9848
|
+
emitJsonError(code, message, exitCode);
|
|
9849
|
+
return;
|
|
9850
|
+
}
|
|
9851
|
+
p.log.error(message);
|
|
9852
|
+
process.exitCode = exitCode;
|
|
9853
|
+
}
|
|
9854
|
+
function reportHuman(purged) {
|
|
9855
|
+
if (!purged) {
|
|
9856
|
+
p.outro("Dry run only; no changes made");
|
|
9857
|
+
return;
|
|
9858
|
+
}
|
|
9859
|
+
p.log.success(`Deleted ${purged.retrieval_attempts.toLocaleString()} retrieval attempts with their exposures, ${purged.non_selected_retrieval_exposures.toLocaleString()} candidates that older attempts did not select, and ${purged.outcome_evidence.toLocaleString()} outcome evidence rows`);
|
|
9860
|
+
p.outro("Done. The database file keeps its size until `maintenance database vacuum`.");
|
|
9861
|
+
}
|
|
9862
|
+
async function runPruneRetrievalLedger(opts) {
|
|
9863
|
+
const batchSize = parseBatchSize(opts.batchSize);
|
|
9864
|
+
if (batchSize === null) {
|
|
9865
|
+
reportFailure$1(opts, "invalid_batch_size", `--batch-size must be an integer from 1 to 10000 (got "${opts.batchSize}")`, 2);
|
|
9866
|
+
return;
|
|
9867
|
+
}
|
|
9868
|
+
let db = null;
|
|
9869
|
+
try {
|
|
9870
|
+
db = connect(resolveDbPath(resolveDbOpt(opts)));
|
|
9871
|
+
const before = retrievalLedgerStats(db);
|
|
9872
|
+
if (!opts.json) {
|
|
9873
|
+
p.intro("codemem maintenance database prune-retrieval-ledger");
|
|
9874
|
+
p.log.info(describeStats(before));
|
|
9875
|
+
}
|
|
9876
|
+
const purged = opts.dryRun ? null : await pruneUntilDone(db, batchSize);
|
|
9877
|
+
const after = purged ? retrievalLedgerStats(db) : before;
|
|
9878
|
+
if (opts.json) {
|
|
9879
|
+
const dryRun = Boolean(opts.dryRun);
|
|
9880
|
+
console.log(JSON.stringify({
|
|
9881
|
+
dry_run: dryRun,
|
|
9882
|
+
before,
|
|
9883
|
+
purged,
|
|
9884
|
+
after
|
|
9885
|
+
}, null, 2));
|
|
9886
|
+
} else reportHuman(purged);
|
|
9887
|
+
} catch (error) {
|
|
9888
|
+
reportFailure$1(opts, "prune_retrieval_ledger_failed", error instanceof Error ? error.message : String(error), 1);
|
|
9889
|
+
} finally {
|
|
9890
|
+
db?.close();
|
|
9891
|
+
}
|
|
9892
|
+
}
|
|
9893
|
+
//#endregion
|
|
9692
9894
|
//#region src/commands/maintenance.ts
|
|
9693
9895
|
var maintenanceCmd = new Command("maintenance").configureHelp(helpStyle).description("Inspect jobs and repair stored data");
|
|
9694
9896
|
var statusCmd = new Command("status").configureHelp(helpStyle).description("Show maintenance job status");
|
|
@@ -9754,7 +9956,7 @@ workerCmd.action(async (opts) => {
|
|
|
9754
9956
|
maintenanceCmd.addCommand(statusCmd);
|
|
9755
9957
|
maintenanceCmd.addCommand(workerCmd, { hidden: true });
|
|
9756
9958
|
maintenanceCmd.addCommand(createEmbeddingsCommand());
|
|
9757
|
-
maintenanceCmd.addCommand(new Command("database").configureHelp(helpStyle).description("Inspect and clean up database storage").addCommand(createDatabaseInitCommand()).addCommand(createDatabaseVacuumCommand()).addCommand(createDatabaseStatsCommand()).addCommand(createDatabasePruneEventsCommand()).addCommand(createDatabasePruneHistoryCommand()));
|
|
9959
|
+
maintenanceCmd.addCommand(new Command("database").configureHelp(helpStyle).description("Inspect and clean up database storage").addCommand(createDatabaseInitCommand()).addCommand(createDatabaseVacuumCommand()).addCommand(createDatabaseStatsCommand()).addCommand(createDatabasePruneEventsCommand()).addCommand(createDatabasePruneHistoryCommand()).addCommand(createDatabasePruneRetrievalLedgerCommand()));
|
|
9758
9960
|
maintenanceCmd.addCommand(new Command("memory").configureHelp(helpStyle).description("Deactivate low-quality memories or redact secrets").addCommand(createMemoryPruneCommand()).addCommand(createMemoryDeduplicateCommand()).addCommand(createMemoryRedactSecretsCommand()));
|
|
9759
9961
|
maintenanceCmd.addCommand(new Command("project").configureHelp(helpStyle).description("Repair project names in stored history").addCommand(createProjectRenameCommand()).addCommand(createProjectNormalizeCommand()));
|
|
9760
9962
|
maintenanceCmd.addCommand(new Command("backfill").configureHelp(helpStyle).description("Repair missing fields in historical memories").addCommand(createBackfillTagsCommand()).addCommand(createBackfillDedupKeysCommand()).addCommand(createBackfillNarrativeCommand()).addCommand(createBackfillStructuredCommand()));
|
|
@@ -10377,7 +10579,7 @@ async function ingestPiWithoutBacklog(runtime, boundaryRequested) {
|
|
|
10377
10579
|
}
|
|
10378
10580
|
/** Ingest one Pi event through the Viewer queue or local spool. */
|
|
10379
10581
|
async function ingestPiHookPayload(payload, opts, deps = {}) {
|
|
10380
|
-
const { [BOUNDARY_CEILING_FIELD]: _ignoredCeiling, ...livePayload } = payload;
|
|
10582
|
+
const { [BOUNDARY_CEILING_FIELD]: _ignoredCeiling, ...livePayload } = sanitizeHookPayload(payload);
|
|
10381
10583
|
const stablePayload = stabilizePiBoundaryPayload(livePayload);
|
|
10382
10584
|
const runtime = createPiIngestRuntime(stablePayload, opts, deps);
|
|
10383
10585
|
const boundaryRequested = shouldForcePiBoundaryFlush(stablePayload);
|
|
@@ -10886,6 +11088,14 @@ function forwardChildStderr(source, options) {
|
|
|
10886
11088
|
}
|
|
10887
11089
|
//#endregion
|
|
10888
11090
|
//#region src/observer-runtime-controller.ts
|
|
11091
|
+
function appliedReasoning(status) {
|
|
11092
|
+
if (status?.reasoningEffortRequestSucceeded == null) return void 0;
|
|
11093
|
+
return {
|
|
11094
|
+
effort: status.actualReasoningEffort ?? null,
|
|
11095
|
+
requestSucceeded: status.reasoningEffortRequestSucceeded,
|
|
11096
|
+
fallbackReason: status.reasoningEffortFallbackReason ?? null
|
|
11097
|
+
};
|
|
11098
|
+
}
|
|
10889
11099
|
/** Keep the live observer and saved config separate until in-flight work has drained. */
|
|
10890
11100
|
var ObserverRuntimeController = class {
|
|
10891
11101
|
sweeper;
|
|
@@ -10913,11 +11123,13 @@ var ObserverRuntimeController = class {
|
|
|
10913
11123
|
observer: {},
|
|
10914
11124
|
reasons: []
|
|
10915
11125
|
}).observer : config;
|
|
11126
|
+
const applied = appliedReasoning(config.observerTierRoutingEnabled ? active.tierReasoningEfforts?.[tier] : active);
|
|
10916
11127
|
return {
|
|
10917
11128
|
provider: selected.observerProvider ?? active.provider,
|
|
10918
11129
|
model: selected.observerModel ?? active.model,
|
|
10919
11130
|
runtime: selected.observerRuntime ?? active.runtime,
|
|
10920
|
-
reasoningEffort: selected.observerReasoningEffort ?? null
|
|
11131
|
+
reasoningEffort: selected.observerReasoningEffort ?? null,
|
|
11132
|
+
...applied ? { appliedReasoning: applied } : {}
|
|
10921
11133
|
};
|
|
10922
11134
|
};
|
|
10923
11135
|
return {
|