codemem 0.47.2 → 0.47.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 CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { ACCOUNT_CONNECTION_MIGRATION_STATEMENTS, ACCOUNT_UNLINK_MIGRATION_STATEMENTS, AUTH_LINK_AUTHORITY_CUTOVER_SQL, ContextOnlyReplayError, CoordinatorAccountLinkError, DEDUP_KEY_BACKFILL_JOB, DEFAULT_COORDINATOR_DB_PATH, 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, coordinatorCreateGroupAction, coordinatorCreateInviteAction, coordinatorCreateScopeAction, coordinatorDisableDeviceAction, coordinatorEnrollDeviceAction, coordinatorGrantIdentityGroupAction, coordinatorGrantScopeMembershipAction, coordinatorImportInviteAction, coordinatorListBootstrapGrantsAction, coordinatorListDevicesAction, coordinatorListGroupsAction, coordinatorListJoinRequestsAction, coordinatorListScopeMembershipsAction, coordinatorListScopesAction, coordinatorQualifyOwnerAction, coordinatorRemoveDeviceAction, coordinatorRenameDeviceAction, coordinatorReviewInviteAction, coordinatorReviewJoinRequestAction, coordinatorRevokeBootstrapGrantAction, coordinatorRevokeDeviceAction, coordinatorRevokeScopeMembershipAction, coordinatorUpdateScopeAction, createBetterSqliteCoordinatorApp, createFileContextRunner, deactivateLowSignalMemories, deactivateLowSignalObservations, dedupNearDuplicateMemories, describePiObserverStatus, detectInstallKind, 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, getSemanticIndexDiagnostics, getSessionExtractionEval, getSessionExtractionEvalScenario, getUpdateStatus, getWorkspaceCodememConfigPath, hasPendingDedupKeyBackfill, hasPendingRefBackfill, hasPendingScopeBackfill, hasPendingSessionContextBackfill, hasPendingSummaryDedupBackfill, hasUnsyncedSharedMemoryChanges, importMemories, importPiSessions, ingestRawEvents, initDatabase, isAutomaticRecallMeasurement, isCoordinatorControllerAttestationReference, isEmbeddingDisabled, isExplicitUpdateInstallEligible, isReleaseVersionForChannel, judgeDistillReport, linkCoordinatorAccount, listMaintenanceJobs, listPerPeerScopeSyncState, listRetentionScopeIds, loadObserverConfig, loadPublicKey, loadRuntimeSigningPublicKey, loadSqliteVec, mdnsEnabled, mutateCodememConfigFile, normalizeCoordinatorAccountLinkOrigin, normalizePromptTransportProtocolRange, observerBaseUrlForProviderOverride, parseControllerHistoryEvidence, parseFileContextTransportRequest, planReplicationOpsAgePrune, probeCodememViewerLiveness, probeCodememViewerLiveness as probeCodememViewerLiveness$1, probeRequiredNativeRuntime, projectMatchesFilter, promptPackArtifactFingerprint, pruneReplicationOpsUntilCaughtUp, rawEventsGate, readAccountLinkDevice, readCodememConfigFile, readCodememConfigFileAtPath, readCoordinatorAccountLinkStatus, readCoordinatorOwnerReviewLocalEvidence, readCoordinatorSyncConfig, readImportPayload, recordAutomaticRecall, recordPromptPackArtifacts, recordPromptPackTerminal, renderUnifiedDiff, replayBatchExtraction, replayBatchExtractionWithTierRouting, requestJson, resolveCodememConfigPath, resolveComparablePath, resolveDbPath, resolveHookProject, resolveKeyPaths, resolvePiAgentDir, resolvePiObserverConfig, resolveProject, resolveProjectRoot, retryRawEventFailures, runSyncDaemon, runSyncPass, scanSecretsRetroactive, schema, scoreExtractionBenchmarkOutput, searchPiSessions, setPeerProjectFilter, syncPassPreflight, tryUpdateRetrievalDelivery, updatePeerAddresses, upgradeCoordinatorAccountSchemaFile, upgradeCoordinatorAuthSchemaFile, upgradeCoordinatorOwnerResolutionSchemaFile, vacuumDatabase, viewerUrl, writeCodememConfigFile } from "@codemem/core";
2
+ import { ACCOUNT_CONNECTION_MIGRATION_STATEMENTS, ACCOUNT_UNLINK_MIGRATION_STATEMENTS, AUTH_LINK_AUTHORITY_CUTOVER_SQL, ContextOnlyReplayError, CoordinatorAccountLinkError, DEDUP_KEY_BACKFILL_JOB, DEFAULT_COORDINATOR_DB_PATH, 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, coordinatorCreateGroupAction, coordinatorCreateInviteAction, coordinatorCreateScopeAction, coordinatorDisableDeviceAction, coordinatorEnrollDeviceAction, coordinatorGrantIdentityGroupAction, coordinatorGrantScopeMembershipAction, coordinatorImportInviteAction, coordinatorListBootstrapGrantsAction, coordinatorListDevicesAction, coordinatorListGroupsAction, coordinatorListJoinRequestsAction, coordinatorListLegacyTeamCompletionsAction, coordinatorListScopeMembershipsAction, coordinatorListScopesAction, coordinatorQualifyOwnerAction, coordinatorRemoveDeviceAction, coordinatorRenameDeviceAction, coordinatorReviewInviteAction, coordinatorReviewJoinRequestAction, coordinatorRevokeBootstrapGrantAction, coordinatorRevokeDeviceAction, coordinatorRevokeScopeMembershipAction, coordinatorUpdateScopeAction, createBetterSqliteCoordinatorApp, createFileContextRunner, deactivateLowSignalMemories, deactivateLowSignalObservations, 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, getSemanticIndexDiagnostics, getSessionExtractionEval, getSessionExtractionEvalScenario, getUpdateStatus, getWorkspaceCodememConfigPath, hasPendingDedupKeyBackfill, hasPendingRefBackfill, hasPendingScopeBackfill, hasPendingSessionContextBackfill, hasPendingSummaryDedupBackfill, hasUnsyncedSharedMemoryChanges, importMemories, importPiSessions, ingestRawEvents, initDatabase, isAutomaticRecallMeasurement, isCoordinatorControllerAttestationReference, isEmbeddingDisabled, isExplicitUpdateInstallEligible, isReleaseVersionForChannel, judgeDistillReport, legacyTeamCandidateId, linkCoordinatorAccount, listMaintenanceJobs, listPerPeerScopeSyncState, listRetentionScopeIds, loadObserverConfig, loadPublicKey, loadRuntimeSigningPublicKey, loadSqliteVec, mdnsEnabled, mutateCodememConfigFile, normalizeCoordinatorAccountLinkOrigin, normalizePromptTransportProtocolRange, observerBaseUrlForProviderOverride, parseControllerHistoryEvidence, parseFileContextTransportRequest, planReplicationOpsAgePrune, probeCodememViewerLiveness, probeCodememViewerLiveness as probeCodememViewerLiveness$1, probeRequiredNativeRuntime, projectMatchesFilter, promptPackArtifactFingerprint, pruneReplicationOpsUntilCaughtUp, rawEventsGate, readAccountLinkDevice, readCodememConfigFile, readCodememConfigFileAtPath, readCoordinatorAccountLinkStatus, readCoordinatorOwnerReviewLocalEvidence, readCoordinatorSyncConfig, readImportPayload, recordAutomaticRecall, recordPromptPackArtifacts, recordPromptPackTerminal, renderUnifiedDiff, replayBatchExtraction, replayBatchExtractionWithTierRouting, requestJson, resolveCodememConfigPath, resolveComparablePath, resolveDbPath, resolveHookProject, resolveKeyPaths, resolvePiAgentDir, resolvePiObserverConfig, resolveProject, resolveProjectRoot, retryRawEventFailures, runSyncDaemon, runSyncPass, scanSecretsRetroactive, schema, scoreExtractionBenchmarkOutput, searchPiSessions, setPeerProjectFilter, 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, copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, rmdirSync, statSync, unlinkSync, writeFileSync } from "node:fs";
@@ -2560,6 +2560,103 @@ function buildCoordinatorAccountSchemaCommand() {
2560
2560
  return command;
2561
2561
  }
2562
2562
  //#endregion
2563
+ //#region src/commands/coordinator-diagnose-team-setup.ts
2564
+ function coordinatorTarget(options) {
2565
+ const config = readCoordinatorSyncConfig(options.config ? readCodememConfigFileAtPath(options.config) : readCodememConfigFile());
2566
+ const coordinatorId = config.syncCoordinatorUrl ? buildBaseUrl(config.syncCoordinatorUrl) : "";
2567
+ if (!coordinatorId || !config.syncCoordinatorAdminSecret) throw new Error("team_setup_diagnosis_configuration_unavailable");
2568
+ return {
2569
+ coordinatorId,
2570
+ auth: {
2571
+ remoteUrl: coordinatorId,
2572
+ adminSecret: config.syncCoordinatorAdminSecret,
2573
+ timeoutS: Math.max(1, config.syncCoordinatorTimeoutS)
2574
+ },
2575
+ groups: config.syncCoordinatorGroups
2576
+ };
2577
+ }
2578
+ async function diagnoseGroup(store, target, groupId) {
2579
+ const records = await coordinatorListLegacyTeamCompletionsAction({
2580
+ groupIds: [groupId],
2581
+ ...target.auth
2582
+ });
2583
+ const devices = await coordinatorListDevicesAction({
2584
+ groupId,
2585
+ includeDisabled: true,
2586
+ ...target.auth
2587
+ });
2588
+ const candidateRef = legacyTeamCandidateId(target.coordinatorId, groupId);
2589
+ return diagnoseLegacyTeamSetupCompletion(store.db, {
2590
+ coordinatorId: target.coordinatorId,
2591
+ groupId,
2592
+ projection: {
2593
+ localActorId: store.actorId,
2594
+ localDeviceId: store.deviceId
2595
+ },
2596
+ completionManifest: records.find((record) => record.group_id === groupId && record.manifest.candidate_ref === candidateRef)?.manifest ?? null,
2597
+ freshRoster: devices.map((device) => ({
2598
+ deviceId: device.device_id,
2599
+ fingerprint: device.fingerprint,
2600
+ displayName: device.display_name ?? "Device",
2601
+ enabled: device.enabled === 1
2602
+ }))
2603
+ });
2604
+ }
2605
+ function describeStep(step, okText) {
2606
+ if (step.ok) return okText;
2607
+ return step.check ? `${step.code} at ${step.check}` : step.code;
2608
+ }
2609
+ function printDiagnosis(diagnosis) {
2610
+ const lines = [`Candidate: ${diagnosis.candidateRef}`, `Coordinator completion: ${describeStep(diagnosis.manifest, `completed ${diagnosis.completedAt}`)}`];
2611
+ if (diagnosis.unavailableScopeIds.length > 0) lines.push(`Spaces not active here: ${diagnosis.unavailableScopeIds.join(", ")}`);
2612
+ const local = diagnosis.localCompletion;
2613
+ lines.push(`Local completion: ${describeStep(local, local.ok ? `identical=${local.identical} additive=${local.additive}` : "")}`);
2614
+ const apply = diagnosis.apply;
2615
+ if (apply) {
2616
+ const outcome = apply.ok ? `would leave Team ${apply.teamStatus}/${apply.migrationState} with ${apply.grantedProjects} Project(s) shared` : "";
2617
+ lines.push(`Apply (dry run): ${describeStep(apply, outcome)}`);
2618
+ }
2619
+ (apply && !apply.ok ? p.log.warn : p.log.info)(`${diagnosis.groupId}\n${lines.map((line) => ` ${line}`).join("\n")}`);
2620
+ }
2621
+ async function diagnoseTeamSetup(group, options) {
2622
+ try {
2623
+ const target = coordinatorTarget(options);
2624
+ const groups = group ? [group] : target.groups;
2625
+ if (groups.length === 0) throw new Error("team_setup_diagnosis_no_groups");
2626
+ const diagnoses = await withDiagnosticStoreSnapshot(resolveDbPath(resolveDbOpt(options)), async (store) => {
2627
+ const results = [];
2628
+ for (const groupId of groups) results.push(await diagnoseGroup(store, target, groupId));
2629
+ return results;
2630
+ });
2631
+ if (options.json) {
2632
+ console.log(JSON.stringify({
2633
+ coordinator_id: target.coordinatorId,
2634
+ groups: diagnoses
2635
+ }));
2636
+ return;
2637
+ }
2638
+ p.intro("codemem coordinator diagnose-team-setup");
2639
+ for (const diagnosis of diagnoses) printDiagnosis(diagnosis);
2640
+ p.outro("Dry run only: no changes were made.");
2641
+ } catch (error) {
2642
+ const message = error instanceof Error ? error.message : String(error);
2643
+ if (options.json) {
2644
+ emitJsonError("team_setup_diagnosis_failed", message);
2645
+ return;
2646
+ }
2647
+ p.log.error(message);
2648
+ process.exitCode = 1;
2649
+ }
2650
+ }
2651
+ function buildCoordinatorDiagnoseTeamSetupCommand() {
2652
+ const command = new Command("diagnose-team-setup").configureHelp(helpStyle).description("Dry-run the coordinator's legacy Team setup completion against this database and report which check fails").argument("[group]", "coordinator group ID (default: configured groups)");
2653
+ addDbOption(command);
2654
+ addConfigOption(command);
2655
+ addJsonOption(command);
2656
+ command.action(diagnoseTeamSetup);
2657
+ return command;
2658
+ }
2659
+ //#endregion
2563
2660
  //#region src/commands/coordinator-enroll-owner.ts
2564
2661
  var CAPTURE_WARNING = "Stop OpenCode capture, the Viewer and the sync daemon before preparing or resuming. Keep them stopped until Verified coordinator Identity is shown. Any capture/history change during the browser ceremony can stop local adoption after the server commits, leaving DB and config separate and requiring operator review.";
2565
2662
  function showPrivateBrowserLink$1(privateUrl) {
@@ -3604,6 +3701,7 @@ function createCoordinatorCommandRoot() {
3604
3701
  cmd.addCommand(buildCoordinatorQualifyOwnerCommand());
3605
3702
  cmd.addCommand(buildCoordinatorGrantIdentityGroupCommand());
3606
3703
  cmd.addCommand(buildCoordinatorRevokeDeviceCommand());
3704
+ cmd.addCommand(buildCoordinatorDiagnoseTeamSetupCommand());
3607
3705
  cmd.addCommand(buildCoordinatorAuthSchemaCommand());
3608
3706
  cmd.addCommand(buildCoordinatorAccountSchemaCommand());
3609
3707
  return cmd;