@codemem/server 0.48.0 → 0.49.0-beta.1
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/application/sync-health.d.ts +5 -0
- package/dist/application/sync-health.d.ts.map +1 -1
- package/dist/feed-cursor.d.ts +31 -0
- package/dist/feed-cursor.d.ts.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +328 -102
- package/dist/index.js.map +1 -1
- package/dist/relay-reachability.d.ts +3 -1
- package/dist/relay-reachability.d.ts.map +1 -1
- package/dist/routes/memory.d.ts.map +1 -1
- package/dist/routes/sync.d.ts +2 -0
- package/dist/routes/sync.d.ts.map +1 -1
- package/package.json +2 -2
- package/static/app.js +45 -45
- package/static/app.js.br +0 -0
- package/static/app.js.gz +0 -0
- package/static/index.html +21 -9
package/dist/index.js
CHANGED
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
import { closeSync, existsSync, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
2
2
|
import { basename, dirname, isAbsolute, join, posix, resolve, win32 } from "node:path";
|
|
3
|
-
import { ACCESS_CLEANUP_OP_TYPE, CodememConfigMutationError, CoordinatorAccountLinkError, CoordinatorReciprocalApprovalRequestChangedError, DEFAULT_TIME_WINDOW_S, FILE_CONTEXT_TRANSPORT_MAX_BYTES, LEGACY_SHARED_REVIEW_SCOPE_ID, LOCAL_DEFAULT_SCOPE_ID, LOCAL_SYNC_CAPABILITY, LOCAL_SYNC_FEATURES, LegacyTeamSetupAdditiveConvergenceError, LegacyTeamSetupRosterCapacityError, MEMORY_FILTER_FIELD_TYPES, MEMORY_FILTER_NAMES, MEMORY_KIND_DESCRIPTIONS, MemoryStore, ObserverClient, PROMPT_TRANSPORT_PROTOCOL_RANGE, REMEMBER_MEMORY_KINDS, RICH_TIER_ANTHROPIC_DEFAULTS, RICH_TIER_DEFAULTS, RawEventIngestValidationError, RecipientPolicyEdgeRequestError, RecipientPolicyTeamRenameError, RemoteCoordinatorRequestError, SCOPE_MEMBERSHIP_REVOCATION_LIMITATION, SIMPLE_TIER_ANTHROPIC_DEFAULTS, SIMPLE_TIER_DEFAULTS, SYNC_AUTHORIZATION_REFRESH_HEADER, SYNC_CAPABILITY_HEADER, SYNC_FEATURES_HEADER, SYNC_SCOPE_QUERY_PARAM, VERSION, VERSION as VERSION$1, VIEWER_IDENTITY_TARGET_KEYS, VIEWER_SERVICE_DISCRIMINATOR, addSyncScopeToBoundary, analyzeProjectScopeMappingChangeGuardrails, analyzeProjectScopeMappingChangesGuardrails, analyzeProjectScopeMappingDeletionGuardrails, applyLegacyTeamSetupCompletionManifest, applyLegacyTeamSetupCompletionManifestAndReturnActivation, applyLocalIdentitySwitch, applyPeerReplicationOps, areLegacyTeamSetupCompletionPolicyFactsAdditivelyCompatible, assertNoLocalIdentityOverride, automaticRecallHealth, buildAuthHeaders, buildBaseUrl, buildDirectPeerAuthHeaders, buildDistillReport, buildFilterBranchesWithContext, buildFilterClausesWithContext, buildPiFlushSignalFromEvent, buildRawEventEnvelopeFromCodexHook, buildRawEventEnvelopeFromHook, buildRawEventEnvelopeFromPiEvent, buildViewerIdentityTarget, canonicalCoordinatorLegacyTeamCompletionManifestJson, canonicalMemoryKind, canonicalRepositoryProjectIdentity, canonicalWorkspaceIdentity, captureAccountOwnerProfilePins, changeCoordinatorAccount, claimRecipientPolicyActorMutations, claimRecipientPolicyPublicationMutation, classifyRecordedSyncFailure, cleanupNonces, clearLegacyTeamSetupDeviceDecision, clonePromptPackAttempt, coerceObserverCommand, commitDeviceIdentityBindings, commitRecipientPolicyEdges, completeLocalIdentitySwitch, containLegacyTeamSetupCompletionConflict, coordinatorArchiveGroupAction, coordinatorAuthControllerReviewAction, coordinatorCreateAddDeviceInviteAction, coordinatorCreateGroupAction, coordinatorCreateInviteAction, coordinatorCreateLegacyTeamCompletionAction, coordinatorCreateScopeAction, coordinatorDisableDeviceAction, coordinatorEnableDeviceAction, coordinatorGetLegacyTeamCompletionAction, coordinatorGrantScopeMembershipAction, coordinatorImportInviteAction, coordinatorListBootstrapGrantsAction, coordinatorListConsumedTeamInvitesAction, coordinatorListDevicesAction, coordinatorListGroupsAction, coordinatorListJoinRequestsAction, coordinatorListLegacyTeamCompletionsAction, coordinatorListReviewedRecipientInviteEvidenceAction, coordinatorListScopeMembershipsAction, coordinatorListScopesAction, coordinatorRemoveDeviceAction, coordinatorRenameDeviceAction, coordinatorRenameGroupAction, coordinatorReviewJoinRequestAction, coordinatorRevokeBootstrapGrantAction, coordinatorRevokeScopeMembershipAction, coordinatorStatusSnapshot, coordinatorUnarchiveGroupAction, coordinatorUpdateScopeAction, countShareableProjectMemories, createCoordinatorReciprocalApproval, decodeInvitePayload, dedupeOrderedIds, defaultSpaceScopeIdForGroup, deleteProjectScopeSettingsMapping, deriveLegacyTeamSetupCompletionManifest, detectInstallKind, deterministicPolicyTeamId, diagnoseStalePeerReceivedRows, discoverLegacyTeamCandidates, dispatchFileContextTransport, ensureDeviceIdentity, executeShareProvisioning, extractInvitePayload, extractReplicationOps, filterReplicationOpsForSyncWithStatus, fingerprintPublicKey, formatHostPort, friendlyDeviceName, fromJson, generateWithOpenCodeV2, getCodememConfigPath, getCodememEnvOverrideValues, getCodememEnvOverrides, getCoordinatorEnrollmentReconciliationIssueSummary, getCoordinatorGroupPreference, getEffectiveCachedScopeAuthorization, getLegacyTeamSetupDraft, getRecipientPolicyAuthorityState, getSemanticIndexDiagnostics, getSyncResetState, getUpdateStatus, ingestRawEvents, inspectFreshLegacyTeamSetupActivation, inspectLegacyTeamSetupActivation, inviteTokenDigest, isAutomaticRecallMeasurement, isLegacyTeamCandidateSelectable, isLegacyTeamSetupProjectMappingIdentity, isPeerTrustBindingCompatible, isProjectSyncEnablementError, isScopedSyncCapability, judgeDistillReport, legacyDecisionCountsAsOwner, legacyTeamCandidateId, legacyTeamCandidateProjectInventory, legacyTeamCanonicalProjectRef, legacyTeamDeviceRef, legacyTeamResolvedProjectRef, legacyTeamSetupApiErrorCode, legacyTeamSetupCompletionActorIds, legacyTeamSetupFailureCheck, linkCoordinatorAccount, listAuthorizedScopesForPeer, listCoordinatorJoinRequests, listDeviceIdentityInventory, listInboundScopeRejections, listLegacyRecipientPolicyProjections, listMaintenanceJobs, listObserverProviderOptions, listOpenCodeV2Models, listPerPeerScopeSyncState, listProjectScopeCandidates, listProjectScopeInventory, listProjectScopeSettingsMappings, listRecipientPolicyIntent, listRecipientPolicyReview, listSharingDomainSettingsScopes, loadMemorySnapshotPageForPeer, loadPrivateKey, loadPublicKey, loadReplicationOpsForPeer, loadRuntimeSigningPublicKey, lookupCoordinatorPeers, markLocalIdentitySwitchBound, markLocalIdentitySwitchNotCommitted, memoryFilterValueMatchesType, mergeAddresses, migrateRecipientPolicyIntent, mutateCodememConfigFile, negotiateSyncCapability, normalizeAddress, normalizeCoordinatorAccountLinkOrigin, normalizeCoordinatorLegacyTeamCompletionManifest, normalizeHumanPresentationName, normalizeSyncCapability, normalizeSyncFeatures, normalizeTeammateName, parseAcceptedProjectIntent, parseBootstrapExpiry, parseFileContextTransportRequest, parsePositiveMemoryId, parseReassignScopePayload, parseRecipientPolicyEdgeCommitRequest, parseStrictInteger, parseSyncScopeRequest, persistShareOperation, personalScopeGrantStatusForPeer, planShareOperation, previewDeviceIdentityBindings, previewLegacyTeamSetupActivation, previewRecipientPolicyEdges, previewRecipientPolicyOnboarding, previewRecipientPolicyOnboardingFromReviewedIntent, probeAvailableCredentials, projectMatchesFilter, projectShareLifecycle, promptPackArtifactFingerprint, readAccountLinkDevice, readAccountOwnerAssociation, readAccountOwnerAssociationRetainedAtMs, readCodememConfigFile, readCompletedLocalIdentitySwitches, readCoordinatorAccountChangeCapabilities, readCoordinatorAccountLinkStatus, readCoordinatorResolvedAccountOwnerReceiptStatus, readCoordinatorResolvedAccountOwnerStatus, readCoordinatorSyncConfig, readOpenLocalIdentitySwitch, readPeerSyncActivity, reassignProjectScopeInventoryProject, recipientInviteAuthoritativeIdentityId, recipientPolicyDigest, recipientReviewedIntentDigest, reconcileCoordinatorEnrollmentSnapshot, reconcileRecipientPolicyProject, reconcileShareOperationAcceptance, reconstructLegacyTeamSetupCompletionManifest, recordAutomaticRecall, recordHighestObservedDirectSignatureVersion, recordLocalIdentitySwitch, recordNonce, recordPromptPackArtifacts, recordPromptPackTerminal, recordSyncTransferObservation, refreshAuthorizedCoordinatorPeerTrust, refreshConfiguredScopeMembershipCache, refreshLegacyTeamCandidate, rejectInboundScopeFailures, renameRecipientPolicyTeam, replayLegacyTeamSetupActivation, repositoryIdentitiesByWorkspace, repositoryIdentityForWorkspace, requestJson, requireLegacyTeamSetupAccessDeltaWithinLimit, resolveCodememConfigPath, resolveDbPath, resolveObserverDefaultModel, resolveObserverRuntime, resolveProject, resolveProjectRoot, resolveRecipientPolicyReview, resolveRecipientPolicyReviewBulk, resolveVisibleScopeIds, resumeDeviceRebind, runDeviceRebind, runSyncPass, schema, scopeAuthorizationFailureReason, searchPiSessions, serializeRecipientPolicyActorMutations, serializeRecipientPolicyCoordinatorGroupMutation, serializeRecipientPolicyPublicationMutation, serializeRecipientPolicyTeamMutation, setLegacyTeamSetupDeviceAssignment, setLegacyTeamSetupDeviceDecision, setLegacyTeamSetupProjectMapping, setLocalSyncFeature, summarizeInboundScopeRejections, summaryLikeSqlPredicate, supportsSyncFeature, syncScopeResetRequiredPayload, toJson, tryUpdateRetrievalDelivery, updatePeerAddresses, upsertCoordinatorGroupPreference, upsertProjectScopeSettingsMappings, validateLegacyTeamSetupCompletionManifest, validateLegacyTeamSetupCompletionManifestBinding, validateRawEvents, verifyDirectPeerSignature, verifyRecipientReviewedIntent, verifySignature, wakeRecipientPoliciesForIdentities, wakeRecipientPoliciesForProjectIdentities } from "@codemem/core";
|
|
3
|
+
import { ACCESS_CLEANUP_OP_TYPE, CodememConfigMutationError, CoordinatorAccountLinkError, CoordinatorReciprocalApprovalRequestChangedError, DEFAULT_TIME_WINDOW_S, FILE_CONTEXT_TRANSPORT_MAX_BYTES, LEGACY_SHARED_REVIEW_SCOPE_ID, LOCAL_DEFAULT_SCOPE_ID, LOCAL_SYNC_CAPABILITY, LOCAL_SYNC_FEATURES, LegacyTeamSetupAdditiveConvergenceError, LegacyTeamSetupRosterCapacityError, MEMORY_FILTER_FIELD_TYPES, MEMORY_FILTER_NAMES, MEMORY_KIND_DESCRIPTIONS, MemoryStore, ObserverClient, PROMPT_TRANSPORT_PROTOCOL_RANGE, REMEMBER_MEMORY_KINDS, RICH_TIER_ANTHROPIC_DEFAULTS, RICH_TIER_DEFAULTS, RawEventIngestValidationError, RecipientPolicyEdgeRequestError, RecipientPolicyTeamRenameError, RemoteCoordinatorRequestError, SCOPE_MEMBERSHIP_REVOCATION_LIMITATION, SIMPLE_TIER_ANTHROPIC_DEFAULTS, SIMPLE_TIER_DEFAULTS, SYNC_AUTHORIZATION_REFRESH_HEADER, SYNC_CAPABILITY_HEADER, SYNC_FEATURES_HEADER, SYNC_SCOPE_QUERY_PARAM, VERSION, VERSION as VERSION$1, VIEWER_IDENTITY_TARGET_KEYS, VIEWER_SERVICE_DISCRIMINATOR, addSyncScopeToBoundary, analyzeProjectScopeMappingChangeGuardrails, analyzeProjectScopeMappingChangesGuardrails, analyzeProjectScopeMappingDeletionGuardrails, applyLegacyTeamSetupCompletionManifest, applyLegacyTeamSetupCompletionManifestAndReturnActivation, applyLocalIdentitySwitch, applyPeerReplicationOps, areLegacyTeamSetupCompletionPolicyFactsAdditivelyCompatible, assertNoLocalIdentityOverride, automaticRecallHealth, buildAuthHeaders, buildBaseUrl, buildDirectPeerAuthHeaders, buildDistillReport, buildFilterBranchesWithContext, buildFilterClausesWithContext, buildPiFlushSignalFromEvent, buildRawEventEnvelopeFromCodexHook, buildRawEventEnvelopeFromHook, buildRawEventEnvelopeFromPiEvent, buildViewerIdentityTarget, canonicalCoordinatorLegacyTeamCompletionManifestJson, canonicalMemoryKind, canonicalRepositoryProjectIdentity, canonicalWorkspaceIdentity, captureAccountOwnerProfilePins, changeCoordinatorAccount, claimRecipientPolicyActorMutations, claimRecipientPolicyPublicationMutation, classifyRecordedSyncFailure, cleanupNonces, clearLegacyTeamSetupDeviceDecision, clonePromptPackAttempt, coerceObserverCommand, commitDeviceIdentityBindings, commitRecipientPolicyEdges, completeLocalIdentitySwitch, containLegacyTeamSetupCompletionConflict, coordinatorArchiveGroupAction, coordinatorAuthControllerReviewAction, coordinatorCreateAddDeviceInviteAction, coordinatorCreateGroupAction, coordinatorCreateInviteAction, coordinatorCreateLegacyTeamCompletionAction, coordinatorCreateScopeAction, coordinatorDisableDeviceAction, coordinatorEnableDeviceAction, coordinatorGetLegacyTeamCompletionAction, coordinatorGrantScopeMembershipAction, coordinatorImportInviteAction, coordinatorListBootstrapGrantsAction, coordinatorListConsumedTeamInvitesAction, coordinatorListDevicesAction, coordinatorListGroupsAction, coordinatorListJoinRequestsAction, coordinatorListLegacyTeamCompletionsAction, coordinatorListReviewedRecipientInviteEvidenceAction, coordinatorListScopeMembershipsAction, coordinatorListScopesAction, coordinatorRemoveDeviceAction, coordinatorRenameDeviceAction, coordinatorRenameGroupAction, coordinatorReviewJoinRequestAction, coordinatorRevokeBootstrapGrantAction, coordinatorRevokeScopeMembershipAction, coordinatorStatusSnapshot, coordinatorUnarchiveGroupAction, coordinatorUpdateScopeAction, countShareableProjectMemories, createCoordinatorReciprocalApproval, decodeInvitePayload, dedupeOrderedIds, defaultSpaceScopeIdForGroup, deleteProjectScopeSettingsMapping, deriveLegacyTeamSetupCompletionManifest, detectInstallKind, deterministicPolicyTeamId, diagnoseStalePeerReceivedRows, discoverLegacyTeamCandidates, dispatchFileContextTransport, ensureDeviceIdentity, executeShareProvisioning, extractInvitePayload, extractReplicationOps, filterReplicationOpsForSyncWithStatus, fingerprintPublicKey, formatHostPort, friendlyDeviceName, fromJson, generateWithOpenCodeV2, getCodememConfigPath, getCodememEnvOverrideValues, getCodememEnvOverrides, getCoordinatorEnrollmentReconciliationIssueSummary, getCoordinatorGroupPreference, getEffectiveCachedScopeAuthorization, getLegacyTeamSetupDraft, getRecipientPolicyAuthorityState, getSemanticIndexDiagnostics, getSyncResetState, getUpdateStatus, ingestRawEvents, inspectFreshLegacyTeamSetupActivation, inspectLegacyTeamSetupActivation, inviteTokenDigest, isAutomaticRecallMeasurement, isLegacyTeamCandidateSelectable, isLegacyTeamSetupProjectMappingIdentity, isPeerTrustBindingCompatible, isProjectSyncEnablementError, isScopedSyncCapability, judgeDistillReport, legacyDecisionCountsAsOwner, legacyTeamCandidateId, legacyTeamCandidateProjectInventory, legacyTeamCanonicalProjectRef, legacyTeamDeviceRef, legacyTeamResolvedProjectRef, legacyTeamSetupApiErrorCode, legacyTeamSetupCompletionActorIds, legacyTeamSetupFailureCheck, linkCoordinatorAccount, listAuthorizedScopesForPeer, listCoordinatorJoinRequests, listDeviceIdentityInventory, listInboundScopeRejections, listLegacyRecipientPolicyProjections, listMaintenanceJobs, listObserverProviderOptions, listOpenCodeV2Models, listPerPeerScopeSyncState, listProjectScopeCandidates, listProjectScopeInventory, listProjectScopeSettingsMappings, listRecipientPolicyIntent, listRecipientPolicyReview, listSharingDomainSettingsScopes, loadMemorySnapshotPageForPeer, loadPrivateKey, loadPublicKey, loadReplicationOpsForPeer, loadRuntimeSigningPublicKey, lookupCoordinatorPeers, markLocalIdentitySwitchBound, markLocalIdentitySwitchNotCommitted, memoryFilterValueMatchesType, mergeAddresses, migrateRecipientPolicyIntent, mutateCodememConfigFile, negotiateSyncCapability, normalizeAddress, normalizeCoordinatorAccountLinkOrigin, normalizeCoordinatorLegacyTeamCompletionManifest, normalizeHumanPresentationName, normalizeSyncCapability, normalizeSyncFeatures, normalizeTeammateName, parseAcceptedProjectIntent, parseBootstrapExpiry, parseFileContextTransportRequest, parsePositiveMemoryId, parseReassignScopePayload, parseRecipientPolicyEdgeCommitRequest, parseStrictInteger, parseSyncScopeRequest, persistShareOperation, personalScopeGrantStatusForPeer, planShareOperation, previewDeviceIdentityBindings, previewLegacyTeamSetupActivation, previewRecipientPolicyEdges, previewRecipientPolicyOnboarding, previewRecipientPolicyOnboardingFromReviewedIntent, probeAvailableCredentials, projectMatchesFilter, projectShareLifecycle, promptPackArtifactFingerprint, readAccountLinkDevice, readAccountOwnerAssociation, readAccountOwnerAssociationRetainedAtMs, readCodememConfigFile, readCompletedLocalIdentitySwitches, readCoordinatorAccountChangeCapabilities, readCoordinatorAccountLinkStatus, readCoordinatorResolvedAccountOwnerReceiptStatus, readCoordinatorResolvedAccountOwnerStatus, readCoordinatorSyncConfig, readOpenLocalIdentitySwitch, readPeerSyncActivity, readRepositoryIdentitySnapshot, reassignProjectScopeInventoryProject, recipientInviteAuthoritativeIdentityId, recipientPolicyDigest, recipientReviewedIntentDigest, reconcileCoordinatorEnrollmentSnapshot, reconcileRecipientPolicyProject, reconcileShareOperationAcceptance, reconstructLegacyTeamSetupCompletionManifest, recordAutomaticRecall, recordHighestObservedDirectSignatureVersion, recordLocalIdentitySwitch, recordNonce, recordPromptPackArtifacts, recordPromptPackTerminal, recordSyncAttempt, recordSyncTransferObservation, refreshAuthorizedCoordinatorPeerTrust, refreshConfiguredScopeMembershipCache, refreshLegacyTeamCandidate, rejectInboundScopeFailures, renameRecipientPolicyTeam, replayLegacyTeamSetupActivation, repositoryIdentitiesByWorkspace, repositoryIdentityForWorkspace, requestJson, requireLegacyTeamSetupAccessDeltaWithinLimit, resolveCodememConfigPath, resolveDbPath, resolveObserverDefaultModel, resolveObserverRuntime, resolveProject, resolveProjectRoot, resolveRecipientPolicyReview, resolveRecipientPolicyReviewBulk, resolveVisibleScopeIds, resumeDeviceRebind, runDeviceRebind, runSyncPass, schema, scopeAuthorizationFailureReason, searchPiSessions, serializeRecipientPolicyActorMutations, serializeRecipientPolicyCoordinatorGroupMutation, serializeRecipientPolicyPublicationMutation, serializeRecipientPolicyTeamMutation, setLegacyTeamSetupDeviceAssignment, setLegacyTeamSetupDeviceDecision, setLegacyTeamSetupProjectMapping, setLocalSyncFeature, summarizeInboundScopeRejections, summaryLikeSqlPredicate, supportsSyncFeature, syncScopeResetRequiredPayload, toJson, tryUpdateRetrievalDelivery, updatePeerAddresses, upsertCoordinatorGroupPreference, upsertProjectScopeSettingsMappings, validateLegacyTeamSetupCompletionManifest, validateLegacyTeamSetupCompletionManifestBinding, validateRawEvents, verifyDirectPeerSignature, verifyRecipientReviewedIntent, verifySignature, wakeRecipientPoliciesForIdentities, wakeRecipientPoliciesForProjectIdentities } from "@codemem/core";
|
|
4
4
|
import { serveStatic } from "@hono/node-server/serve-static";
|
|
5
5
|
import { Hono } from "hono";
|
|
6
6
|
import { createCipheriv, createDecipheriv, createHash, createPrivateKey, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
7
7
|
import { createMiddleware } from "hono/factory";
|
|
8
8
|
import { RateLimiter } from "limiter";
|
|
9
|
+
import { feedFullContextText, projectFeedItem } from "@codemem/core/feed-contract";
|
|
9
10
|
import { and, count, desc, eq, inArray, max, ne, sql } from "drizzle-orm";
|
|
10
11
|
import { drizzle } from "drizzle-orm/better-sqlite3";
|
|
12
|
+
import { Buffer as Buffer$1 } from "node:buffer";
|
|
11
13
|
import { homedir, hostname, networkInterfaces } from "node:os";
|
|
12
14
|
import * as z from "zod";
|
|
13
15
|
import { chmod, link, mkdir, open, readFile, readdir, rm, stat } from "node:fs/promises";
|
|
@@ -2760,8 +2762,61 @@ function healthRoutes(getStore) {
|
|
|
2760
2762
|
});
|
|
2761
2763
|
return app;
|
|
2762
2764
|
}
|
|
2765
|
+
function feedCursorFilterKey(options) {
|
|
2766
|
+
return createHash("sha256").update(JSON.stringify([
|
|
2767
|
+
options.classification,
|
|
2768
|
+
options.project ?? null,
|
|
2769
|
+
options.scope ?? null,
|
|
2770
|
+
options.q ?? null,
|
|
2771
|
+
options.actorId,
|
|
2772
|
+
options.dbPath
|
|
2773
|
+
])).digest("hex");
|
|
2774
|
+
}
|
|
2775
|
+
function isFeedCursorPayload(value) {
|
|
2776
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
|
|
2777
|
+
const payload = value;
|
|
2778
|
+
return Object.keys(payload).length === 4 && payload.v === 1 && typeof payload.created_at === "string" && payload.created_at.length <= 256 && typeof payload.id === "number" && Number.isSafeInteger(payload.id) && payload.id > 0 && typeof payload.filter === "string" && /^[a-f0-9]{64}$/.test(payload.filter);
|
|
2779
|
+
}
|
|
2780
|
+
function tryEncodeFeedCursor(options) {
|
|
2781
|
+
const payload = {
|
|
2782
|
+
v: 1,
|
|
2783
|
+
created_at: options.position.created_at,
|
|
2784
|
+
id: options.position.id,
|
|
2785
|
+
filter: options.filter
|
|
2786
|
+
};
|
|
2787
|
+
if (!isFeedCursorPayload(payload)) return null;
|
|
2788
|
+
const token = Buffer$1.from(JSON.stringify(payload), "utf8").toString("base64url");
|
|
2789
|
+
if (token.length > 4096) return null;
|
|
2790
|
+
return token;
|
|
2791
|
+
}
|
|
2792
|
+
function decodeFeedCursor(options) {
|
|
2793
|
+
const { cursor, filter } = options;
|
|
2794
|
+
if (!cursor || cursor.length > 4096 || !/^[A-Za-z0-9_-]+$/.test(cursor)) return null;
|
|
2795
|
+
const bytes = Buffer$1.from(cursor, "base64url");
|
|
2796
|
+
if (bytes.toString("base64url") !== cursor) return null;
|
|
2797
|
+
const text = bytes.toString("utf8");
|
|
2798
|
+
if (!Buffer$1.from(text, "utf8").equals(bytes)) return null;
|
|
2799
|
+
let payload;
|
|
2800
|
+
try {
|
|
2801
|
+
payload = JSON.parse(text);
|
|
2802
|
+
} catch {
|
|
2803
|
+
return null;
|
|
2804
|
+
}
|
|
2805
|
+
if (!isFeedCursorPayload(payload) || payload.filter !== filter) return null;
|
|
2806
|
+
if (tryEncodeFeedCursor({
|
|
2807
|
+
position: payload,
|
|
2808
|
+
filter
|
|
2809
|
+
}) !== cursor) return null;
|
|
2810
|
+
return {
|
|
2811
|
+
created_at: payload.created_at,
|
|
2812
|
+
id: payload.id
|
|
2813
|
+
};
|
|
2814
|
+
}
|
|
2763
2815
|
//#endregion
|
|
2764
2816
|
//#region src/routes/memory.ts
|
|
2817
|
+
/**
|
|
2818
|
+
* Memory routes — observations, summaries, sessions, projects, pack, artifacts.
|
|
2819
|
+
*/
|
|
2765
2820
|
var MAX_FEED_QUERY_CODE_UNITS = 256;
|
|
2766
2821
|
var searchFunctionsRegisteredStores = /* @__PURE__ */ new WeakSet();
|
|
2767
2822
|
function casefold(value) {
|
|
@@ -3021,18 +3076,18 @@ function countVisibleArtifactRows(store, project) {
|
|
|
3021
3076
|
const row = store.db.prepare(`SELECT COUNT(*) AS total FROM ${from} WHERE ${clauses.join(" AND ")}`).get(...params);
|
|
3022
3077
|
return Number(row?.total ?? 0);
|
|
3023
3078
|
}
|
|
3024
|
-
function
|
|
3079
|
+
function buildMemoryReadQuery(store, options) {
|
|
3025
3080
|
ensureMemorySearchFunctions(store);
|
|
3026
3081
|
const filters = {};
|
|
3027
3082
|
if (options.project) filters.project = options.project;
|
|
3028
3083
|
if (options.scope) filters.ownership_scope = options.scope;
|
|
3029
3084
|
const filterResult = buildViewerMemoryFilters(store, filters);
|
|
3030
|
-
const
|
|
3031
|
-
|
|
3032
|
-
|
|
3033
|
-
options.classification === "summary" ? summaryPredicate : `NOT ${summaryPredicate}
|
|
3034
|
-
|
|
3035
|
-
|
|
3085
|
+
const clauses = ["memory_items.active = 1"];
|
|
3086
|
+
if (options.classification) {
|
|
3087
|
+
const summaryPredicate = summaryLikeSqlPredicate();
|
|
3088
|
+
clauses.push(options.classification === "summary" ? summaryPredicate : `NOT ${summaryPredicate}`);
|
|
3089
|
+
}
|
|
3090
|
+
clauses.push(...filterResult.clauses);
|
|
3036
3091
|
const params = [...filterResult.params];
|
|
3037
3092
|
if (options.q) {
|
|
3038
3093
|
const search = memorySearchSql(options.q);
|
|
@@ -3040,14 +3095,163 @@ function queryMemoryPage(store, options) {
|
|
|
3040
3095
|
params.push(...search.params);
|
|
3041
3096
|
}
|
|
3042
3097
|
const where = clauses.join(" AND ");
|
|
3043
|
-
|
|
3098
|
+
return {
|
|
3099
|
+
from: filterResult.joinSessions ? "memory_items JOIN sessions ON sessions.id = memory_items.session_id" : "memory_items",
|
|
3100
|
+
where,
|
|
3101
|
+
params
|
|
3102
|
+
};
|
|
3103
|
+
}
|
|
3104
|
+
function queryMemoryPage(store, options) {
|
|
3105
|
+
const query = buildMemoryReadQuery(store, options);
|
|
3106
|
+
const { from, params } = query;
|
|
3107
|
+
let where = query.where;
|
|
3108
|
+
let limitClause = "LIMIT ?";
|
|
3109
|
+
if (options.paging.mode === "cursor" && options.paging.position) {
|
|
3110
|
+
where += " AND (memory_items.created_at, memory_items.id) < (?, ?)";
|
|
3111
|
+
params.push(options.paging.position.created_at, options.paging.position.id);
|
|
3112
|
+
}
|
|
3113
|
+
params.push(options.limit + 1);
|
|
3114
|
+
if (options.paging.mode === "offset") {
|
|
3115
|
+
limitClause += " OFFSET ?";
|
|
3116
|
+
params.push(options.paging.offset);
|
|
3117
|
+
}
|
|
3044
3118
|
const rows = store.db.prepare(`SELECT memory_items.* FROM ${from}
|
|
3045
3119
|
WHERE ${where}
|
|
3046
3120
|
ORDER BY memory_items.created_at DESC, memory_items.id DESC
|
|
3047
|
-
|
|
3121
|
+
${limitClause}`).all(...params);
|
|
3048
3122
|
const ownedBySelf = store.buildOwnershipPredicate();
|
|
3049
3123
|
return rows.map((row) => serializeMemoryRow(ownedBySelf, row));
|
|
3050
3124
|
}
|
|
3125
|
+
function parseMemoryPaging(c, store, options) {
|
|
3126
|
+
if (c.req.query("paging") !== "cursor") return {
|
|
3127
|
+
mode: "offset",
|
|
3128
|
+
offset: Math.max(0, queryInt(c.req.query("offset"), 0))
|
|
3129
|
+
};
|
|
3130
|
+
const offset = c.req.query("offset");
|
|
3131
|
+
if (offset !== void 0 && offset !== "0") return null;
|
|
3132
|
+
const filter = feedCursorFilterKey({
|
|
3133
|
+
...options,
|
|
3134
|
+
actorId: store.actorId,
|
|
3135
|
+
dbPath: store.dbPath
|
|
3136
|
+
});
|
|
3137
|
+
const cursor = c.req.query("cursor");
|
|
3138
|
+
if (cursor === void 0) return {
|
|
3139
|
+
mode: "cursor",
|
|
3140
|
+
filter,
|
|
3141
|
+
position: null
|
|
3142
|
+
};
|
|
3143
|
+
const position = decodeFeedCursor({
|
|
3144
|
+
cursor,
|
|
3145
|
+
filter
|
|
3146
|
+
});
|
|
3147
|
+
if (!position) return null;
|
|
3148
|
+
return {
|
|
3149
|
+
mode: "cursor",
|
|
3150
|
+
filter,
|
|
3151
|
+
position
|
|
3152
|
+
};
|
|
3153
|
+
}
|
|
3154
|
+
function memoryPagePagination(options) {
|
|
3155
|
+
const { paging, limit, hasMore, items } = options;
|
|
3156
|
+
if (paging.mode === "offset") return {
|
|
3157
|
+
limit,
|
|
3158
|
+
offset: paging.offset,
|
|
3159
|
+
next_offset: hasMore ? paging.offset + items.length : null,
|
|
3160
|
+
has_more: hasMore
|
|
3161
|
+
};
|
|
3162
|
+
const last = items.at(-1);
|
|
3163
|
+
const nextCursor = hasMore && last ? tryEncodeFeedCursor({
|
|
3164
|
+
position: {
|
|
3165
|
+
created_at: last.created_at,
|
|
3166
|
+
id: last.id
|
|
3167
|
+
},
|
|
3168
|
+
filter: paging.filter
|
|
3169
|
+
}) : null;
|
|
3170
|
+
if (hasMore && nextCursor === null) return null;
|
|
3171
|
+
return {
|
|
3172
|
+
limit,
|
|
3173
|
+
offset: null,
|
|
3174
|
+
next_offset: null,
|
|
3175
|
+
has_more: hasMore,
|
|
3176
|
+
paging: "cursor",
|
|
3177
|
+
next_cursor: nextCursor
|
|
3178
|
+
};
|
|
3179
|
+
}
|
|
3180
|
+
function handleMemoryListRequest(c, getStore, options) {
|
|
3181
|
+
if (c.req.query("paging") === "cursor") c.header("Cache-Control", "no-store");
|
|
3182
|
+
const store = getStore();
|
|
3183
|
+
const limit = Math.max(1, queryInt(c.req.query("limit"), options.defaultLimit));
|
|
3184
|
+
const q = normalizeMemorySearchQuery(c.req.query("q"));
|
|
3185
|
+
const readOptions = {
|
|
3186
|
+
project: c.req.query("project") || void 0,
|
|
3187
|
+
scope: normalizeScope(c.req.query("scope")),
|
|
3188
|
+
q,
|
|
3189
|
+
classification: options.classification
|
|
3190
|
+
};
|
|
3191
|
+
const paging = parseMemoryPaging(c, store, readOptions);
|
|
3192
|
+
if (!paging) return c.json({ error: "invalid_cursor" }, 400);
|
|
3193
|
+
const items = queryMemoryPage(store, {
|
|
3194
|
+
...readOptions,
|
|
3195
|
+
limit,
|
|
3196
|
+
paging
|
|
3197
|
+
});
|
|
3198
|
+
const hasMore = items.length > limit;
|
|
3199
|
+
const result = hasMore ? items.slice(0, limit) : items;
|
|
3200
|
+
const pagination = memoryPagePagination({
|
|
3201
|
+
paging,
|
|
3202
|
+
limit,
|
|
3203
|
+
hasMore,
|
|
3204
|
+
items: result
|
|
3205
|
+
});
|
|
3206
|
+
if (pagination === null) return c.json({ error: "cursor_unavailable" }, 409);
|
|
3207
|
+
attachSessionFields(store, result);
|
|
3208
|
+
attachResolvedIdentityFields(store, result);
|
|
3209
|
+
return c.json({
|
|
3210
|
+
items: c.req.query("view") === "feed" ? feedResponseItems(result, q) : result,
|
|
3211
|
+
pagination
|
|
3212
|
+
});
|
|
3213
|
+
}
|
|
3214
|
+
function fullContextRevision(context) {
|
|
3215
|
+
return createHash("sha256").update(context).digest("hex");
|
|
3216
|
+
}
|
|
3217
|
+
function feedResponseItems(items, query) {
|
|
3218
|
+
return items.map((item) => {
|
|
3219
|
+
const context = feedFullContextText(item);
|
|
3220
|
+
return projectFeedItem({
|
|
3221
|
+
item,
|
|
3222
|
+
query,
|
|
3223
|
+
contextRevision: context === null ? "" : fullContextRevision(context)
|
|
3224
|
+
});
|
|
3225
|
+
});
|
|
3226
|
+
}
|
|
3227
|
+
function queryMemoryContextItem(store, id, options) {
|
|
3228
|
+
const { from, where, params } = buildMemoryReadQuery(store, options);
|
|
3229
|
+
const row = store.db.prepare(`SELECT memory_items.* FROM ${from} WHERE ${where} AND memory_items.id = ?`).get(...params, id);
|
|
3230
|
+
if (!row) return null;
|
|
3231
|
+
return serializeMemoryRow(store.buildOwnershipPredicate(), row);
|
|
3232
|
+
}
|
|
3233
|
+
function handleMemoryContextRequest(c, getStore) {
|
|
3234
|
+
c.header("Cache-Control", "no-store");
|
|
3235
|
+
const rawId = c.req.param("id") ?? "";
|
|
3236
|
+
const id = Number(rawId);
|
|
3237
|
+
if (!/^[1-9][0-9]*$/.test(rawId) || !Number.isSafeInteger(id)) return c.json({ error: "id must be a positive safe integer" }, 400);
|
|
3238
|
+
const classification = c.req.query("classification");
|
|
3239
|
+
if (classification !== void 0 && classification !== "observation" && classification !== "summary") return c.json({ error: "classification must be observation or summary" }, 400);
|
|
3240
|
+
const item = queryMemoryContextItem(getStore(), id, {
|
|
3241
|
+
project: c.req.query("project") || void 0,
|
|
3242
|
+
scope: normalizeScope(c.req.query("scope")),
|
|
3243
|
+
q: normalizeMemorySearchQuery(c.req.query("q")),
|
|
3244
|
+
classification
|
|
3245
|
+
});
|
|
3246
|
+
const context = item ? feedFullContextText(item) : null;
|
|
3247
|
+
if (context === null) return c.json({ error: "memory not found" }, 404);
|
|
3248
|
+
const response = {
|
|
3249
|
+
id,
|
|
3250
|
+
revision: fullContextRevision(context),
|
|
3251
|
+
context
|
|
3252
|
+
};
|
|
3253
|
+
return c.json(response);
|
|
3254
|
+
}
|
|
3051
3255
|
async function handleLegacyPackRequest(c, getStore) {
|
|
3052
3256
|
const store = getStore();
|
|
3053
3257
|
const context = c.req.query("context") || "";
|
|
@@ -3108,64 +3312,14 @@ function memoryRoutes(getStore) {
|
|
|
3108
3312
|
const search = new URL(c.req.url).search;
|
|
3109
3313
|
return c.redirect(`/api/observations${search}`, 301);
|
|
3110
3314
|
});
|
|
3111
|
-
app.get("/api/observations", (c) => {
|
|
3112
|
-
|
|
3113
|
-
|
|
3114
|
-
|
|
3115
|
-
|
|
3116
|
-
|
|
3117
|
-
|
|
3118
|
-
|
|
3119
|
-
project: c.req.query("project") || void 0,
|
|
3120
|
-
scope: normalizeScope(c.req.query("scope")),
|
|
3121
|
-
q: normalizeMemorySearchQuery(c.req.query("q")),
|
|
3122
|
-
classification: "observation"
|
|
3123
|
-
});
|
|
3124
|
-
const hasMore = items.length > limit;
|
|
3125
|
-
const result = hasMore ? items.slice(0, limit) : items;
|
|
3126
|
-
const asRecords = result;
|
|
3127
|
-
attachSessionFields(store, asRecords);
|
|
3128
|
-
attachResolvedIdentityFields(store, asRecords);
|
|
3129
|
-
return c.json({
|
|
3130
|
-
items: asRecords,
|
|
3131
|
-
pagination: {
|
|
3132
|
-
limit,
|
|
3133
|
-
offset,
|
|
3134
|
-
next_offset: hasMore ? offset + result.length : null,
|
|
3135
|
-
has_more: hasMore
|
|
3136
|
-
}
|
|
3137
|
-
});
|
|
3138
|
-
}
|
|
3139
|
-
});
|
|
3140
|
-
app.get("/api/summaries", (c) => {
|
|
3141
|
-
const store = getStore();
|
|
3142
|
-
{
|
|
3143
|
-
const limit = Math.max(1, queryInt(c.req.query("limit"), 50));
|
|
3144
|
-
const offset = Math.max(0, queryInt(c.req.query("offset"), 0));
|
|
3145
|
-
const items = queryMemoryPage(store, {
|
|
3146
|
-
limit,
|
|
3147
|
-
offset,
|
|
3148
|
-
project: c.req.query("project") || void 0,
|
|
3149
|
-
scope: normalizeScope(c.req.query("scope")),
|
|
3150
|
-
q: normalizeMemorySearchQuery(c.req.query("q")),
|
|
3151
|
-
classification: "summary"
|
|
3152
|
-
});
|
|
3153
|
-
const hasMore = items.length > limit;
|
|
3154
|
-
const result = hasMore ? items.slice(0, limit) : items;
|
|
3155
|
-
const asRecords = result;
|
|
3156
|
-
attachSessionFields(store, asRecords);
|
|
3157
|
-
attachResolvedIdentityFields(store, asRecords);
|
|
3158
|
-
return c.json({
|
|
3159
|
-
items: asRecords,
|
|
3160
|
-
pagination: {
|
|
3161
|
-
limit,
|
|
3162
|
-
offset,
|
|
3163
|
-
next_offset: hasMore ? offset + result.length : null,
|
|
3164
|
-
has_more: hasMore
|
|
3165
|
-
}
|
|
3166
|
-
});
|
|
3167
|
-
}
|
|
3168
|
-
});
|
|
3315
|
+
app.get("/api/observations", (c) => handleMemoryListRequest(c, getStore, {
|
|
3316
|
+
classification: "observation",
|
|
3317
|
+
defaultLimit: 20
|
|
3318
|
+
}));
|
|
3319
|
+
app.get("/api/summaries", (c) => handleMemoryListRequest(c, getStore, {
|
|
3320
|
+
classification: "summary",
|
|
3321
|
+
defaultLimit: 50
|
|
3322
|
+
}));
|
|
3169
3323
|
app.get("/api/session", (c) => {
|
|
3170
3324
|
const store = getStore();
|
|
3171
3325
|
{
|
|
@@ -3219,6 +3373,7 @@ function memoryRoutes(getStore) {
|
|
|
3219
3373
|
]);
|
|
3220
3374
|
return c.json(trace);
|
|
3221
3375
|
});
|
|
3376
|
+
app.get("/api/memory/:id/context", (c) => handleMemoryContextRequest(c, getStore));
|
|
3222
3377
|
app.get("/api/memory", (c) => {
|
|
3223
3378
|
const store = getStore();
|
|
3224
3379
|
{
|
|
@@ -5933,6 +6088,15 @@ async function reconcileRecipientPolicyProjectsOperation(store, options) {
|
|
|
5933
6088
|
//#endregion
|
|
5934
6089
|
//#region src/application/sync-health.ts
|
|
5935
6090
|
var STALE_AFTER_MS = 6e5;
|
|
6091
|
+
function readLastSuccessfulConnections(store) {
|
|
6092
|
+
const rows = store.db.prepare(`
|
|
6093
|
+
SELECT p.peer_device_id, a.transport, a.finished_at FROM sync_peers p
|
|
6094
|
+
JOIN sync_attempts a ON a.id = (
|
|
6095
|
+
SELECT id FROM sync_attempts WHERE peer_device_id = p.peer_device_id AND ok <> 0
|
|
6096
|
+
ORDER BY started_at DESC, id DESC LIMIT 1
|
|
6097
|
+
)`);
|
|
6098
|
+
return new Map(rows.all().map((row) => [row.peer_device_id, row]));
|
|
6099
|
+
}
|
|
5936
6100
|
function timestamp(value) {
|
|
5937
6101
|
if (!value) return null;
|
|
5938
6102
|
const parsed = Date.parse(value);
|
|
@@ -5997,11 +6161,22 @@ function readPeerSyncHealth(store, peerIds) {
|
|
|
5997
6161
|
)`);
|
|
5998
6162
|
const failed = /* @__PURE__ */ new Map();
|
|
5999
6163
|
for (const row of latest.all()) if (!row.ok && row.finished_at) failed.set(row.peer_device_id, row.finished_at);
|
|
6000
|
-
|
|
6001
|
-
|
|
6002
|
-
|
|
6003
|
-
|
|
6004
|
-
|
|
6164
|
+
const connections = readLastSuccessfulConnections(store);
|
|
6165
|
+
return new Map(peerIds.map((id) => {
|
|
6166
|
+
const connection = connections.get(id);
|
|
6167
|
+
const transport = connection?.transport;
|
|
6168
|
+
return [id, {
|
|
6169
|
+
...peerSyncHealth(activity.get(id), {
|
|
6170
|
+
now,
|
|
6171
|
+
staleAfterMs,
|
|
6172
|
+
failedAt: failed.get(id)
|
|
6173
|
+
}),
|
|
6174
|
+
last_successful_connection: {
|
|
6175
|
+
transport: transport === "direct" || transport === "relay" ? transport : null,
|
|
6176
|
+
at: connection?.finished_at ?? null
|
|
6177
|
+
}
|
|
6178
|
+
}];
|
|
6179
|
+
}));
|
|
6005
6180
|
}
|
|
6006
6181
|
function overallSyncHealth(peers, options) {
|
|
6007
6182
|
const paired = peers.filter((peer) => peer.pinned);
|
|
@@ -8541,6 +8716,29 @@ function teamSetupRoutes(options) {
|
|
|
8541
8716
|
/**
|
|
8542
8717
|
* Sync routes — status, peers, actors, attempts, pairing, mutations.
|
|
8543
8718
|
*/
|
|
8719
|
+
function manualSyncReachability(resolver, store, peerId) {
|
|
8720
|
+
let route;
|
|
8721
|
+
try {
|
|
8722
|
+
route = resolver?.forPeer(store.db, peerId);
|
|
8723
|
+
} catch {
|
|
8724
|
+
return;
|
|
8725
|
+
}
|
|
8726
|
+
if (!route) return void 0;
|
|
8727
|
+
const signals = [resolver?.signal, route.signal].filter((signal) => signal !== void 0);
|
|
8728
|
+
return {
|
|
8729
|
+
...route,
|
|
8730
|
+
signal: signals.length > 0 ? AbortSignal.any(signals) : void 0,
|
|
8731
|
+
deadlineMs: void 0
|
|
8732
|
+
};
|
|
8733
|
+
}
|
|
8734
|
+
function runManualSyncPass(store, peerId, resolver) {
|
|
8735
|
+
return runSyncPass(store.db, peerId, {
|
|
8736
|
+
keysDir: syncKeysDir(),
|
|
8737
|
+
dbPath: store.dbPath,
|
|
8738
|
+
scanner: store.scanner,
|
|
8739
|
+
reachability: manualSyncReachability(resolver, store, peerId)
|
|
8740
|
+
});
|
|
8741
|
+
}
|
|
8544
8742
|
function safeSkippedSyncDetail(detail) {
|
|
8545
8743
|
if (!detail) return null;
|
|
8546
8744
|
return {
|
|
@@ -11962,11 +12160,14 @@ async function deleteProjectScopeMappingRoute(c, store) {
|
|
|
11962
12160
|
releasePublicationMutation?.();
|
|
11963
12161
|
}
|
|
11964
12162
|
}
|
|
11965
|
-
function projectSharingByRepository(store, operations) {
|
|
12163
|
+
function projectSharingByRepository(store, operations, repositoryIdentitySnapshot) {
|
|
11966
12164
|
const operationById = new Map(operations.map((operation) => [operation.operation_id, operation]));
|
|
11967
12165
|
const sharingByProject = /* @__PURE__ */ new Map();
|
|
11968
12166
|
const mappings = store.db.prepare("SELECT workspace_identity, project_pattern FROM project_scope_mappings").all();
|
|
11969
|
-
const repositoryIdentities = repositoryIdentitiesByWorkspace(store.db, {
|
|
12167
|
+
const repositoryIdentities = repositoryIdentitiesByWorkspace(store.db, {
|
|
12168
|
+
repositoryIdentitySnapshot,
|
|
12169
|
+
knownRepositoryIdentities: mappings.flatMap((mapping) => [mapping.workspace_identity, mapping.project_pattern])
|
|
12170
|
+
});
|
|
11970
12171
|
const seenOperationProjects = /* @__PURE__ */ new Set();
|
|
11971
12172
|
const reviewed = store.db.prepare(`SELECT p.operation_id, p.canonical_project_identity
|
|
11972
12173
|
FROM share_operation_projects p
|
|
@@ -12177,6 +12378,22 @@ function createActorMutationPreflightRoutes(getStore) {
|
|
|
12177
12378
|
app.post("/api/sync/actors/merge", preflight);
|
|
12178
12379
|
return app;
|
|
12179
12380
|
}
|
|
12381
|
+
async function projectScopeInventoryRoute(c, store) {
|
|
12382
|
+
const limit = Math.max(1, queryInt(c.req.query("limit"), 50));
|
|
12383
|
+
const offset = Math.max(0, queryInt(c.req.query("offset"), 0));
|
|
12384
|
+
const repositoryIdentitySnapshot = readRepositoryIdentitySnapshot(store.db);
|
|
12385
|
+
const inventory = listProjectScopeInventory(store.db, {
|
|
12386
|
+
repositoryIdentitySnapshot,
|
|
12387
|
+
identitySource: c.req.query("identity_source"),
|
|
12388
|
+
limit,
|
|
12389
|
+
offset,
|
|
12390
|
+
query: c.req.query("q"),
|
|
12391
|
+
scopeId: c.req.query("scope_id"),
|
|
12392
|
+
status: c.req.query("status")
|
|
12393
|
+
});
|
|
12394
|
+
const sharingByProject = projectSharingByRepository(store, await shareOperationReadModels(store, void 0, false), repositoryIdentitySnapshot);
|
|
12395
|
+
return c.json(serializeProjectScopeInventory(store, inventory, sharingByProject));
|
|
12396
|
+
}
|
|
12180
12397
|
function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
|
|
12181
12398
|
const app = createActorMutationPreflightRoutes(getStore);
|
|
12182
12399
|
app.post("/api/sync/invites/inspect", inspectPairingInvite);
|
|
@@ -12520,11 +12737,7 @@ function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
|
|
|
12520
12737
|
else peerIds = store.db.prepare("SELECT peer_device_id FROM sync_peers").all().map((row) => String(row.peer_device_id ?? "").trim()).filter(Boolean);
|
|
12521
12738
|
const items = [];
|
|
12522
12739
|
for (const peerId of peerIds) {
|
|
12523
|
-
const result = await
|
|
12524
|
-
keysDir: syncKeysDir(),
|
|
12525
|
-
dbPath: store.dbPath,
|
|
12526
|
-
scanner: store.scanner
|
|
12527
|
-
});
|
|
12740
|
+
const result = await runManualSyncPass(store, peerId, options.syncReachability);
|
|
12528
12741
|
items.push({
|
|
12529
12742
|
peer_device_id: peerId,
|
|
12530
12743
|
...result,
|
|
@@ -12788,21 +13001,7 @@ function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
|
|
|
12788
13001
|
}, requests);
|
|
12789
13002
|
return c.json(result, result.results.some((item) => item.status !== "applied") ? 207 : 200);
|
|
12790
13003
|
});
|
|
12791
|
-
app.get("/api/sync/projects",
|
|
12792
|
-
const store = getStore();
|
|
12793
|
-
const limit = Math.max(1, queryInt(c.req.query("limit"), 50));
|
|
12794
|
-
const offset = Math.max(0, queryInt(c.req.query("offset"), 0));
|
|
12795
|
-
const inventory = listProjectScopeInventory(store.db, {
|
|
12796
|
-
identitySource: c.req.query("identity_source"),
|
|
12797
|
-
limit,
|
|
12798
|
-
offset,
|
|
12799
|
-
query: c.req.query("q"),
|
|
12800
|
-
scopeId: c.req.query("scope_id"),
|
|
12801
|
-
status: c.req.query("status")
|
|
12802
|
-
});
|
|
12803
|
-
const sharingByProject = projectSharingByRepository(store, await shareOperationReadModels(store, void 0, false));
|
|
12804
|
-
return c.json(serializeProjectScopeInventory(store, inventory, sharingByProject));
|
|
12805
|
-
});
|
|
13004
|
+
app.get("/api/sync/projects", (c) => projectScopeInventoryRoute(c, getStore()));
|
|
12806
13005
|
app.post("/api/sync/projects/reassign-project", async (c) => {
|
|
12807
13006
|
const store = getStore();
|
|
12808
13007
|
const body = await parseViewerJsonBody(c);
|
|
@@ -15972,7 +16171,8 @@ sqliteTable("sync_attempts", {
|
|
|
15972
16171
|
local_sync_capability: text("local_sync_capability"),
|
|
15973
16172
|
peer_sync_capability: text("peer_sync_capability"),
|
|
15974
16173
|
negotiated_sync_capability: text("negotiated_sync_capability"),
|
|
15975
|
-
failure_category: text("failure_category")
|
|
16174
|
+
failure_category: text("failure_category"),
|
|
16175
|
+
transport: text("transport")
|
|
15976
16176
|
}, (table) => [
|
|
15977
16177
|
index("idx_sync_attempts_peer_started").on(table.peer_device_id, table.started_at),
|
|
15978
16178
|
index("idx_sync_attempts_occurred").on(sql`CASE WHEN ${table.finished_at} IS NULL THEN ${table.started_at} ELSE ${table.finished_at} END`, table.id),
|
|
@@ -17651,6 +17851,7 @@ function buildClient(deps, config) {
|
|
|
17651
17851
|
},
|
|
17652
17852
|
authorityId: config.authorityId,
|
|
17653
17853
|
groupId: config.groupId,
|
|
17854
|
+
pairPacing: options.pairPacingByGroup?.get(config.groupId),
|
|
17654
17855
|
relayAudienceId: config.relayAudienceId,
|
|
17655
17856
|
externalPathname: config.externalPathname,
|
|
17656
17857
|
coordinator: createRelayCoordinatorClient({
|
|
@@ -17659,6 +17860,20 @@ function buildClient(deps, config) {
|
|
|
17659
17860
|
}),
|
|
17660
17861
|
resolvePeerPin: (peerDeviceId) => pinnedPeerKey(db, peerDeviceId),
|
|
17661
17862
|
validateLocal: () => sameDevice(readLocalDevice(db), device),
|
|
17863
|
+
onInboundFailure: (failure) => {
|
|
17864
|
+
const http = failure.httpCode ? ` http=${failure.httpCode}` : "";
|
|
17865
|
+
const diagnostic = `relay_target_failure stage=${failure.stage} reason=${failure.reason}${http}`;
|
|
17866
|
+
try {
|
|
17867
|
+
recordSyncAttempt(db, "", {
|
|
17868
|
+
ok: false,
|
|
17869
|
+
error: diagnostic,
|
|
17870
|
+
failureCategory: "connectivity"
|
|
17871
|
+
});
|
|
17872
|
+
} catch {
|
|
17873
|
+
options.log?.("[codemem] relay target diagnostic could not be persisted", "warn");
|
|
17874
|
+
}
|
|
17875
|
+
options.log?.(`[codemem] ${diagnostic}`, "warn");
|
|
17876
|
+
},
|
|
17662
17877
|
onInbound: (_connection, context) => context.serve({
|
|
17663
17878
|
origin: RELAY_LOGICAL_ORIGIN,
|
|
17664
17879
|
dispatch: deps.dispatch
|
|
@@ -17963,20 +18178,30 @@ function registerViewerBoundary(app, opts) {
|
|
|
17963
18178
|
registry: options.registry
|
|
17964
18179
|
}));
|
|
17965
18180
|
}
|
|
18181
|
+
function registerViewerTargetGuards(options) {
|
|
18182
|
+
const { app, storeFactory } = options;
|
|
18183
|
+
const viewerTargetGuard = viewerTargetQueryGuard(storeFactory);
|
|
18184
|
+
app.use("/api/memories/*", viewerTargetGuard);
|
|
18185
|
+
app.use("/api/memory", viewerTargetGuard);
|
|
18186
|
+
app.use("/api/memory/:id/context", (c, next) => {
|
|
18187
|
+
c.header("Cache-Control", "no-store");
|
|
18188
|
+
return viewerTargetGuard(c, next);
|
|
18189
|
+
});
|
|
18190
|
+
app.use("/api/pi/sessions/search", viewerTargetGuard);
|
|
18191
|
+
}
|
|
17966
18192
|
function createApp(opts) {
|
|
17967
18193
|
const storeFactory = opts?.storeFactory ?? getStore;
|
|
17968
18194
|
const sweeper = opts?.sweeper ?? null;
|
|
17969
18195
|
const getObserver = opts?.getObserver ?? (() => opts?.observer ?? null);
|
|
17970
|
-
const getSyncRuntimeStatus = opts?.getSyncRuntimeStatus ?? (() => null);
|
|
17971
18196
|
let invalidateTeamSetupSummary = () => {};
|
|
17972
18197
|
const app = new Hono();
|
|
17973
18198
|
registerViewerBoundary(app, opts);
|
|
17974
18199
|
app.use("*", preflightHandler());
|
|
17975
18200
|
app.use("*", originGuard({ unsafeGetPathPrefixes: [TEAM_SETUP_ROUTE_PREFIX] }));
|
|
17976
|
-
|
|
17977
|
-
|
|
17978
|
-
|
|
17979
|
-
|
|
18201
|
+
registerViewerTargetGuards({
|
|
18202
|
+
app,
|
|
18203
|
+
storeFactory
|
|
18204
|
+
});
|
|
17980
18205
|
app.route("/", healthRoutes(storeFactory));
|
|
17981
18206
|
app.route("/", diagnosticsRoutes(storeFactory));
|
|
17982
18207
|
app.route("/", statsRoutes(storeFactory));
|
|
@@ -17991,7 +18216,8 @@ function createApp(opts) {
|
|
|
17991
18216
|
}));
|
|
17992
18217
|
registerConfigRoutes(app, opts, sweeper);
|
|
17993
18218
|
app.route("/", rawEventsRoutes(storeFactory, sweeper, opts?.rawEventInbox, opts?.rawEventTarget));
|
|
17994
|
-
app.route("/", syncRoutes(storeFactory, getSyncRuntimeStatus, {
|
|
18219
|
+
app.route("/", syncRoutes(storeFactory, opts?.getSyncRuntimeStatus, {
|
|
18220
|
+
syncReachability: opts?.syncReachability,
|
|
17995
18221
|
loadDeviceIdentityCoordinatorEvidence: opts?.loadDeviceIdentityCoordinatorEvidence,
|
|
17996
18222
|
onRecipientPolicyTeamRenamed: () => invalidateTeamSetupSummary(),
|
|
17997
18223
|
readCoordinatorConfig: opts?.readCoordinatorConfig,
|