@narumitw/pi-sync 0.57.2 → 0.57.5
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/README.md +5 -1
- package/dist/chunks/{agent-plan-K3CRYVXV.ts → agent-plan-3L7CRFDM.ts} +28 -11
- package/dist/chunks/agent-plan-3L7CRFDM.ts.map +7 -0
- package/dist/chunks/agent-refusal-retry-AH7TXOQT.ts +69 -0
- package/dist/chunks/agent-refusal-retry-AH7TXOQT.ts.map +7 -0
- package/dist/chunks/{agent-runner-E2JU2VZ6.ts → agent-runner-WMSCKSCB.ts} +7 -5
- package/dist/chunks/agent-runner-WMSCKSCB.ts.map +7 -0
- package/dist/chunks/{agent-store-A3F6IYWZ.ts → agent-store-55CZOCPX.ts} +25 -3
- package/dist/chunks/agent-store-55CZOCPX.ts.map +7 -0
- package/dist/chunks/{chunk-QGK445K7.ts → chunk-3ST7RSYN.ts} +1 -1
- package/dist/chunks/chunk-3ST7RSYN.ts.map +7 -0
- package/dist/chunks/{chunk-OWBAZA6J.ts → chunk-DT6TOCIG.ts} +2 -2
- package/dist/chunks/{chunk-JJTARUSO.ts → chunk-JCH3VXIO.ts} +3 -2
- package/dist/chunks/{chunk-JJTARUSO.ts.map → chunk-JCH3VXIO.ts.map} +2 -2
- package/dist/chunks/{chunk-OEWQVWLC.ts → chunk-ORGBI36T.ts} +4 -4
- package/dist/chunks/{chunk-EUMINX7L.ts → chunk-P7DD5PWZ.ts} +2 -2
- package/dist/chunks/{chunk-VJN7KU4J.ts → chunk-PG7NMFP2.ts} +83 -18
- package/dist/chunks/chunk-PG7NMFP2.ts.map +7 -0
- package/dist/chunks/{chunk-T3NC77TU.ts → chunk-R75IHAOJ.ts} +45 -18
- package/dist/chunks/chunk-R75IHAOJ.ts.map +7 -0
- package/dist/chunks/{chunk-4TQWFLOQ.ts → chunk-U3XRI2HF.ts} +28 -197
- package/dist/chunks/chunk-U3XRI2HF.ts.map +7 -0
- package/dist/chunks/chunk-WD6FJHCK.ts +140 -0
- package/dist/chunks/chunk-WD6FJHCK.ts.map +7 -0
- package/dist/chunks/{conflict-review-ZCGWFKEK.ts → conflict-review-T7GSOKNG.ts} +9 -8
- package/dist/chunks/{conflict-review-ZCGWFKEK.ts.map → conflict-review-T7GSOKNG.ts.map} +1 -1
- package/dist/chunks/{continuous-record-LFRVXQBD.ts → continuous-record-SQJ47CXN.ts} +3 -3
- package/dist/chunks/{continuous-sync-LAIMSW7D.ts → continuous-sync-U4HIKPQK.ts} +9 -9
- package/dist/chunks/{continuous-sync-LAIMSW7D.ts.map → continuous-sync-U4HIKPQK.ts.map} +2 -2
- package/dist/chunks/{git-backend-KYDZ673X.ts → git-backend-NYKSG5X6.ts} +4 -4
- package/dist/chunks/{manager-result-dispatcher-AGBBVDDS.ts → manager-result-dispatcher-HOCM2GDA.ts} +4 -4
- package/dist/chunks/{manager-ui-PSA2L6CE.ts → manager-ui-FXXO6TW4.ts} +54 -17
- package/dist/chunks/manager-ui-FXXO6TW4.ts.map +7 -0
- package/dist/chunks/{remote-selection-ui-5725JDNC.ts → remote-selection-ui-YFPGYGNE.ts} +3 -3
- package/dist/chunks/{s3-backend-Y7WSCLJI.ts → s3-backend-F7PR5FB3.ts} +4 -4
- package/dist/chunks/{setup-wizard-SOYOJQKP.ts → setup-wizard-OVHZYXNW.ts} +2 -2
- package/dist/chunks/{sync-inspection-XFJOAMJD.ts → sync-inspection-5MY2HI4P.ts} +3 -3
- package/dist/chunks/{sync-operations-W5HFFMTP.ts → sync-operations-GNPS6BLY.ts} +29 -17
- package/dist/chunks/sync-operations-GNPS6BLY.ts.map +7 -0
- package/dist/chunks/{webdav-backend-6K26F6LT.ts → webdav-backend-TGFUH3SF.ts} +4 -4
- package/dist/index.ts +28 -23
- package/dist/index.ts.map +2 -2
- package/docs/agent-continuous-hardening.md +79 -0
- package/docs/agent-mode-verification.md +2 -0
- package/docs/agent-quality-verification.md +41 -0
- package/docs/continuous-sync-verification.md +2 -0
- package/package.json +4 -4
- package/skills/configure-pi-sync/references/configuration.md +21 -5
- package/src/commands/command-execution.ts +7 -2
- package/src/commands/command-handler.ts +3 -1
- package/src/commands/command-types.ts +3 -1
- package/src/sync/agent-plan.ts +26 -9
- package/src/sync/agent-refusal-retry.ts +54 -0
- package/src/sync/agent-request.ts +3 -1
- package/src/sync/agent-runner.ts +8 -6
- package/src/sync/agent-store.ts +32 -1
- package/src/sync/agent-sync.ts +63 -13
- package/src/sync/continuous-lease.ts +2 -7
- package/src/sync/continuous-record.ts +95 -13
- package/src/sync/continuous-storage.ts +12 -3
- package/src/sync/continuous-sync.ts +2 -1
- package/src/sync/merged-sync.ts +37 -9
- package/src/sync/sync-mutations.ts +11 -0
- package/src/ui/cancellable-operation.ts +2 -0
- package/src/ui/manager-state.ts +1 -0
- package/src/ui/manager-ui.ts +59 -14
- package/src/ui/secret-input.ts +29 -211
- package/dist/chunks/agent-plan-K3CRYVXV.ts.map +0 -7
- package/dist/chunks/agent-runner-E2JU2VZ6.ts.map +0 -7
- package/dist/chunks/agent-store-A3F6IYWZ.ts.map +0 -7
- package/dist/chunks/chunk-4TQWFLOQ.ts.map +0 -7
- package/dist/chunks/chunk-QGK445K7.ts.map +0 -7
- package/dist/chunks/chunk-QOC47PBC.ts +0 -97
- package/dist/chunks/chunk-QOC47PBC.ts.map +0 -7
- package/dist/chunks/chunk-T3NC77TU.ts.map +0 -7
- package/dist/chunks/chunk-VJN7KU4J.ts.map +0 -7
- package/dist/chunks/manager-ui-PSA2L6CE.ts.map +0 -7
- package/dist/chunks/sync-operations-W5HFFMTP.ts.map +0 -7
- /package/dist/chunks/{chunk-OWBAZA6J.ts.map → chunk-DT6TOCIG.ts.map} +0 -0
- /package/dist/chunks/{chunk-OEWQVWLC.ts.map → chunk-ORGBI36T.ts.map} +0 -0
- /package/dist/chunks/{chunk-EUMINX7L.ts.map → chunk-P7DD5PWZ.ts.map} +0 -0
- /package/dist/chunks/{continuous-record-LFRVXQBD.ts.map → continuous-record-SQJ47CXN.ts.map} +0 -0
- /package/dist/chunks/{git-backend-KYDZ673X.ts.map → git-backend-NYKSG5X6.ts.map} +0 -0
- /package/dist/chunks/{manager-result-dispatcher-AGBBVDDS.ts.map → manager-result-dispatcher-HOCM2GDA.ts.map} +0 -0
- /package/dist/chunks/{remote-selection-ui-5725JDNC.ts.map → remote-selection-ui-YFPGYGNE.ts.map} +0 -0
- /package/dist/chunks/{s3-backend-Y7WSCLJI.ts.map → s3-backend-F7PR5FB3.ts.map} +0 -0
- /package/dist/chunks/{setup-wizard-SOYOJQKP.ts.map → setup-wizard-OVHZYXNW.ts.map} +0 -0
- /package/dist/chunks/{sync-inspection-XFJOAMJD.ts.map → sync-inspection-5MY2HI4P.ts.map} +0 -0
- /package/dist/chunks/{webdav-backend-6K26F6LT.ts.map → webdav-backend-TGFUH3SF.ts.map} +0 -0
package/dist/index.ts.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/ui/operation-dialogs.ts", "../src/commands/command-execution.ts", "../src/commands/command-handler.ts", "../src/settings/config-errors.ts", "../src/sync/automatic-sync.ts", "../src/sync/startup-check.ts", "../src/sync/sync-loaders.ts", "../src/sync-extension.ts"],
|
|
4
|
-
"sourcesContent": ["import type { ExtensionContext } from \"@earendil-works/pi-coding-agent\";\n\n/** Track History's Pi-owned selector/confirmation lifetime without inspecting renderer internals. */\nexport function trackOperationDialogs<Context extends ExtensionContext>(\n ctx: Context,\n onDialog?: (active: boolean) => void,\n): Context {\n if (!onDialog) return ctx;\n const runDialog = async <Value>(task: () => Promise<Value>): Promise<Value> => {\n onDialog(true);\n try {\n return await task();\n } finally {\n onDialog(false);\n }\n };\n const ui: ExtensionContext[\"ui\"] = {\n ...ctx.ui,\n select: (...args) => runDialog(() => ctx.ui.select(...args)),\n confirm: (...args) => runDialog(() => ctx.ui.confirm(...args)),\n };\n // Forward live context properties: copying the context would hide session\n // replacement from mutation-owner revalidation after a dialog settles.\n return new Proxy(ctx, {\n get(target, key, receiver) {\n return key === \"ui\" ? ui : Reflect.get(target, key, receiver);\n },\n });\n}\n", "import type { ExtensionCommandContext, ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport { loadConfig, sessionTokenWarnings, syncSessionsWarnings } from \"../settings/config.js\";\nimport { activeLocalConfigPath, createLocalConfigDocument, localConfigPath } from \"../settings/config-file.js\";\nimport { localConfigTemplate, readLocalConfigObject } from \"../settings/settings-store.js\";\nimport type { AnySyncConfig } from \"../settings/settings-types.js\";\nimport { unlock, withLock } from \"../state/lock.js\";\nimport { migrateLegacyStateDirectory, stateDirectoryMigrationNotice } from \"../state/state-directory.js\";\nimport { withAgentSyncLock } from \"../sync/agent-sync.js\";\nimport { throwIfAborted } from \"../sync/signals.js\";\nimport { syncErrorGuidance } from \"../sync/sync-error-guidance.js\";\nimport { isSyncDecisionRequiredError, SetupPullRequiresUiError } from \"../sync/sync-errors.js\";\nimport type { SyncLoaders } from \"../sync/sync-loaders.js\";\nimport { RemoteSelectionMismatchError } from \"../sync/sync-policy.js\";\nimport { automaticSyncSummary } from \"../ui/automatic-sync-summary.js\";\nimport type { RunRouteResult } from \"../ui/cancellable-operation.js\";\nimport { trackOperationDialogs } from \"../ui/operation-dialogs.js\";\nimport { startupTransferSummary } from \"../ui/sync-behavior.js\";\nimport { setSyncStatus } from \"../ui/sync-status.js\";\nimport { safeTerminalText } from \"../ui/terminal-text.js\";\nimport { parseOptions, resolveSyncCommand, splitArgs, usage, validateCommandOptions } from \"./command.js\";\nimport type { CommandOptions } from \"./command-types.js\";\n\nexport async function executeRecoveryCommand(\n rawArgs: string,\n ctx: ExtensionContext,\n signal: AbortSignal | undefined,\n loaders: SyncLoaders,\n onCommit?: () => void,\n setup?: string,\n): Promise<RunRouteResult> {\n try {\n const [subcommand, ...rest] = splitArgs(rawArgs);\n if (subcommand !== \"sync\" && subcommand !== \"pull\" && subcommand !== \"push\") {\n throw new Error(`Unsupported sync recovery route: ${subcommand ?? \"missing\"}`);\n }\n const options = parseOptions(rest);\n if (setup !== undefined) options.setup = setup;\n if (signal) options.signal = signal;\n if (onCommit) options.onCommit = onCommit;\n options.reload = false;\n options.auto = false;\n validateCommandOptions(subcommand, options);\n const operations = await loaders.operations();\n throwIfAborted(options.signal);\n if (subcommand === \"push\") {\n const outcome = await withLock(\"push\", () => operations.push(ctx, options));\n return { kind: \"completed\", ...(outcome ? { outcome } : {}) };\n }\n if (subcommand === \"pull\") {\n const outcome = await withLock(\"pull\", () => operations.pull(ctx, options));\n return { kind: \"completed\", ...(outcome ? { outcome } : {}) };\n }\n await withAgentSyncLock(ctx, options, (current) => operations.syncBoth(ctx, current));\n return { kind: \"completed\" };\n } catch (error) {\n if (signal?.aborted) return { kind: \"failed\" };\n setSyncStatus(ctx, undefined);\n if (error instanceof RemoteSelectionMismatchError) {\n return { kind: \"remote-selection-required\", decision: error.decision };\n }\n if (isSyncDecisionRequiredError(error)) {\n return { kind: \"decision-required\", decision: error.decision };\n }\n ctx.ui.notify(syncErrorGuidance(error), \"error\");\n return { kind: \"failed\" };\n }\n}\n\nexport async function executeCommand(\n rawArgs: string,\n ctx: ExtensionCommandContext,\n signal: AbortSignal | undefined,\n loaders: SyncLoaders,\n onCommit?: () => void,\n setup?: string,\n onDialog?: (active: boolean) => void,\n): Promise<RunRouteResult> {\n ctx = trackOperationDialogs(ctx, onDialog);\n try {\n const command = await resolveSyncCommand(rawArgs, ctx);\n if (signal?.aborted || !command) return { kind: \"completed\" };\n const { subcommand, rest } = command;\n const options = parseOptions(rest);\n if (setup !== undefined) options.setup = setup;\n if (signal) options.signal = signal;\n if (onCommit) options.onCommit = onCommit;\n validateCommandOptions(subcommand, options);\n\n switch (subcommand) {\n case \"help\":\n ctx.ui.notify(usage(), \"info\");\n return { kind: \"completed\" };\n case \"use\": {\n const { useSyncSetup } = await loaders.setupSwitch();\n throwIfAborted(options.signal);\n await useSyncSetup(\n ctx,\n options.args[0] ?? \"\",\n async (selectedSetup) => {\n const operations = await loaders.operations();\n throwIfAborted(options.signal);\n return withLock(\"pull\", () => operations.pull(ctx, { ...options, setup: selectedSetup }));\n },\n undefined,\n options.signal,\n );\n return { kind: \"completed\" };\n }\n case \"init\":\n await initConfig(ctx, signal);\n return { kind: \"completed\" };\n case \"config\":\n await showConfig(ctx, options);\n return { kind: \"completed\" };\n case \"files\": {\n const { showFileSelection } = await import(\"../ui/file-selection.js\");\n throwIfAborted(options.signal);\n await showFileSelection(ctx, options.setup, options.signal);\n return { kind: \"completed\" };\n }\n case \"status\": {\n const operations = await loaders.operations();\n throwIfAborted(options.signal);\n await operations.status(ctx, options);\n return { kind: \"completed\" };\n }\n case \"diff\": {\n const operations = await loaders.operations();\n throwIfAborted(options.signal);\n await operations.diff(ctx, options);\n return { kind: \"completed\" };\n }\n case \"conflicts\": {\n const { showConflicts } = await import(\"../sync/conflict-review.js\");\n throwIfAborted(options.signal);\n await withLock(\"sync\", () => showConflicts(ctx, options));\n return { kind: \"completed\" };\n }\n case \"doctor\": {\n const operations = await loaders.operations();\n throwIfAborted(options.signal);\n await operations.doctor(ctx, options);\n return { kind: \"completed\" };\n }\n case \"push\": {\n const operations = await loaders.operations();\n throwIfAborted(options.signal);\n const outcome = await withLock(\"push\", () => operations.push(ctx, options));\n return { kind: \"completed\", ...(outcome ? { outcome } : {}) };\n }\n case \"pull\": {\n const operations = await loaders.operations();\n throwIfAborted(options.signal);\n const outcome = await withLock(\"pull\", () => operations.pull(ctx, options));\n return { kind: \"completed\", ...(outcome ? { outcome } : {}) };\n }\n case \"sync\": {\n const operations = await loaders.operations();\n throwIfAborted(options.signal);\n await withAgentSyncLock(ctx, options, (current) => operations.syncBoth(ctx, current));\n return { kind: \"completed\" };\n }\n case \"history\": {\n const operations = await loaders.operations();\n throwIfAborted(options.signal);\n await operations.history(ctx, options);\n return { kind: \"completed\" };\n }\n case \"rollback\": {\n const operations = await loaders.operations();\n throwIfAborted(options.signal);\n await withLock(\"rollback\", () => operations.rollback(ctx, options));\n return { kind: \"completed\" };\n }\n case \"migrate-state\":\n await migrateStateDirectory(ctx, options);\n return { kind: \"completed\" };\n case \"unlock\":\n await unlock(ctx, options);\n return { kind: \"completed\" };\n default:\n ctx.ui.notify(`Unknown /sync command: ${subcommand}\\n\\n${usage()}`, \"warning\");\n return { kind: \"failed\" };\n }\n } catch (error) {\n if (signal?.aborted) return { kind: \"failed\" };\n setSyncStatus(ctx, undefined);\n if (error instanceof SetupPullRequiresUiError) throw error;\n if (error instanceof RemoteSelectionMismatchError) {\n return { kind: \"remote-selection-required\", decision: error.decision };\n }\n if (isSyncDecisionRequiredError(error)) {\n return { kind: \"decision-required\", decision: error.decision };\n }\n ctx.ui.notify(syncErrorGuidance(error), \"error\");\n return { kind: \"failed\" };\n }\n}\n\nasync function migrateStateDirectory(ctx: ExtensionCommandContext, options: CommandOptions) {\n const notice = stateDirectoryMigrationNotice();\n if (!notice) {\n ctx.ui.notify(\"pi-sync already uses the canonical pi-sync/ state directory.\", \"info\");\n return;\n }\n if (\n !options.yes &&\n !(await ctx.ui.confirm(\n \"Migrate pi-sync state directory\",\n \"Confirm that every other Pi process is closed. pi-sync will atomically rename .pisync/ to pi-sync/ without merging or deleting either root.\",\n { signal: options.signal },\n ))\n ) {\n ctx.ui.notify(\"pi-sync state migration cancelled.\", \"info\");\n return;\n }\n throwIfAborted(options.signal);\n const result = await migrateLegacyStateDirectory();\n throwIfAborted(options.signal);\n if (result.status === \"ready\") {\n ctx.ui.notify(\"pi-sync already uses the canonical pi-sync/ state directory.\", \"info\");\n return;\n }\n ctx.ui.notify(result.message, result.status === \"migrated\" ? \"info\" : \"warning\");\n}\n\nasync function initConfig(ctx: ExtensionCommandContext, signal?: AbortSignal) {\n const configPath = localConfigPath();\n if (await readLocalConfigObject()) {\n ctx.ui.notify(`Config already exists: ${await activeLocalConfigPath()}`, \"info\");\n return;\n }\n\n if (ctx.mode === \"tui\") {\n const { showSetupWizard } = await import(\"../ui/setup/setup-wizard.js\");\n throwIfAborted(signal);\n await showSetupWizard(ctx, signal);\n return;\n }\n await createLocalConfigDocument(localConfigTemplate());\n ctx.ui.notify(`Created ${configPath}. Add a storage connection and sync setup before syncing.`, \"info\");\n}\n\nasync function showConfig(ctx: ExtensionCommandContext, options: CommandOptions) {\n const config = await loadConfig(options.setup);\n const warnings = [\n ...(config.backend.type === \"s3\" ? sessionTokenWarnings(config.backend.profile) : []),\n ...syncSessionsWarnings(config),\n ];\n const storageLines = configStorageLines(config);\n ctx.ui.notify(\n [\n \"pi-sync config:\",\n `sync setup: ${config.setupName}`,\n `storage connection: ${config.connectionName}`,\n ...storageLines,\n `storage path: ${config.storagePath}`,\n `automatic sync: ${automaticSyncSummary(config.automatic)}`,\n `settings field merge: ${config.mergeSettings ? \"On (experimental)\" : \"Off\"}`,\n `machine-local settings.json fields: ${(config.localFields ?? []).map(safeTerminalText).join(\", \") || \"none\"}`,\n `startup transfer: ${startupTransferSummary(config)}`,\n `agent mode: ${config.agentMode ? \"On (experimental)\" : \"Off\"}`,\n `continuous sync: ${config.continuous ? (config.agentMode ? \"On (experimental)\" : \"paused; Agent mode is Off\") : \"Off\"}`,\n `included content: ${config.include.join(\", \") || \"none\"}`,\n `sessions: ${config.include.includes(\"sessions\") ? \"included\" : \"not included\"}`,\n `settings file: ${localConfigPath()}`,\n ...warnings,\n ].join(\"\\n\"),\n warnings.length > 0 ? \"warning\" : \"info\",\n );\n}\n\nfunction configStorageLines(config: AnySyncConfig) {\n switch (config.backend.type) {\n case \"git\":\n return [\n \"kind: git\",\n `remote: ${displayGitRemote(config.backend.profile.remote)}`,\n \"authentication: existing Git/SSH credentials (not stored)\",\n `branch: ${config.backend.destination.branch}`,\n ];\n case \"webdav\":\n return [\n \"kind: webdav\",\n `url: ${displayWebDavUrl(config.backend.profile.url, config.backend.profile.username)}`,\n \"username: configured (value hidden)\",\n \"password: configured\",\n ];\n case \"s3\":\n return [\n \"kind: s3\",\n `endpoint: ${config.backend.profile.endpoint}`,\n `bucket: ${config.backend.destination.bucket}`,\n `region: ${config.backend.profile.region}`,\n \"access key id: configured\",\n \"secret access key: configured\",\n `session token: ${config.backend.profile.sessionToken ? \"configured\" : \"not configured\"}`,\n ];\n }\n}\n\nfunction displayGitRemote(value: string | undefined) {\n if (!value) return \"missing\";\n try {\n const url = new URL(value);\n url.username = \"\";\n url.password = \"\";\n url.search = \"\";\n url.hash = \"\";\n return url.toString();\n } catch {\n return value.replace(/^(?:[^@\\s]+@)?(?<host>[^:]+):.+$/u, \"$<host>:\u2026\");\n }\n}\n\nfunction displayWebDavUrl(value: string | undefined, username: string | undefined) {\n if (!value) return \"missing\";\n try {\n const url = new URL(value);\n url.username = \"\";\n url.password = \"\";\n url.search = \"\";\n url.hash = \"\";\n return username ? `${url.origin}/\u2026` : `${url.origin}${url.pathname}`;\n } catch {\n return \"invalid (value hidden)\";\n }\n}\n", "import type { ExtensionCommandContext, ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport { loadConfig } from \"../settings/config.js\";\nimport { readStateForConfig, syncStateFingerprint } from \"../state/sync-state-store.js\";\nimport { combineSignals } from \"../sync/signals.js\";\nimport { errorMessage } from \"../sync/sync-errors.js\";\nimport type { SyncLoaders } from \"../sync/sync-loaders.js\";\nimport { formatRemoteSelectionMismatch } from \"../sync/sync-policy.js\";\nimport type { RunRouteResult } from \"../ui/cancellable-operation.js\";\nimport {\n observationMatchesConfig,\n type SyncAttentionController,\n type SyncAttentionOrigin,\n syncAttentionMatchesConfig,\n} from \"../ui/sync-attention.js\";\nimport { setSyncStatus } from \"../ui/sync-status.js\";\nimport { parseOptions, splitArgs, validateCommandOptions } from \"./command.js\";\nimport { executeCommand, executeRecoveryCommand } from \"./command-execution.js\";\n\nexport async function handleCommand(\n rawArgs: string,\n ctx: ExtensionCommandContext,\n sessionSignal: AbortSignal,\n loaders: SyncLoaders,\n attention: SyncAttentionController,\n onExplicitSync?: (setup?: string) => void,\n) {\n await reconcileObservation(attention, sessionSignal);\n if (sessionSignal.aborted) return;\n const run = (\n route: string,\n signal?: AbortSignal,\n onCommit?: () => void,\n target?: string,\n onDialog?: (active: boolean) => void,\n ) => {\n const [command, ...args] = splitArgs(route);\n if (command === \"sync\") {\n try {\n const options = parseOptions(args);\n validateCommandOptions(\"sync\", options);\n onExplicitSync?.(target ?? options.setup);\n } catch {\n /* Invalid routes do not request an automatic retry. */\n }\n }\n return executeCommand(\n route,\n ctx,\n combineSignals(sessionSignal, signal),\n loaders,\n observationCommitCallback(attention, sessionSignal, onCommit),\n target,\n onDialog,\n );\n };\n if (!rawArgs.trim()) {\n try {\n const { showSyncManager } = await import(\"../ui/manager-ui.js\");\n if (sessionSignal.aborted) return;\n await showSyncManager(ctx, run, sessionSignal, {\n getAttention: () => attention.current(),\n getObservation: () => attention.observation(),\n onObservationInvalidated: () => attention.clearObservation(),\n onSelectionResolved: (expected) => {\n if (attention.current() === expected) attention.clear(ctx);\n },\n });\n } catch (error) {\n if (sessionSignal.aborted) return;\n setSyncStatus(ctx, undefined);\n ctx.ui.notify(errorMessage(error), \"error\");\n }\n await reconcileObservation(attention, sessionSignal);\n if (!sessionSignal.aborted) await attention.publish(ctx, sessionSignal);\n return;\n }\n const result = await run(rawArgs);\n if (result.kind === \"decision-required\") {\n ctx.ui.notify(result.decision.directMessage, \"error\");\n } else if (result.kind === \"remote-selection-required\") {\n const origin = directSelectionOrigin(rawArgs);\n if (origin) attention.set(result.decision, origin);\n const deterministic = splitArgs(rawArgs).some((arg) => arg === \"--yes\" || arg === \"-y\");\n if (origin && ctx.mode === \"tui\" && !deterministic) {\n await resolveSelectionAttention(ctx, attention, sessionSignal, loaders);\n } else {\n ctx.ui.notify(\n formatRemoteSelectionMismatch(\n result.decision.setupName,\n result.decision.localInclude,\n result.decision.remoteInclude,\n ),\n \"error\",\n );\n }\n }\n await clearAttentionAfterCompletedOperation(rawArgs, result, ctx, attention, sessionSignal);\n await reconcileSelectionAttention(ctx, attention, sessionSignal);\n await reconcileObservation(attention, sessionSignal);\n if (!sessionSignal.aborted) await attention.publish(ctx, sessionSignal);\n}\n\nfunction observationCommitCallback(\n attention: SyncAttentionController,\n sessionSignal: AbortSignal,\n onCommit?: () => void,\n) {\n const observed = attention.observation();\n return () => {\n // Opening or cancelling a review changes nothing. A commit may change data\n // even if later publication/baseline cleanup fails; never restore old hints.\n if (!sessionSignal.aborted && attention.observation() === observed) attention.clearObservation();\n onCommit?.();\n };\n}\n\nasync function reconcileObservation(attention: SyncAttentionController, signal: AbortSignal) {\n const observed = attention.observation();\n if (!observed || signal.aborted) return;\n try {\n const config = await loadConfig();\n if (signal.aborted || attention.observation() !== observed) return;\n if (!observationMatchesConfig(observed, config)) {\n attention.clearObservation();\n return;\n }\n const state = await readStateForConfig(config);\n if (signal.aborted || attention.observation() !== observed) return;\n if (syncStateFingerprint(state) !== observed.inspection.stateIdentity) attention.clearObservation();\n } catch {\n if (!signal.aborted && attention.observation() === observed) attention.clearObservation();\n }\n}\n\nasync function clearAttentionAfterCompletedOperation(\n rawArgs: string,\n result: RunRouteResult,\n ctx: ExtensionContext,\n attention: SyncAttentionController,\n signal: AbortSignal,\n) {\n if (result.kind !== \"completed\" || result.outcome === \"cancelled\" || signal.aborted) return;\n const [command, ...rest] = splitArgs(rawArgs);\n if (command !== \"sync\" && command !== \"pull\" && command !== \"push\") return;\n const current = attention.current();\n if (!current) return;\n try {\n const options = parseOptions(rest);\n const setupName = options.setup ?? (await loadConfig()).setupName;\n if (signal.aborted || attention.current() !== current) return;\n if (current.decision.setupName === setupName) attention.clear(ctx);\n } catch {\n // Attention reconciliation below owns malformed or concurrently changed settings.\n }\n}\n\nasync function reconcileSelectionAttention(\n ctx: ExtensionContext,\n attention: SyncAttentionController,\n signal: AbortSignal,\n) {\n const current = attention.current();\n if (!current || signal.aborted) return;\n try {\n const config = await loadConfig(current.decision.setupName);\n if (signal.aborted || attention.current() !== current) return;\n if (!syncAttentionMatchesConfig(current, config)) attention.clear(ctx);\n } catch {\n if (!signal.aborted && attention.current() === current) attention.clear(ctx);\n }\n}\n\nfunction directSelectionOrigin(rawArgs: string): SyncAttentionOrigin | undefined {\n const command = splitArgs(rawArgs)[0];\n return command === \"sync\" || command === \"pull\" || command === \"push\" ? command : undefined;\n}\n\nexport async function resolveSelectionAttention(\n ctx: ExtensionContext,\n attention: SyncAttentionController,\n signal: AbortSignal,\n loaders: SyncLoaders,\n options: {\n cancelLabel?: string;\n withStateAccess?: <T>(task: () => Promise<T>) => Promise<T>;\n } = {},\n) {\n const current = attention.current();\n if (!current || signal.aborted) return;\n const { dispatchManagerResult } = await import(\"../ui/manager-result-dispatcher.js\");\n if (signal.aborted || attention.current() !== current) return;\n await dispatchManagerResult(\n ctx,\n { kind: \"remote-selection-required\", decision: current.decision },\n current.origin,\n (route, actionSignal, onCommit, target) => {\n const execute = () =>\n executeRecoveryCommand(\n route,\n ctx,\n combineSignals(signal, actionSignal),\n loaders,\n observationCommitCallback(attention, signal, onCommit),\n target,\n );\n return options.withStateAccess ? options.withStateAccess(execute) : execute();\n },\n signal,\n {\n cancelLabel: options.cancelLabel,\n withStateAccess: options.withStateAccess,\n onSelectionResolved: () => {\n if (attention.current() === current) attention.clear(ctx);\n },\n },\n );\n}\n", "export function isMissingConfigError(error: unknown) {\n return (\n error instanceof Error &&\n (error.message.startsWith(\"Missing pi-sync settings.\") || error.message === \"No sync setups are configured.\")\n );\n}\n", "import type { ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport { setSyncSetupCompletions } from \"../commands/command.js\";\nimport type { CommandOptions } from \"../commands/command-types.js\";\nimport { loadConfig, loadPartialConfig } from \"../settings/config.js\";\nimport { isMissingConfigError } from \"../settings/config-errors.js\";\nimport { consumeLocalConfigMigrationNotice } from \"../settings/config-file.js\";\nimport { readLocalConfigObject } from \"../settings/settings-store.js\";\nimport { sessionDirFromContext, snapshotOptionsForContext } from \"../snapshot/session-paths.js\";\nimport { recoverSnapshotTransactionsOnStartup } from \"../snapshot/snapshot-transaction.js\";\nimport { withLock } from \"../state/lock.js\";\nimport { stateDirectoryMigrationNotice } from \"../state/state-directory.js\";\nimport { ensureStateDir, readStateForConfig } from \"../state/sync-state-store.js\";\nimport { configureSyncStatus, setSyncStatus } from \"../ui/sync-status.js\";\nimport { safeTerminalText } from \"../ui/terminal-text.js\";\nimport { startupTransferEnabled } from \"./agent-policy.js\";\nimport { throwIfAborted } from \"./signals.js\";\nimport { createStartupTimings } from \"./startup-timings.js\";\nimport { errorMessage } from \"./sync-errors.js\";\nimport type { SyncLoaders } from \"./sync-loaders.js\";\nimport { captureMutationOwner } from \"./sync-local.js\";\n\nconst AUTO_SYNC_OPTIONS: CommandOptions = {\n yes: true,\n force: false,\n stale: false,\n silent: true,\n reload: false,\n auto: true,\n args: [],\n};\n\nexport async function startSession(ctx: ExtensionContext, signal: AbortSignal) {\n const timings = createStartupTimings();\n let debug = false;\n let outcome: \"completed\" | \"stopped\" = \"stopped\";\n try {\n throwIfAborted(signal);\n const stateNotice = stateDirectoryMigrationNotice();\n if (stateNotice && ctx.hasUI) ctx.ui.notify(stateNotice, \"warning\");\n // Recovery can restore managed files: finish it before Pi accepts user edits.\n // Unlike remote inspection, it must never be detached behind startup.\n const validateMutation = captureMutationOwner(ctx, signal);\n const currentFile = ctx.sessionManager.getSessionFile?.();\n await timings.measure(\"transaction recovery\", () =>\n recoverSnapshotTransactionsOnStartup({\n signal,\n sessionDir: sessionDirFromContext(ctx),\n protectedTargets: currentFile ? [currentFile] : [],\n validateMutation,\n }),\n );\n throwIfAborted(signal);\n try {\n const settings = await timings.measure(\"settings read\", () => readLocalConfigObject());\n throwIfAborted(signal);\n debug = settings?.debug ?? false;\n const names = settings ? Object.keys(settings.syncSetups).sort((left, right) => left.localeCompare(right)) : [];\n setSyncSetupCompletions(names);\n configureSyncStatus(ctx, settings?.showStatus ?? true);\n } catch {\n if (signal.aborted) return;\n setSyncSetupCompletions([]);\n }\n const migrationNotice = consumeLocalConfigMigrationNotice();\n if (migrationNotice && ctx.hasUI) ctx.ui.notify(migrationNotice, \"warning\");\n throwIfAborted(signal);\n if (!ctx.hasUI) return;\n try {\n const config = await timings.measure(\"config resolution\", () => loadConfig());\n throwIfAborted(signal);\n configureSyncStatus(ctx, config.showStatus);\n outcome = \"completed\";\n return config.automatic || startupTransferEnabled(config) ? config : undefined;\n } catch (error) {\n throwIfAborted(signal);\n if (!isMissingConfigError(error)) {\n ctx.ui.notify(`pi-sync startup check skipped: ${safeTerminalText(errorMessage(error))}`, \"warning\");\n }\n }\n } finally {\n timings.publish(ctx, debug, signal, \"local initialization\", outcome);\n }\n}\n\nexport async function autoPushSessions(ctx: ExtensionContext, signal: AbortSignal, loaders: SyncLoaders) {\n try {\n const partial = await loadPartialConfig();\n throwIfAborted(signal);\n if (!partial.automatic) return;\n if (!partial.include.includes(\"sessions\")) return;\n await ensureStateDir();\n throwIfAborted(signal);\n const config = await loadConfig();\n throwIfAborted(signal);\n if (!config.include.includes(\"sessions\")) return;\n const [operations, snapshotModule, syncStateModule] = await Promise.all([\n loaders.operations(),\n loaders.snapshot(),\n loaders.syncState(),\n ]);\n throwIfAborted(signal);\n await withLock(\"auto-session-push\", async () => {\n throwIfAborted(signal);\n const state = await readStateForConfig(config);\n throwIfAborted(signal);\n const local = await snapshotModule.createSnapshot(config.snapshotIdentity, {\n ...snapshotOptionsForContext(ctx, config),\n signal,\n });\n throwIfAborted(signal);\n if (!syncStateModule.hasLocalChanges(local, state, config)) return;\n await operations.push(ctx, { ...AUTO_SYNC_OPTIONS, signal }, { config, state, local });\n });\n } catch (error) {\n if (signal.aborted || isMissingConfigError(error)) return;\n setSyncStatus(ctx, undefined);\n ctx.ui.notify(`pi-sync session push skipped: ${errorMessage(error)}`, \"warning\");\n }\n}\n", "import type { ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport { loadConfigForCheck, syncCheckConfigFingerprint } from \"../settings/config.js\";\nimport { isMissingConfigError } from \"../settings/config-errors.js\";\nimport type { AnySyncConfig } from \"../settings/settings-types.js\";\nimport { snapshotOptionsForContext } from \"../snapshot/session-paths.js\";\nimport { withLock } from \"../state/lock.js\";\nimport { withStateDirectoryAccess } from \"../state/state-directory.js\";\nimport { readStateForConfig, syncStateFingerprint } from \"../state/sync-state-store.js\";\nimport type { SyncAttentionController } from \"../ui/sync-attention.js\";\nimport { setSyncStatus } from \"../ui/sync-status.js\";\nimport { safeTerminalText } from \"../ui/terminal-text.js\";\nimport { startupTransferEnabled } from \"./agent-policy.js\";\nimport { withAgentSyncLock } from \"./agent-sync.js\";\nimport { combineSignals, throwIfAborted } from \"./signals.js\";\nimport { createStartupTimings } from \"./startup-timings.js\";\nimport { errorMessage } from \"./sync-errors.js\";\nimport type { SyncLoaders } from \"./sync-loaders.js\";\n\n/** One owned task per extension session, never keyed by the shared headless UI. */\nexport function createStartupCheck(loaders: SyncLoaders, attention: SyncAttentionController, timeoutMs = 30_000) {\n let active:\n | {\n controller: AbortController;\n promise: Promise<void>;\n owner: ExtensionContext[\"sessionManager\"];\n transfer: boolean;\n }\n | undefined;\n\n let pending: { ctx: ExtensionContext; signal: AbortSignal; config: AnySyncConfig } | undefined;\n\n const controllerApi = {\n async interrupt(ctx: ExtensionContext) {\n const task = active;\n if (!task?.transfer || task.owner !== ctx.sessionManager) return;\n task.controller.abort(new DOMException(\"Agent became busy\", \"AbortError\"));\n await task.promise;\n },\n settled(ctx: ExtensionContext) {\n const queued = pending;\n if (!queued || queued.ctx.sessionManager !== ctx.sessionManager || queued.signal.aborted || !ctx.isIdle()) return;\n pending = undefined;\n controllerApi.start(ctx, queued.signal, queued.config);\n },\n start(ctx: ExtensionContext, sessionSignal: AbortSignal, initialConfig?: AnySyncConfig) {\n if (!ctx.hasUI || sessionSignal.aborted) return;\n if (initialConfig && startupTransferEnabled(initialConfig) && !ctx.isIdle()) {\n pending = { ctx, signal: sessionSignal, config: initialConfig };\n return;\n }\n if (active) throw new Error(\"Previous startup check has not been drained.\");\n const timings = createStartupTimings();\n const controller = new AbortController();\n const signal = combineSignals(sessionSignal, controller.signal);\n const task = {\n controller,\n owner: ctx.sessionManager,\n promise: Promise.resolve(),\n transfer: Boolean(initialConfig && startupTransferEnabled(initialConfig)),\n };\n active = task;\n const isCurrent = () => !sessionSignal.aborted && active === task && task.owner === ctx.sessionManager;\n const timer = setTimeout(\n () => controller.abort(new DOMException(\"Startup check timed out\", \"TimeoutError\")),\n timeoutMs,\n );\n let config: AnySyncConfig | undefined;\n let checking = false;\n let stopped = false;\n // Handle every detached rejection here; Pi's awaited event runner cannot catch it.\n task.promise = Promise.resolve()\n .then(async () => {\n try {\n throwIfAborted(signal);\n config = initialConfig ?? (await loadConfigForCheck());\n task.transfer = startupTransferEnabled(config);\n throwIfAborted(signal);\n if (!config.automatic && !startupTransferEnabled(config)) return;\n const captured = config;\n const identity = syncCheckConfigFingerprint(captured);\n checking = true;\n setSyncStatus(ctx, \"sync ...\");\n const { inspectSync } = await timings.measure(\"inspection import\", () => loaders.inspection());\n throwIfAborted(signal);\n const currentConfig = await loadConfigForCheck();\n throwIfAborted(signal);\n if (syncCheckConfigFingerprint(currentConfig) !== identity) return;\n // Lock order: state migration guard \u2192 sync operation \u2192 backend cache.\n // Read heads may write only private cache data. Never call doctor/syncBoth.\n const inspection = await timings.measure(\"inspection and guards\", () =>\n withStateDirectoryAccess(() => {\n throwIfAborted(signal);\n return withLock(\"startup-check\", () => {\n throwIfAborted(signal);\n return inspectSync(captured, snapshotOptionsForContext(ctx, captured), signal, undefined, timings);\n });\n }),\n );\n throwIfAborted(signal);\n const latest = await loadConfigForCheck();\n throwIfAborted(signal);\n if (syncCheckConfigFingerprint(latest) !== identity) return;\n const state = await withStateDirectoryAccess(() => readStateForConfig(latest));\n throwIfAborted(signal);\n if (syncStateFingerprint(state) !== inspection.stateIdentity || !isCurrent()) return;\n attention.observe({\n setupName: captured.setupName,\n configIdentity: identity,\n checkedAt: new Date().toISOString(),\n inspection,\n automaticTransfer: startupTransferEnabled(captured),\n });\n if (\n startupTransferEnabled(captured) &&\n !inspection.firstSync &&\n inspection.head &&\n inspection.selectionState?.kind === \"same\"\n ) {\n const operations = await timings.measure(\"operations import\", () => loaders.operations());\n throwIfAborted(signal);\n if (!isCurrent()) return;\n if (!ctx.isIdle()) {\n pending = { ctx, signal: sessionSignal, config: captured };\n return;\n }\n await timings.measure(\"automatic transfer\", () =>\n withStateDirectoryAccess(() =>\n withAgentSyncLock(\n ctx,\n {\n args: [],\n yes: true,\n force: false,\n stale: false,\n silent: true,\n reload: false,\n auto: true,\n signal,\n startupTimings: timings,\n onCommit: () => attention.clearObservation(),\n },\n (options) => operations.syncBoth(ctx, options),\n ),\n ),\n );\n throwIfAborted(signal);\n if (!isCurrent()) return;\n attention.clearObservation();\n return;\n }\n attention.observe({\n setupName: captured.setupName,\n configIdentity: identity,\n checkedAt: new Date().toISOString(),\n inspection,\n automaticTransfer: startupTransferEnabled(captured),\n });\n if (ctx.mode === \"rpc\") attention.notifyObservation(ctx);\n } catch (error) {\n stopped = true;\n if (!isCurrent() || sessionSignal.aborted || isMissingConfigError(error)) return;\n if (signal.aborted && controller.signal.reason?.name !== \"TimeoutError\") return;\n // A settings edit invalidates failures as well as successful observations.\n if (config) {\n const latest = await loadConfigForCheck().catch(() => undefined);\n if (!isCurrent() || (signal.aborted && controller.signal.reason?.name !== \"TimeoutError\")) return;\n if (!latest || syncCheckConfigFingerprint(latest) !== syncCheckConfigFingerprint(config)) return;\n }\n ctx.ui.notify(\n config && startupTransferEnabled(config)\n ? `pi-sync automatic transfer stopped: ${safeTerminalText(errorMessage(error))}. Run /sync to review or reconcile retained recovery evidence. No resources were reloaded.`\n : `pi-sync startup check skipped: ${safeTerminalText(errorMessage(error))}. Run /sync status to retry. No startup transfer was performed.`,\n \"warning\",\n );\n } finally {\n clearTimeout(timer);\n if (isCurrent() && checking) {\n if (!signal.aborted || controller.signal.reason?.name === \"TimeoutError\") {\n const latest = await loadConfigForCheck().catch(() => undefined);\n if (isCurrent()) {\n if (signal.aborted && controller.signal.reason?.name !== \"TimeoutError\")\n setSyncStatus(ctx, undefined);\n else if (\n config &&\n latest &&\n syncCheckConfigFingerprint(latest) === syncCheckConfigFingerprint(config)\n )\n await attention.publish(ctx, sessionSignal);\n else attention.reset(ctx);\n }\n } else setSyncStatus(ctx, undefined);\n }\n if (isCurrent()) {\n timings.publish(\n ctx,\n config?.debug ?? false,\n sessionSignal,\n \"background startup\",\n signal.aborted || stopped ? \"stopped\" : \"completed\",\n );\n }\n if (active === task) active = undefined;\n }\n })\n .catch(() => {\n // UI teardown can itself throw. No unhandled rejection or retained timer.\n clearTimeout(timer);\n if (active === task) active = undefined;\n });\n },\n async stop() {\n pending = undefined;\n const task = active;\n if (!task) return;\n task.controller.abort(new DOMException(\"Startup check cancelled\", \"AbortError\"));\n // Drain the actual work, including child/ref cleanup, before foreground guards.\n await task.promise;\n },\n };\n return controllerApi;\n}\n", "type SetupSwitchModule = Pick<typeof import(\"./setup-switch.js\"), \"useSyncSetup\">;\ntype SnapshotModule = Pick<typeof import(\"../snapshot/snapshot.js\"), \"createSnapshot\">;\ntype SyncStateModule = Pick<typeof import(\"./sync-state.js\"), \"hasLocalChanges\">;\ntype SyncOperations = typeof import(\"./sync-operations.js\");\n\ntype SyncInspectionModule = Pick<typeof import(\"./sync-inspection.js\"), \"inspectSync\">;\n\nexport interface SyncDependencies {\n loadSyncInspection(): Promise<SyncInspectionModule>;\n loadSetupSwitch(): Promise<SetupSwitchModule>;\n loadSnapshot(): Promise<SnapshotModule>;\n loadSyncState(): Promise<SyncStateModule>;\n loadSyncOperations(): Promise<SyncOperations>;\n}\n\nexport interface SyncLoaders {\n inspection(): Promise<SyncInspectionModule>;\n setupSwitch(): Promise<SetupSwitchModule>;\n snapshot(): Promise<SnapshotModule>;\n syncState(): Promise<SyncStateModule>;\n operations(): Promise<SyncOperations>;\n}\n\nexport function createSyncLoaders(dependencies: Partial<SyncDependencies>): SyncLoaders {\n const loaders: SyncLoaders = {\n inspection: cachedModuleLoader(dependencies.loadSyncInspection ?? (() => import(\"./sync-inspection.js\"))),\n setupSwitch: cachedModuleLoader(dependencies.loadSetupSwitch ?? (() => import(\"./setup-switch.js\"))),\n snapshot: cachedModuleLoader(dependencies.loadSnapshot ?? (() => import(\"../snapshot/snapshot.js\"))),\n syncState: cachedModuleLoader(dependencies.loadSyncState ?? (() => import(\"./sync-state.js\"))),\n operations: cachedModuleLoader(dependencies.loadSyncOperations ?? (() => import(\"./sync-operations.js\"))),\n };\n return loaders;\n}\n\nfunction cachedModuleLoader<Module>(load: () => Promise<Module>): () => Promise<Module> {\n let pending: Promise<Module> | undefined;\n return () => {\n if (!pending) {\n pending = load().catch((error) => {\n pending = undefined;\n throw error;\n });\n }\n return pending;\n };\n}\n", "import type { ExtensionAPI, ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport { completeSyncArguments, splitArgs } from \"./commands/command.js\";\nimport { handleCommand } from \"./commands/command-handler.js\";\nimport type { AnySyncConfig } from \"./settings/settings-types.js\";\nimport { withStateDirectoryAccess } from \"./state/state-directory.js\";\nimport { autoPushSessions, startSession } from \"./sync/automatic-sync.js\";\nimport { combineSignals } from \"./sync/signals.js\";\nimport { createStartupCheck } from \"./sync/startup-check.js\";\nimport { errorMessage } from \"./sync/sync-errors.js\";\nimport { createSyncLoaders, type SyncDependencies } from \"./sync/sync-loaders.js\";\nimport { createSyncAttentionController } from \"./ui/sync-attention.js\";\nimport { setSyncStatus } from \"./ui/sync-status.js\";\nimport { safeTerminalText } from \"./ui/terminal-text.js\";\n\nexport default function sync(pi: ExtensionAPI, dependencies: Partial<SyncDependencies> = {}) {\n const loaders = createSyncLoaders(dependencies);\n const attention = createSyncAttentionController();\n const check = createStartupCheck(loaders, attention);\n let sessionAbort = new AbortController();\n let shutdownAbort: AbortController | undefined;\n let initialization = Promise.resolve<AnySyncConfig | false | undefined>(undefined);\n let continuous: ReturnType<typeof import(\"./sync/continuous-sync.js\")[\"createContinuousSync\"]> | undefined;\n let owner: ExtensionContext[\"sessionManager\"] | undefined;\n let continuousPossible = false;\n const foreground = new Map<ExtensionContext[\"sessionManager\"], number>();\n async function resumeContinuous(ctx: ExtensionContext, signal: AbortSignal, retry?: { setup?: string }) {\n const isCurrent = () => !signal.aborted && !foreground.has(ctx.sessionManager) && owner === ctx.sessionManager;\n if (!isCurrent() || !ctx.hasUI) return;\n try {\n const { loadConfigForCheck } = await import(\"./settings/config.js\");\n if (!isCurrent()) return;\n const config = await loadConfigForCheck();\n if (!isCurrent()) return;\n continuousPossible = Boolean(config.continuous && config.agentMode);\n if (!continuousPossible) {\n await continuous?.stop(ctx.sessionManager);\n return;\n }\n const { createContinuousSync } = await import(\"./sync/continuous-sync.js\");\n if (!isCurrent()) return;\n continuous ??= createContinuousSync(loaders);\n continuous.start(ctx, signal, Boolean(retry && (retry.setup === undefined || retry.setup === config.setupName)));\n } catch {\n /* Existing initialization/command paths report settings errors. */\n }\n }\n\n pi.registerCommand(\"sync\", {\n description: \"Sync Pi settings through Git, WebDAV, R2, or S3-compatible storage\",\n getArgumentCompletions: completeSyncArguments,\n handler: async (args, ctx) => {\n if (!ctx.hasUI) {\n throw new Error(\"/sync requires TUI or RPC mode so results and safety prompts are observable.\");\n }\n const signal = sessionAbort.signal;\n const manager = ctx.sessionManager;\n const command = splitArgs(args)[0];\n let retry: { setup?: string } | undefined;\n let mayResume = false;\n foreground.set(manager, (foreground.get(manager) ?? 0) + 1);\n try {\n const ready = await initialization;\n mayResume = ready !== false;\n if (signal.aborted) return;\n await continuous?.stop(manager);\n if (signal.aborted) return;\n await check.stop();\n if (signal.aborted) return;\n if (ready === false && command !== \"help\" && command !== \"unlock\" && command !== \"migrate-state\") {\n ctx.ui.notify(\n \"pi-sync recovery required. Repair the startup error, then /reload before syncing. Use /sync help for recovery guidance.\",\n \"error\",\n );\n return;\n }\n const run = () =>\n handleCommand(args, ctx, signal, loaders, attention, (setup) => {\n retry = { setup };\n });\n // Drain background children before foreground guards. Help remains reachable during repair.\n if (command === \"migrate-state\" || command === \"help\") await run();\n else await withStateDirectoryAccess(run);\n } finally {\n const count = (foreground.get(manager) ?? 1) - 1;\n if (count) foreground.set(manager, count);\n else foreground.delete(manager);\n if (mayResume) await resumeContinuous(ctx, signal, retry);\n }\n },\n });\n\n pi.on(\"session_start\", async (_event, ctx) => {\n shutdownAbort?.abort(new DOMException(\"Session replaced\", \"AbortError\"));\n shutdownAbort = undefined;\n sessionAbort.abort(new DOMException(\"Session replaced\", \"AbortError\"));\n sessionAbort = new AbortController();\n const signal = sessionAbort.signal;\n owner = ctx.sessionManager;\n continuousPossible = false;\n attention.reset(ctx);\n const previous = initialization;\n initialization = (async () => {\n await previous;\n if (signal.aborted) return false;\n await continuous?.stop();\n if (signal.aborted) return false;\n await check.stop();\n if (signal.aborted) return false;\n try {\n const config = await withStateDirectoryAccess(() => startSession(ctx, signal));\n return signal.aborted ? false : config;\n } catch (error) {\n if (!signal.aborted && ctx.hasUI) {\n ctx.ui.notify(`pi-sync recovery required: ${safeTerminalText(errorMessage(error))}`, \"error\");\n }\n return false;\n }\n })();\n const ready = await initialization;\n if (ready && !signal.aborted) {\n if (ready.continuous && ready.agentMode) await resumeContinuous(ctx, signal);\n else check.start(ctx, signal, ready);\n }\n });\n\n pi.on(\"agent_start\", async (_event, ctx) => {\n await continuous?.stop(ctx.sessionManager);\n await check.interrupt(ctx);\n });\n\n pi.on(\"agent_settled\", async (_event, ctx) => {\n const signal = sessionAbort.signal;\n if (!signal.aborted) {\n check.settled(ctx);\n if (continuousPossible) await resumeContinuous(ctx, signal);\n }\n });\n\n pi.on(\"session_shutdown\", async (event, ctx) => {\n if (continuous && owner && owner !== ctx.sessionManager) return;\n sessionAbort.abort(new DOMException(\"Session shut down\", \"AbortError\"));\n attention.reset(ctx);\n shutdownAbort?.abort(new DOMException(\"Session shut down again\", \"AbortError\"));\n const controller = new AbortController();\n shutdownAbort = controller;\n const signal = combineSignals(controller.signal, AbortSignal.timeout(30_000));\n const reason = typeof event === \"object\" && event ? (event as { reason?: string }).reason : undefined;\n try {\n const ready = await initialization;\n if (signal.aborted) return;\n await continuous?.stop(ctx.sessionManager);\n if (signal.aborted) return;\n await check.stop();\n if (signal.aborted) return;\n if (ready !== false && reason !== \"reload\") {\n await withStateDirectoryAccess(async () => {\n if (signal.aborted) return;\n await autoPushSessions(ctx, signal, loaders);\n });\n }\n } catch (error) {\n if (!signal.aborted) {\n ctx.ui.notify(`pi-sync session push skipped: ${errorMessage(error)}`, \"warning\");\n }\n } finally {\n if (shutdownAbort === controller) shutdownAbort = undefined;\n }\n if (signal.aborted) return;\n setSyncStatus(ctx, undefined);\n });\n}\n\nexport type { SyncDependencies } from \"./sync/sync-loaders.js\";\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGO,SAAS,sBACd,KACA,UACS;AACT,MAAI,CAAC,SAAU,QAAO;AACtB,QAAM,YAAY,OAAc,SAA+C;AAC7E,aAAS,IAAI;AACb,QAAI;AACF,aAAO,MAAM,KAAK;AAAA,IACpB,UAAE;AACA,eAAS,KAAK;AAAA,IAChB;AAAA,EACF;AACA,QAAM,KAA6B;AAAA,IACjC,GAAG,IAAI;AAAA,IACP,QAAQ,IAAI,SAAS,UAAU,MAAM,IAAI,GAAG,OAAO,GAAG,IAAI,CAAC;AAAA,IAC3D,SAAS,IAAI,SAAS,UAAU,MAAM,IAAI,GAAG,QAAQ,GAAG,IAAI,CAAC;AAAA,EAC/D;AAGA,SAAO,IAAI,MAAM,KAAK;AAAA,IACpB,IAAI,QAAQ,KAAK,UAAU;AACzB,aAAO,QAAQ,OAAO,KAAK,QAAQ,IAAI,QAAQ,KAAK,QAAQ;AAAA,IAC9D;AAAA,EACF,CAAC;AACH;;;ACNA,eAAsB,uBACpB,SACA,KACA,QACA,SACA,UACA,OACyB;AACzB,MAAI;AACF,UAAM,CAAC,YAAY,GAAG,IAAI,IAAI,UAAU,OA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AM,iBAAiB,KAAK,MAAM;AAAA,IAC5D;AAAA,EACF,CAAC;AAED,KAAG,GAAG,oBAAoB,OAAO,OAAO,QAAQ;AAC9C,QAAI,cAAc,SAAS,UAAU,IAAI,eAAgB;AACzD,iBAAa,MAAM,IAAI,aAAa,qBAAqB,YAAY,CAAC;AACtE,cAAU,MAAM,GAAG;AACnB,mBAAe,MAAM,IAAI,aAAa,2BAA2B,YAAY,CAAC;AAC9E,UAAM,aAAa,IAAI,gBAAgB;AACvC,oBAAgB;AAChB,UAAM,SAAS,eAAe,WAAW,QAAQ,YAAY,QAAQ,GAAM,CAAC;AAC5E,UAAM,SAAS,OAAO,UAAU,YAAY,QAAS,MAA8B,SAAS;AAC5F,QAAI;AACF,YAAM,QAAQ,MAAM;AACpB,UAAI,OAAO,QAAS;AACpB,YAAM,YAAY,KAAK,IAAI,cAAc;AACzC,UAAI,OAAO,QAAS;AACpB,YAAM,MAAM,KAAK;AACjB,UAAI,OAAO,QAAS;AACpB,UAAI,UAAU,SAAS,WAAW,UAAU;AAC1C,cAAM,yBAAyB,YAAY;AACzC,cAAI,OAAO,QAAS;AACpB,gBAAM,iBAAiB,KAAK,QAAQ,OAAO;AAAA,QAC7C,CAAC;AAAA,MACH;AAAA,IACF,SAAS,OAAO;AACd,UAAI,CAAC,OAAO,SAAS;AACnB,YAAI,GAAG,OAAO,iCAAiC,aAAa,KAAK,CAAC,IAAI,SAAS;AAAA,MACjF;AAAA,IACF,UAAE;AACA,UAAI,kBAAkB,WAAY,iBAAgB;AAAA,IACpD;AACA,QAAI,OAAO,QAAS;AACpB,kBAAc,KAAK,MAAS;AAAA,EAC9B,CAAC;AACH;",
|
|
4
|
+
"sourcesContent": ["import type { ExtensionContext } from \"@earendil-works/pi-coding-agent\";\n\n/** Track History's Pi-owned selector/confirmation lifetime without inspecting renderer internals. */\nexport function trackOperationDialogs<Context extends ExtensionContext>(\n ctx: Context,\n onDialog?: (active: boolean) => void,\n): Context {\n if (!onDialog) return ctx;\n const runDialog = async <Value>(task: () => Promise<Value>): Promise<Value> => {\n onDialog(true);\n try {\n return await task();\n } finally {\n onDialog(false);\n }\n };\n const ui: ExtensionContext[\"ui\"] = {\n ...ctx.ui,\n select: (...args) => runDialog(() => ctx.ui.select(...args)),\n confirm: (...args) => runDialog(() => ctx.ui.confirm(...args)),\n };\n // Forward live context properties: copying the context would hide session\n // replacement from mutation-owner revalidation after a dialog settles.\n return new Proxy(ctx, {\n get(target, key, receiver) {\n return key === \"ui\" ? ui : Reflect.get(target, key, receiver);\n },\n });\n}\n", "import type { ExtensionCommandContext, ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport { loadConfig, sessionTokenWarnings, syncSessionsWarnings } from \"../settings/config.js\";\nimport { activeLocalConfigPath, createLocalConfigDocument, localConfigPath } from \"../settings/config-file.js\";\nimport { localConfigTemplate, readLocalConfigObject } from \"../settings/settings-store.js\";\nimport type { AnySyncConfig } from \"../settings/settings-types.js\";\nimport { unlock, withLock } from \"../state/lock.js\";\nimport { migrateLegacyStateDirectory, stateDirectoryMigrationNotice } from \"../state/state-directory.js\";\nimport { withAgentSyncLock } from \"../sync/agent-sync.js\";\nimport { throwIfAborted } from \"../sync/signals.js\";\nimport { syncErrorGuidance } from \"../sync/sync-error-guidance.js\";\nimport { isSyncDecisionRequiredError, SetupPullRequiresUiError } from \"../sync/sync-errors.js\";\nimport type { SyncLoaders } from \"../sync/sync-loaders.js\";\nimport { RemoteSelectionMismatchError } from \"../sync/sync-policy.js\";\nimport { automaticSyncSummary } from \"../ui/automatic-sync-summary.js\";\nimport type { RunRouteResult } from \"../ui/cancellable-operation.js\";\nimport { trackOperationDialogs } from \"../ui/operation-dialogs.js\";\nimport { startupTransferSummary } from \"../ui/sync-behavior.js\";\nimport { setSyncStatus } from \"../ui/sync-status.js\";\nimport { safeTerminalText } from \"../ui/terminal-text.js\";\nimport { parseOptions, resolveSyncCommand, splitArgs, usage, validateCommandOptions } from \"./command.js\";\nimport type { CommandOptions } from \"./command-types.js\";\n\nexport async function executeRecoveryCommand(\n rawArgs: string,\n ctx: ExtensionContext,\n signal: AbortSignal | undefined,\n loaders: SyncLoaders,\n onCommit?: () => void,\n setup?: string,\n): Promise<RunRouteResult> {\n try {\n const [subcommand, ...rest] = splitArgs(rawArgs);\n if (subcommand !== \"sync\" && subcommand !== \"pull\" && subcommand !== \"push\") {\n throw new Error(`Unsupported sync recovery route: ${subcommand ?? \"missing\"}`);\n }\n const options = parseOptions(rest);\n if (setup !== undefined) options.setup = setup;\n if (signal) options.signal = signal;\n if (onCommit) options.onCommit = onCommit;\n options.reload = false;\n options.auto = false;\n validateCommandOptions(subcommand, options);\n const operations = await loaders.operations();\n throwIfAborted(options.signal);\n if (subcommand === \"push\") {\n const outcome = await withLock(\"push\", () => operations.push(ctx, options));\n return { kind: \"completed\", ...(outcome ? { outcome } : {}) };\n }\n if (subcommand === \"pull\") {\n const outcome = await withLock(\"pull\", () => operations.pull(ctx, options));\n return { kind: \"completed\", ...(outcome ? { outcome } : {}) };\n }\n await withAgentSyncLock(ctx, options, (current) => operations.syncBoth(ctx, current));\n return { kind: \"completed\" };\n } catch (error) {\n if (signal?.aborted) return { kind: \"failed\" };\n setSyncStatus(ctx, undefined);\n if (error instanceof RemoteSelectionMismatchError) {\n return { kind: \"remote-selection-required\", decision: error.decision };\n }\n if (isSyncDecisionRequiredError(error)) {\n return { kind: \"decision-required\", decision: error.decision };\n }\n ctx.ui.notify(syncErrorGuidance(error), \"error\");\n return { kind: \"failed\" };\n }\n}\n\nexport async function executeCommand(\n rawArgs: string,\n ctx: ExtensionCommandContext,\n signal: AbortSignal | undefined,\n loaders: SyncLoaders,\n onCommit?: () => void,\n setup?: string,\n onDialog?: (active: boolean) => void,\n retryRefusal = false,\n): Promise<RunRouteResult> {\n ctx = trackOperationDialogs(ctx, onDialog);\n try {\n const command = await resolveSyncCommand(rawArgs, ctx);\n if (signal?.aborted || !command) return { kind: \"completed\" };\n const { subcommand, rest } = command;\n const options = parseOptions(rest);\n if (setup !== undefined) options.setup = setup;\n if (signal) options.signal = signal;\n if (onCommit) options.onCommit = onCommit;\n validateCommandOptions(subcommand, options);\n if (retryRefusal) {\n if (subcommand !== \"sync\") throw new Error(\"A refused-model retry is available only for merged sync.\");\n options.agentRetryRefusal = true;\n }\n\n switch (subcommand) {\n case \"help\":\n ctx.ui.notify(usage(), \"info\");\n return { kind: \"completed\" };\n case \"use\": {\n const { useSyncSetup } = await loaders.setupSwitch();\n throwIfAborted(options.signal);\n await useSyncSetup(\n ctx,\n options.args[0] ?? \"\",\n async (selectedSetup) => {\n const operations = await loaders.operations();\n throwIfAborted(options.signal);\n return withLock(\"pull\", () => operations.pull(ctx, { ...options, setup: selectedSetup }));\n },\n undefined,\n options.signal,\n );\n return { kind: \"completed\" };\n }\n case \"init\":\n await initConfig(ctx, signal);\n return { kind: \"completed\" };\n case \"config\":\n await showConfig(ctx, options);\n return { kind: \"completed\" };\n case \"files\": {\n const { showFileSelection } = await import(\"../ui/file-selection.js\");\n throwIfAborted(options.signal);\n await showFileSelection(ctx, options.setup, options.signal);\n return { kind: \"completed\" };\n }\n case \"status\": {\n const operations = await loaders.operations();\n throwIfAborted(options.signal);\n await operations.status(ctx, options);\n return { kind: \"completed\" };\n }\n case \"diff\": {\n const operations = await loaders.operations();\n throwIfAborted(options.signal);\n await operations.diff(ctx, options);\n return { kind: \"completed\" };\n }\n case \"conflicts\": {\n const { showConflicts } = await import(\"../sync/conflict-review.js\");\n throwIfAborted(options.signal);\n await withLock(\"sync\", () => showConflicts(ctx, options));\n return { kind: \"completed\" };\n }\n case \"doctor\": {\n const operations = await loaders.operations();\n throwIfAborted(options.signal);\n await operations.doctor(ctx, options);\n return { kind: \"completed\" };\n }\n case \"push\": {\n const operations = await loaders.operations();\n throwIfAborted(options.signal);\n const outcome = await withLock(\"push\", () => operations.push(ctx, options));\n return { kind: \"completed\", ...(outcome ? { outcome } : {}) };\n }\n case \"pull\": {\n const operations = await loaders.operations();\n throwIfAborted(options.signal);\n const outcome = await withLock(\"pull\", () => operations.pull(ctx, options));\n return { kind: \"completed\", ...(outcome ? { outcome } : {}) };\n }\n case \"sync\": {\n const operations = await loaders.operations();\n throwIfAborted(options.signal);\n const outcome = await withAgentSyncLock(ctx, options, (current) => operations.syncBoth(ctx, current));\n return { kind: \"completed\", ...(retryRefusal && outcome ? { outcome } : {}) };\n }\n case \"history\": {\n const operations = await loaders.operations();\n throwIfAborted(options.signal);\n await operations.history(ctx, options);\n return { kind: \"completed\" };\n }\n case \"rollback\": {\n const operations = await loaders.operations();\n throwIfAborted(options.signal);\n await withLock(\"rollback\", () => operations.rollback(ctx, options));\n return { kind: \"completed\" };\n }\n case \"migrate-state\":\n await migrateStateDirectory(ctx, options);\n return { kind: \"completed\" };\n case \"unlock\":\n await unlock(ctx, options);\n return { kind: \"completed\" };\n default:\n ctx.ui.notify(`Unknown /sync command: ${subcommand}\\n\\n${usage()}`, \"warning\");\n return { kind: \"failed\" };\n }\n } catch (error) {\n if (signal?.aborted) return { kind: \"failed\" };\n setSyncStatus(ctx, undefined);\n if (error instanceof SetupPullRequiresUiError) throw error;\n if (error instanceof RemoteSelectionMismatchError) {\n return { kind: \"remote-selection-required\", decision: error.decision };\n }\n if (isSyncDecisionRequiredError(error)) {\n return { kind: \"decision-required\", decision: error.decision };\n }\n ctx.ui.notify(syncErrorGuidance(error), \"error\");\n return { kind: \"failed\" };\n }\n}\n\nasync function migrateStateDirectory(ctx: ExtensionCommandContext, options: CommandOptions) {\n const notice = stateDirectoryMigrationNotice();\n if (!notice) {\n ctx.ui.notify(\"pi-sync already uses the canonical pi-sync/ state directory.\", \"info\");\n return;\n }\n if (\n !options.yes &&\n !(await ctx.ui.confirm(\n \"Migrate pi-sync state directory\",\n \"Confirm that every other Pi process is closed. pi-sync will atomically rename .pisync/ to pi-sync/ without merging or deleting either root.\",\n { signal: options.signal },\n ))\n ) {\n ctx.ui.notify(\"pi-sync state migration cancelled.\", \"info\");\n return;\n }\n throwIfAborted(options.signal);\n const result = await migrateLegacyStateDirectory();\n throwIfAborted(options.signal);\n if (result.status === \"ready\") {\n ctx.ui.notify(\"pi-sync already uses the canonical pi-sync/ state directory.\", \"info\");\n return;\n }\n ctx.ui.notify(result.message, result.status === \"migrated\" ? \"info\" : \"warning\");\n}\n\nasync function initConfig(ctx: ExtensionCommandContext, signal?: AbortSignal) {\n const configPath = localConfigPath();\n if (await readLocalConfigObject()) {\n ctx.ui.notify(`Config already exists: ${await activeLocalConfigPath()}`, \"info\");\n return;\n }\n\n if (ctx.mode === \"tui\") {\n const { showSetupWizard } = await import(\"../ui/setup/setup-wizard.js\");\n throwIfAborted(signal);\n await showSetupWizard(ctx, signal);\n return;\n }\n await createLocalConfigDocument(localConfigTemplate());\n ctx.ui.notify(`Created ${configPath}. Add a storage connection and sync setup before syncing.`, \"info\");\n}\n\nasync function showConfig(ctx: ExtensionCommandContext, options: CommandOptions) {\n const config = await loadConfig(options.setup);\n const warnings = [\n ...(config.backend.type === \"s3\" ? sessionTokenWarnings(config.backend.profile) : []),\n ...syncSessionsWarnings(config),\n ];\n const storageLines = configStorageLines(config);\n ctx.ui.notify(\n [\n \"pi-sync config:\",\n `sync setup: ${config.setupName}`,\n `storage connection: ${config.connectionName}`,\n ...storageLines,\n `storage path: ${config.storagePath}`,\n `automatic sync: ${automaticSyncSummary(config.automatic)}`,\n `settings field merge: ${config.mergeSettings ? \"On (experimental)\" : \"Off\"}`,\n `machine-local settings.json fields: ${(config.localFields ?? []).map(safeTerminalText).join(\", \") || \"none\"}`,\n `startup transfer: ${startupTransferSummary(config)}`,\n `agent mode: ${config.agentMode ? \"On (experimental)\" : \"Off\"}`,\n `continuous sync: ${config.continuous ? (config.agentMode ? \"On (experimental)\" : \"paused; Agent mode is Off\") : \"Off\"}`,\n `included content: ${config.include.join(\", \") || \"none\"}`,\n `sessions: ${config.include.includes(\"sessions\") ? \"included\" : \"not included\"}`,\n `settings file: ${localConfigPath()}`,\n ...warnings,\n ].join(\"\\n\"),\n warnings.length > 0 ? \"warning\" : \"info\",\n );\n}\n\nfunction configStorageLines(config: AnySyncConfig) {\n switch (config.backend.type) {\n case \"git\":\n return [\n \"kind: git\",\n `remote: ${displayGitRemote(config.backend.profile.remote)}`,\n \"authentication: existing Git/SSH credentials (not stored)\",\n `branch: ${config.backend.destination.branch}`,\n ];\n case \"webdav\":\n return [\n \"kind: webdav\",\n `url: ${displayWebDavUrl(config.backend.profile.url, config.backend.profile.username)}`,\n \"username: configured (value hidden)\",\n \"password: configured\",\n ];\n case \"s3\":\n return [\n \"kind: s3\",\n `endpoint: ${config.backend.profile.endpoint}`,\n `bucket: ${config.backend.destination.bucket}`,\n `region: ${config.backend.profile.region}`,\n \"access key id: configured\",\n \"secret access key: configured\",\n `session token: ${config.backend.profile.sessionToken ? \"configured\" : \"not configured\"}`,\n ];\n }\n}\n\nfunction displayGitRemote(value: string | undefined) {\n if (!value) return \"missing\";\n try {\n const url = new URL(value);\n url.username = \"\";\n url.password = \"\";\n url.search = \"\";\n url.hash = \"\";\n return url.toString();\n } catch {\n return value.replace(/^(?:[^@\\s]+@)?(?<host>[^:]+):.+$/u, \"$<host>:\u2026\");\n }\n}\n\nfunction displayWebDavUrl(value: string | undefined, username: string | undefined) {\n if (!value) return \"missing\";\n try {\n const url = new URL(value);\n url.username = \"\";\n url.password = \"\";\n url.search = \"\";\n url.hash = \"\";\n return username ? `${url.origin}/\u2026` : `${url.origin}${url.pathname}`;\n } catch {\n return \"invalid (value hidden)\";\n }\n}\n", "import type { ExtensionCommandContext, ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport { loadConfig } from \"../settings/config.js\";\nimport { readStateForConfig, syncStateFingerprint } from \"../state/sync-state-store.js\";\nimport { combineSignals } from \"../sync/signals.js\";\nimport { errorMessage } from \"../sync/sync-errors.js\";\nimport type { SyncLoaders } from \"../sync/sync-loaders.js\";\nimport { formatRemoteSelectionMismatch } from \"../sync/sync-policy.js\";\nimport type { RunRouteResult } from \"../ui/cancellable-operation.js\";\nimport {\n observationMatchesConfig,\n type SyncAttentionController,\n type SyncAttentionOrigin,\n syncAttentionMatchesConfig,\n} from \"../ui/sync-attention.js\";\nimport { setSyncStatus } from \"../ui/sync-status.js\";\nimport { parseOptions, splitArgs, validateCommandOptions } from \"./command.js\";\nimport { executeCommand, executeRecoveryCommand } from \"./command-execution.js\";\n\nexport async function handleCommand(\n rawArgs: string,\n ctx: ExtensionCommandContext,\n sessionSignal: AbortSignal,\n loaders: SyncLoaders,\n attention: SyncAttentionController,\n onExplicitSync?: (setup?: string) => void,\n) {\n await reconcileObservation(attention, sessionSignal);\n if (sessionSignal.aborted) return;\n const run = (\n route: string,\n signal?: AbortSignal,\n onCommit?: () => void,\n target?: string,\n onDialog?: (active: boolean) => void,\n retryRefusal = false,\n ) => {\n const [command, ...args] = splitArgs(route);\n if (command === \"sync\" && !retryRefusal) {\n try {\n const options = parseOptions(args);\n validateCommandOptions(\"sync\", options);\n onExplicitSync?.(target ?? options.setup);\n } catch {\n /* Invalid routes do not request an automatic retry. */\n }\n }\n return executeCommand(\n route,\n ctx,\n combineSignals(sessionSignal, signal),\n loaders,\n observationCommitCallback(attention, sessionSignal, onCommit),\n target,\n onDialog,\n retryRefusal,\n );\n };\n if (!rawArgs.trim()) {\n try {\n const { showSyncManager } = await import(\"../ui/manager-ui.js\");\n if (sessionSignal.aborted) return;\n await showSyncManager(ctx, run, sessionSignal, {\n getAttention: () => attention.current(),\n getObservation: () => attention.observation(),\n onObservationInvalidated: () => attention.clearObservation(),\n onSelectionResolved: (expected) => {\n if (attention.current() === expected) attention.clear(ctx);\n },\n });\n } catch (error) {\n if (sessionSignal.aborted) return;\n setSyncStatus(ctx, undefined);\n ctx.ui.notify(errorMessage(error), \"error\");\n }\n await reconcileObservation(attention, sessionSignal);\n if (!sessionSignal.aborted) await attention.publish(ctx, sessionSignal);\n return;\n }\n const result = await run(rawArgs);\n if (result.kind === \"decision-required\") {\n ctx.ui.notify(result.decision.directMessage, \"error\");\n } else if (result.kind === \"remote-selection-required\") {\n const origin = directSelectionOrigin(rawArgs);\n if (origin) attention.set(result.decision, origin);\n const deterministic = splitArgs(rawArgs).some((arg) => arg === \"--yes\" || arg === \"-y\");\n if (origin && ctx.mode === \"tui\" && !deterministic) {\n await resolveSelectionAttention(ctx, attention, sessionSignal, loaders);\n } else {\n ctx.ui.notify(\n formatRemoteSelectionMismatch(\n result.decision.setupName,\n result.decision.localInclude,\n result.decision.remoteInclude,\n ),\n \"error\",\n );\n }\n }\n await clearAttentionAfterCompletedOperation(rawArgs, result, ctx, attention, sessionSignal);\n await reconcileSelectionAttention(ctx, attention, sessionSignal);\n await reconcileObservation(attention, sessionSignal);\n if (!sessionSignal.aborted) await attention.publish(ctx, sessionSignal);\n}\n\nfunction observationCommitCallback(\n attention: SyncAttentionController,\n sessionSignal: AbortSignal,\n onCommit?: () => void,\n) {\n const observed = attention.observation();\n return () => {\n // Opening or cancelling a review changes nothing. A commit may change data\n // even if later publication/baseline cleanup fails; never restore old hints.\n if (!sessionSignal.aborted && attention.observation() === observed) attention.clearObservation();\n onCommit?.();\n };\n}\n\nasync function reconcileObservation(attention: SyncAttentionController, signal: AbortSignal) {\n const observed = attention.observation();\n if (!observed || signal.aborted) return;\n try {\n const config = await loadConfig();\n if (signal.aborted || attention.observation() !== observed) return;\n if (!observationMatchesConfig(observed, config)) {\n attention.clearObservation();\n return;\n }\n const state = await readStateForConfig(config);\n if (signal.aborted || attention.observation() !== observed) return;\n if (syncStateFingerprint(state) !== observed.inspection.stateIdentity) attention.clearObservation();\n } catch {\n if (!signal.aborted && attention.observation() === observed) attention.clearObservation();\n }\n}\n\nasync function clearAttentionAfterCompletedOperation(\n rawArgs: string,\n result: RunRouteResult,\n ctx: ExtensionContext,\n attention: SyncAttentionController,\n signal: AbortSignal,\n) {\n if (result.kind !== \"completed\" || result.outcome === \"cancelled\" || signal.aborted) return;\n const [command, ...rest] = splitArgs(rawArgs);\n if (command !== \"sync\" && command !== \"pull\" && command !== \"push\") return;\n const current = attention.current();\n if (!current) return;\n try {\n const options = parseOptions(rest);\n const setupName = options.setup ?? (await loadConfig()).setupName;\n if (signal.aborted || attention.current() !== current) return;\n if (current.decision.setupName === setupName) attention.clear(ctx);\n } catch {\n // Attention reconciliation below owns malformed or concurrently changed settings.\n }\n}\n\nasync function reconcileSelectionAttention(\n ctx: ExtensionContext,\n attention: SyncAttentionController,\n signal: AbortSignal,\n) {\n const current = attention.current();\n if (!current || signal.aborted) return;\n try {\n const config = await loadConfig(current.decision.setupName);\n if (signal.aborted || attention.current() !== current) return;\n if (!syncAttentionMatchesConfig(current, config)) attention.clear(ctx);\n } catch {\n if (!signal.aborted && attention.current() === current) attention.clear(ctx);\n }\n}\n\nfunction directSelectionOrigin(rawArgs: string): SyncAttentionOrigin | undefined {\n const command = splitArgs(rawArgs)[0];\n return command === \"sync\" || command === \"pull\" || command === \"push\" ? command : undefined;\n}\n\nexport async function resolveSelectionAttention(\n ctx: ExtensionContext,\n attention: SyncAttentionController,\n signal: AbortSignal,\n loaders: SyncLoaders,\n options: {\n cancelLabel?: string;\n withStateAccess?: <T>(task: () => Promise<T>) => Promise<T>;\n } = {},\n) {\n const current = attention.current();\n if (!current || signal.aborted) return;\n const { dispatchManagerResult } = await import(\"../ui/manager-result-dispatcher.js\");\n if (signal.aborted || attention.current() !== current) return;\n await dispatchManagerResult(\n ctx,\n { kind: \"remote-selection-required\", decision: current.decision },\n current.origin,\n (route, actionSignal, onCommit, target) => {\n const execute = () =>\n executeRecoveryCommand(\n route,\n ctx,\n combineSignals(signal, actionSignal),\n loaders,\n observationCommitCallback(attention, signal, onCommit),\n target,\n );\n return options.withStateAccess ? options.withStateAccess(execute) : execute();\n },\n signal,\n {\n cancelLabel: options.cancelLabel,\n withStateAccess: options.withStateAccess,\n onSelectionResolved: () => {\n if (attention.current() === current) attention.clear(ctx);\n },\n },\n );\n}\n", "export function isMissingConfigError(error: unknown) {\n return (\n error instanceof Error &&\n (error.message.startsWith(\"Missing pi-sync settings.\") || error.message === \"No sync setups are configured.\")\n );\n}\n", "import type { ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport { setSyncSetupCompletions } from \"../commands/command.js\";\nimport type { CommandOptions } from \"../commands/command-types.js\";\nimport { loadConfig, loadPartialConfig } from \"../settings/config.js\";\nimport { isMissingConfigError } from \"../settings/config-errors.js\";\nimport { consumeLocalConfigMigrationNotice } from \"../settings/config-file.js\";\nimport { readLocalConfigObject } from \"../settings/settings-store.js\";\nimport { sessionDirFromContext, snapshotOptionsForContext } from \"../snapshot/session-paths.js\";\nimport { recoverSnapshotTransactionsOnStartup } from \"../snapshot/snapshot-transaction.js\";\nimport { withLock } from \"../state/lock.js\";\nimport { stateDirectoryMigrationNotice } from \"../state/state-directory.js\";\nimport { ensureStateDir, readStateForConfig } from \"../state/sync-state-store.js\";\nimport { configureSyncStatus, setSyncStatus } from \"../ui/sync-status.js\";\nimport { safeTerminalText } from \"../ui/terminal-text.js\";\nimport { startupTransferEnabled } from \"./agent-policy.js\";\nimport { throwIfAborted } from \"./signals.js\";\nimport { createStartupTimings } from \"./startup-timings.js\";\nimport { errorMessage } from \"./sync-errors.js\";\nimport type { SyncLoaders } from \"./sync-loaders.js\";\nimport { captureMutationOwner } from \"./sync-local.js\";\n\nconst AUTO_SYNC_OPTIONS: CommandOptions = {\n yes: true,\n force: false,\n stale: false,\n silent: true,\n reload: false,\n auto: true,\n args: [],\n};\n\nexport async function startSession(ctx: ExtensionContext, signal: AbortSignal) {\n const timings = createStartupTimings();\n let debug = false;\n let outcome: \"completed\" | \"stopped\" = \"stopped\";\n try {\n throwIfAborted(signal);\n const stateNotice = stateDirectoryMigrationNotice();\n if (stateNotice && ctx.hasUI) ctx.ui.notify(stateNotice, \"warning\");\n // Recovery can restore managed files: finish it before Pi accepts user edits.\n // Unlike remote inspection, it must never be detached behind startup.\n const validateMutation = captureMutationOwner(ctx, signal);\n const currentFile = ctx.sessionManager.getSessionFile?.();\n await timings.measure(\"transaction recovery\", () =>\n recoverSnapshotTransactionsOnStartup({\n signal,\n sessionDir: sessionDirFromContext(ctx),\n protectedTargets: currentFile ? [currentFile] : [],\n validateMutation,\n }),\n );\n throwIfAborted(signal);\n try {\n const settings = await timings.measure(\"settings read\", () => readLocalConfigObject());\n throwIfAborted(signal);\n debug = settings?.debug ?? false;\n const names = settings ? Object.keys(settings.syncSetups).sort((left, right) => left.localeCompare(right)) : [];\n setSyncSetupCompletions(names);\n configureSyncStatus(ctx, settings?.showStatus ?? true);\n } catch {\n if (signal.aborted) return;\n setSyncSetupCompletions([]);\n }\n const migrationNotice = consumeLocalConfigMigrationNotice();\n if (migrationNotice && ctx.hasUI) ctx.ui.notify(migrationNotice, \"warning\");\n throwIfAborted(signal);\n if (!ctx.hasUI) return;\n try {\n const config = await timings.measure(\"config resolution\", () => loadConfig());\n throwIfAborted(signal);\n configureSyncStatus(ctx, config.showStatus);\n outcome = \"completed\";\n return config.automatic || startupTransferEnabled(config) ? config : undefined;\n } catch (error) {\n throwIfAborted(signal);\n if (!isMissingConfigError(error)) {\n ctx.ui.notify(`pi-sync startup check skipped: ${safeTerminalText(errorMessage(error))}`, \"warning\");\n }\n }\n } finally {\n timings.publish(ctx, debug, signal, \"local initialization\", outcome);\n }\n}\n\nexport async function autoPushSessions(ctx: ExtensionContext, signal: AbortSignal, loaders: SyncLoaders) {\n try {\n const partial = await loadPartialConfig();\n throwIfAborted(signal);\n if (!partial.automatic) return;\n if (!partial.include.includes(\"sessions\")) return;\n await ensureStateDir();\n throwIfAborted(signal);\n const config = await loadConfig();\n throwIfAborted(signal);\n if (!config.include.includes(\"sessions\")) return;\n const [operations, snapshotModule, syncStateModule] = await Promise.all([\n loaders.operations(),\n loaders.snapshot(),\n loaders.syncState(),\n ]);\n throwIfAborted(signal);\n await withLock(\"auto-session-push\", async () => {\n throwIfAborted(signal);\n const state = await readStateForConfig(config);\n throwIfAborted(signal);\n const local = await snapshotModule.createSnapshot(config.snapshotIdentity, {\n ...snapshotOptionsForContext(ctx, config),\n signal,\n });\n throwIfAborted(signal);\n if (!syncStateModule.hasLocalChanges(local, state, config)) return;\n await operations.push(ctx, { ...AUTO_SYNC_OPTIONS, signal }, { config, state, local });\n });\n } catch (error) {\n if (signal.aborted || isMissingConfigError(error)) return;\n setSyncStatus(ctx, undefined);\n ctx.ui.notify(`pi-sync session push skipped: ${errorMessage(error)}`, \"warning\");\n }\n}\n", "import type { ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport { loadConfigForCheck, syncCheckConfigFingerprint } from \"../settings/config.js\";\nimport { isMissingConfigError } from \"../settings/config-errors.js\";\nimport type { AnySyncConfig } from \"../settings/settings-types.js\";\nimport { snapshotOptionsForContext } from \"../snapshot/session-paths.js\";\nimport { withLock } from \"../state/lock.js\";\nimport { withStateDirectoryAccess } from \"../state/state-directory.js\";\nimport { readStateForConfig, syncStateFingerprint } from \"../state/sync-state-store.js\";\nimport type { SyncAttentionController } from \"../ui/sync-attention.js\";\nimport { setSyncStatus } from \"../ui/sync-status.js\";\nimport { safeTerminalText } from \"../ui/terminal-text.js\";\nimport { startupTransferEnabled } from \"./agent-policy.js\";\nimport { withAgentSyncLock } from \"./agent-sync.js\";\nimport { combineSignals, throwIfAborted } from \"./signals.js\";\nimport { createStartupTimings } from \"./startup-timings.js\";\nimport { errorMessage } from \"./sync-errors.js\";\nimport type { SyncLoaders } from \"./sync-loaders.js\";\n\n/** One owned task per extension session, never keyed by the shared headless UI. */\nexport function createStartupCheck(loaders: SyncLoaders, attention: SyncAttentionController, timeoutMs = 30_000) {\n let active:\n | {\n controller: AbortController;\n promise: Promise<void>;\n owner: ExtensionContext[\"sessionManager\"];\n transfer: boolean;\n }\n | undefined;\n\n let pending: { ctx: ExtensionContext; signal: AbortSignal; config: AnySyncConfig } | undefined;\n\n const controllerApi = {\n async interrupt(ctx: ExtensionContext) {\n const task = active;\n if (!task?.transfer || task.owner !== ctx.sessionManager) return;\n task.controller.abort(new DOMException(\"Agent became busy\", \"AbortError\"));\n await task.promise;\n },\n settled(ctx: ExtensionContext) {\n const queued = pending;\n if (!queued || queued.ctx.sessionManager !== ctx.sessionManager || queued.signal.aborted || !ctx.isIdle()) return;\n pending = undefined;\n controllerApi.start(ctx, queued.signal, queued.config);\n },\n start(ctx: ExtensionContext, sessionSignal: AbortSignal, initialConfig?: AnySyncConfig) {\n if (!ctx.hasUI || sessionSignal.aborted) return;\n if (initialConfig && startupTransferEnabled(initialConfig) && !ctx.isIdle()) {\n pending = { ctx, signal: sessionSignal, config: initialConfig };\n return;\n }\n if (active) throw new Error(\"Previous startup check has not been drained.\");\n const timings = createStartupTimings();\n const controller = new AbortController();\n const signal = combineSignals(sessionSignal, controller.signal);\n const task = {\n controller,\n owner: ctx.sessionManager,\n promise: Promise.resolve(),\n transfer: Boolean(initialConfig && startupTransferEnabled(initialConfig)),\n };\n active = task;\n const isCurrent = () => !sessionSignal.aborted && active === task && task.owner === ctx.sessionManager;\n const timer = setTimeout(\n () => controller.abort(new DOMException(\"Startup check timed out\", \"TimeoutError\")),\n timeoutMs,\n );\n let config: AnySyncConfig | undefined;\n let checking = false;\n let stopped = false;\n // Handle every detached rejection here; Pi's awaited event runner cannot catch it.\n task.promise = Promise.resolve()\n .then(async () => {\n try {\n throwIfAborted(signal);\n config = initialConfig ?? (await loadConfigForCheck());\n task.transfer = startupTransferEnabled(config);\n throwIfAborted(signal);\n if (!config.automatic && !startupTransferEnabled(config)) return;\n const captured = config;\n const identity = syncCheckConfigFingerprint(captured);\n checking = true;\n setSyncStatus(ctx, \"sync ...\");\n const { inspectSync } = await timings.measure(\"inspection import\", () => loaders.inspection());\n throwIfAborted(signal);\n const currentConfig = await loadConfigForCheck();\n throwIfAborted(signal);\n if (syncCheckConfigFingerprint(currentConfig) !== identity) return;\n // Lock order: state migration guard \u2192 sync operation \u2192 backend cache.\n // Read heads may write only private cache data. Never call doctor/syncBoth.\n const inspection = await timings.measure(\"inspection and guards\", () =>\n withStateDirectoryAccess(() => {\n throwIfAborted(signal);\n return withLock(\"startup-check\", () => {\n throwIfAborted(signal);\n return inspectSync(captured, snapshotOptionsForContext(ctx, captured), signal, undefined, timings);\n });\n }),\n );\n throwIfAborted(signal);\n const latest = await loadConfigForCheck();\n throwIfAborted(signal);\n if (syncCheckConfigFingerprint(latest) !== identity) return;\n const state = await withStateDirectoryAccess(() => readStateForConfig(latest));\n throwIfAborted(signal);\n if (syncStateFingerprint(state) !== inspection.stateIdentity || !isCurrent()) return;\n attention.observe({\n setupName: captured.setupName,\n configIdentity: identity,\n checkedAt: new Date().toISOString(),\n inspection,\n automaticTransfer: startupTransferEnabled(captured),\n });\n if (\n startupTransferEnabled(captured) &&\n !inspection.firstSync &&\n inspection.head &&\n inspection.selectionState?.kind === \"same\"\n ) {\n const operations = await timings.measure(\"operations import\", () => loaders.operations());\n throwIfAborted(signal);\n if (!isCurrent()) return;\n if (!ctx.isIdle()) {\n pending = { ctx, signal: sessionSignal, config: captured };\n return;\n }\n await timings.measure(\"automatic transfer\", () =>\n withStateDirectoryAccess(() =>\n withAgentSyncLock(\n ctx,\n {\n args: [],\n yes: true,\n force: false,\n stale: false,\n silent: true,\n reload: false,\n auto: true,\n signal,\n startupTimings: timings,\n onCommit: () => attention.clearObservation(),\n },\n (options) => operations.syncBoth(ctx, options),\n ),\n ),\n );\n throwIfAborted(signal);\n if (!isCurrent()) return;\n attention.clearObservation();\n return;\n }\n attention.observe({\n setupName: captured.setupName,\n configIdentity: identity,\n checkedAt: new Date().toISOString(),\n inspection,\n automaticTransfer: startupTransferEnabled(captured),\n });\n if (ctx.mode === \"rpc\") attention.notifyObservation(ctx);\n } catch (error) {\n stopped = true;\n if (!isCurrent() || sessionSignal.aborted || isMissingConfigError(error)) return;\n if (signal.aborted && controller.signal.reason?.name !== \"TimeoutError\") return;\n // A settings edit invalidates failures as well as successful observations.\n if (config) {\n const latest = await loadConfigForCheck().catch(() => undefined);\n if (!isCurrent() || (signal.aborted && controller.signal.reason?.name !== \"TimeoutError\")) return;\n if (!latest || syncCheckConfigFingerprint(latest) !== syncCheckConfigFingerprint(config)) return;\n }\n ctx.ui.notify(\n config && startupTransferEnabled(config)\n ? `pi-sync automatic transfer stopped: ${safeTerminalText(errorMessage(error))}. Run /sync to review or reconcile retained recovery evidence. No resources were reloaded.`\n : `pi-sync startup check skipped: ${safeTerminalText(errorMessage(error))}. Run /sync status to retry. No startup transfer was performed.`,\n \"warning\",\n );\n } finally {\n clearTimeout(timer);\n if (isCurrent() && checking) {\n if (!signal.aborted || controller.signal.reason?.name === \"TimeoutError\") {\n const latest = await loadConfigForCheck().catch(() => undefined);\n if (isCurrent()) {\n if (signal.aborted && controller.signal.reason?.name !== \"TimeoutError\")\n setSyncStatus(ctx, undefined);\n else if (\n config &&\n latest &&\n syncCheckConfigFingerprint(latest) === syncCheckConfigFingerprint(config)\n )\n await attention.publish(ctx, sessionSignal);\n else attention.reset(ctx);\n }\n } else setSyncStatus(ctx, undefined);\n }\n if (isCurrent()) {\n timings.publish(\n ctx,\n config?.debug ?? false,\n sessionSignal,\n \"background startup\",\n signal.aborted || stopped ? \"stopped\" : \"completed\",\n );\n }\n if (active === task) active = undefined;\n }\n })\n .catch(() => {\n // UI teardown can itself throw. No unhandled rejection or retained timer.\n clearTimeout(timer);\n if (active === task) active = undefined;\n });\n },\n async stop() {\n pending = undefined;\n const task = active;\n if (!task) return;\n task.controller.abort(new DOMException(\"Startup check cancelled\", \"AbortError\"));\n // Drain the actual work, including child/ref cleanup, before foreground guards.\n await task.promise;\n },\n };\n return controllerApi;\n}\n", "type SetupSwitchModule = Pick<typeof import(\"./setup-switch.js\"), \"useSyncSetup\">;\ntype SnapshotModule = Pick<typeof import(\"../snapshot/snapshot.js\"), \"createSnapshot\">;\ntype SyncStateModule = Pick<typeof import(\"./sync-state.js\"), \"hasLocalChanges\">;\ntype SyncOperations = typeof import(\"./sync-operations.js\");\n\ntype SyncInspectionModule = Pick<typeof import(\"./sync-inspection.js\"), \"inspectSync\">;\n\nexport interface SyncDependencies {\n loadSyncInspection(): Promise<SyncInspectionModule>;\n loadSetupSwitch(): Promise<SetupSwitchModule>;\n loadSnapshot(): Promise<SnapshotModule>;\n loadSyncState(): Promise<SyncStateModule>;\n loadSyncOperations(): Promise<SyncOperations>;\n}\n\nexport interface SyncLoaders {\n inspection(): Promise<SyncInspectionModule>;\n setupSwitch(): Promise<SetupSwitchModule>;\n snapshot(): Promise<SnapshotModule>;\n syncState(): Promise<SyncStateModule>;\n operations(): Promise<SyncOperations>;\n}\n\nexport function createSyncLoaders(dependencies: Partial<SyncDependencies>): SyncLoaders {\n const loaders: SyncLoaders = {\n inspection: cachedModuleLoader(dependencies.loadSyncInspection ?? (() => import(\"./sync-inspection.js\"))),\n setupSwitch: cachedModuleLoader(dependencies.loadSetupSwitch ?? (() => import(\"./setup-switch.js\"))),\n snapshot: cachedModuleLoader(dependencies.loadSnapshot ?? (() => import(\"../snapshot/snapshot.js\"))),\n syncState: cachedModuleLoader(dependencies.loadSyncState ?? (() => import(\"./sync-state.js\"))),\n operations: cachedModuleLoader(dependencies.loadSyncOperations ?? (() => import(\"./sync-operations.js\"))),\n };\n return loaders;\n}\n\nfunction cachedModuleLoader<Module>(load: () => Promise<Module>): () => Promise<Module> {\n let pending: Promise<Module> | undefined;\n return () => {\n if (!pending) {\n pending = load().catch((error) => {\n pending = undefined;\n throw error;\n });\n }\n return pending;\n };\n}\n", "import type { ExtensionAPI, ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport { completeSyncArguments, splitArgs } from \"./commands/command.js\";\nimport { handleCommand } from \"./commands/command-handler.js\";\nimport type { AnySyncConfig } from \"./settings/settings-types.js\";\nimport { withStateDirectoryAccess } from \"./state/state-directory.js\";\nimport { autoPushSessions, startSession } from \"./sync/automatic-sync.js\";\nimport { combineSignals } from \"./sync/signals.js\";\nimport { createStartupCheck } from \"./sync/startup-check.js\";\nimport { errorMessage } from \"./sync/sync-errors.js\";\nimport { createSyncLoaders, type SyncDependencies } from \"./sync/sync-loaders.js\";\nimport { createSyncAttentionController } from \"./ui/sync-attention.js\";\nimport { setSyncStatus } from \"./ui/sync-status.js\";\nimport { safeTerminalText } from \"./ui/terminal-text.js\";\n\nexport default function sync(pi: ExtensionAPI, dependencies: Partial<SyncDependencies> = {}) {\n const loaders = createSyncLoaders(dependencies);\n const attention = createSyncAttentionController();\n const check = createStartupCheck(loaders, attention);\n let sessionAbort = new AbortController();\n let shutdownAbort: AbortController | undefined;\n let initialization = Promise.resolve<AnySyncConfig | false | undefined>(undefined);\n let continuous: ReturnType<typeof import(\"./sync/continuous-sync.js\")[\"createContinuousSync\"]> | undefined;\n let owner: ExtensionContext[\"sessionManager\"] | undefined;\n let continuousPossible = false;\n const foreground = new Map<ExtensionContext[\"sessionManager\"], number>();\n async function resumeContinuous(ctx: ExtensionContext, signal: AbortSignal, retry?: { setup?: string }) {\n const isCurrent = () => !signal.aborted && !foreground.has(ctx.sessionManager) && owner === ctx.sessionManager;\n if (!isCurrent() || !ctx.hasUI) return;\n try {\n const { loadConfigForCheck } = await import(\"./settings/config.js\");\n if (!isCurrent()) return;\n const config = await loadConfigForCheck();\n if (!isCurrent()) return;\n continuousPossible = Boolean(config.continuous && config.agentMode);\n if (!continuousPossible) {\n await continuous?.stop(ctx.sessionManager);\n return;\n }\n const { createContinuousSync } = await import(\"./sync/continuous-sync.js\");\n if (!isCurrent()) return;\n continuous ??= createContinuousSync(loaders);\n continuous.start(ctx, signal, Boolean(retry && (retry.setup === undefined || retry.setup === config.setupName)));\n } catch {\n /* Existing initialization/command paths report settings errors. */\n }\n }\n\n pi.registerCommand(\"sync\", {\n description: \"Sync Pi settings through Git, WebDAV, R2, or S3-compatible storage\",\n getArgumentCompletions: completeSyncArguments,\n handler: async (args, ctx) => {\n if (!ctx.hasUI) {\n throw new Error(\"/sync requires TUI or RPC mode so results and safety prompts are observable.\");\n }\n const signal = sessionAbort.signal;\n const manager = ctx.sessionManager;\n const command = splitArgs(args)[0];\n let retry: { setup?: string } | undefined;\n let mayResume = false;\n foreground.set(manager, (foreground.get(manager) ?? 0) + 1);\n try {\n const ready = await initialization;\n mayResume = ready !== false;\n if (signal.aborted) return;\n await continuous?.stop(manager);\n if (signal.aborted) return;\n await check.stop();\n if (signal.aborted) return;\n if (ready === false && command !== \"help\" && command !== \"unlock\" && command !== \"migrate-state\") {\n ctx.ui.notify(\n \"pi-sync recovery required. Repair the startup error, then /reload before syncing. Use /sync help for recovery guidance.\",\n \"error\",\n );\n return;\n }\n const run = () =>\n handleCommand(args, ctx, signal, loaders, attention, (setup) => {\n retry = { setup };\n });\n // Drain background children before foreground guards. Help remains reachable during repair.\n if (command === \"migrate-state\" || command === \"help\") await run();\n else await withStateDirectoryAccess(run);\n } finally {\n const count = (foreground.get(manager) ?? 1) - 1;\n if (count) foreground.set(manager, count);\n else foreground.delete(manager);\n if (mayResume) await resumeContinuous(ctx, signal, retry);\n }\n },\n });\n\n pi.on(\"session_start\", async (_event, ctx) => {\n shutdownAbort?.abort(new DOMException(\"Session replaced\", \"AbortError\"));\n shutdownAbort = undefined;\n sessionAbort.abort(new DOMException(\"Session replaced\", \"AbortError\"));\n sessionAbort = new AbortController();\n const signal = sessionAbort.signal;\n owner = ctx.sessionManager;\n continuousPossible = false;\n attention.reset(ctx);\n const previous = initialization;\n initialization = (async () => {\n await previous;\n if (signal.aborted) return false;\n await continuous?.stop();\n if (signal.aborted) return false;\n await check.stop();\n if (signal.aborted) return false;\n try {\n const config = await withStateDirectoryAccess(() => startSession(ctx, signal));\n return signal.aborted ? false : config;\n } catch (error) {\n if (!signal.aborted && ctx.hasUI) {\n ctx.ui.notify(`pi-sync recovery required: ${safeTerminalText(errorMessage(error))}`, \"error\");\n }\n return false;\n }\n })();\n const ready = await initialization;\n if (ready && !signal.aborted) {\n if (ready.continuous && ready.agentMode) await resumeContinuous(ctx, signal);\n else check.start(ctx, signal, ready);\n }\n });\n\n pi.on(\"agent_start\", async (_event, ctx) => {\n await continuous?.stop(ctx.sessionManager);\n await check.interrupt(ctx);\n });\n\n pi.on(\"agent_settled\", async (_event, ctx) => {\n const signal = sessionAbort.signal;\n if (!signal.aborted) {\n check.settled(ctx);\n if (continuousPossible) await resumeContinuous(ctx, signal);\n }\n });\n\n pi.on(\"session_shutdown\", async (event, ctx) => {\n if (continuous && owner && owner !== ctx.sessionManager) return;\n sessionAbort.abort(new DOMException(\"Session shut down\", \"AbortError\"));\n attention.reset(ctx);\n shutdownAbort?.abort(new DOMException(\"Session shut down again\", \"AbortError\"));\n const controller = new AbortController();\n shutdownAbort = controller;\n const signal = combineSignals(controller.signal, AbortSignal.timeout(30_000));\n const reason = typeof event === \"object\" && event ? (event as { reason?: string }).reason : undefined;\n try {\n const ready = await initialization;\n if (signal.aborted) return;\n await continuous?.stop(ctx.sessionManager);\n if (signal.aborted) return;\n await check.stop();\n if (signal.aborted) return;\n if (ready !== false && reason !== \"reload\") {\n await withStateDirectoryAccess(async () => {\n if (signal.aborted) return;\n await autoPushSessions(ctx, signal, loaders);\n });\n }\n } catch (error) {\n if (!signal.aborted) {\n ctx.ui.notify(`pi-sync session push skipped: ${errorMessage(error)}`, \"warning\");\n }\n } finally {\n if (shutdownAbort === controller) shutdownAbort = undefined;\n }\n if (signal.aborted) return;\n setSyncStatus(ctx, undefined);\n });\n}\n\nexport type { SyncDependencies } from \"./sync/sync-loaders.js\";\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGO,SAAS,sBACd,KACA,UACS;AACT,MAAI,CAAC,SAAU,QAAO;AACtB,QAAM,YAAY,OAAc,SAA+C;AAC7E,aAAS,IAAI;AACb,QAAI;AACF,aAAO,MAAM,KAAK;AAAA,IACpB,UAAE;AACA,eAAS,KAAK;AAAA,IAChB;AAAA,EACF;AACA,QAAM,KAA6B;AAAA,IACjC,GAAG,IAAI;AAAA,IACP,QAAQ,IAAI,SAAS,UAAU,MAAM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AACpB,UAAI,UAAU,SAAS,WAAW,UAAU;AAC1C,cAAM,yBAAyB,YAAY;AACzC,cAAI,OAAO,QAAS;AACpB,gBAAM,iBAAiB,KAAK,QAAQ,OAAO;AAAA,QAC7C,CAAC;AAAA,MACH;AAAA,IACF,SAAS,OAAO;AACd,UAAI,CAAC,OAAO,SAAS;AACnB,YAAI,GAAG,OAAO,iCAAiC,aAAa,KAAK,CAAC,IAAI,SAAS;AAAA,MACjF;AAAA,IACF,UAAE;AACA,UAAI,kBAAkB,WAAY,iBAAgB;AAAA,IACpD;AACA,QAAI,OAAO,QAAS;AACpB,kBAAc,KAAK,MAAS;AAAA,EAC9B,CAAC;AACH;",
|
|
6
6
|
"names": ["loadConfigForCheck"]
|
|
7
7
|
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
# Agent and Continuous Sync Recovery Boundaries
|
|
2
|
+
|
|
3
|
+
Pi Sync distinguishes a rejected pre-publication observation from an uncertain publication. Only proven freshness failures retry automatically. Unknown errors do not become retryable because their text looks temporary.
|
|
4
|
+
|
|
5
|
+
## Failure classification audit
|
|
6
|
+
|
|
7
|
+
The authoritative paths are `src/sync/merged-sync.ts`, `agent-plan.ts`, and `continuous-errors.ts`. The error classifier follows at most eight unique causes and uses typed categories, backend conflict types, HTTP status, and known operating-system error codes. It does not infer policy from provider or Git error text.
|
|
8
|
+
|
|
9
|
+
| Decision branch | Classification and next action |
|
|
10
|
+
| --- | --- |
|
|
11
|
+
| Local bytes, baseline fingerprint, or remote revision changes before no-transfer baseline acceptance | `stale`; reject acceptance and inspect fresh evidence after bounded backoff. |
|
|
12
|
+
| Local bytes, baseline fingerprint, or remote revision changes before the publication journal | `stale`; no transfer of the rejected candidate. |
|
|
13
|
+
| Local bytes or baseline changes after journal creation, before any backend publication call | Clear the safely uncommitted journal first, then report `stale`; a cleanup failure retains its original classification. |
|
|
14
|
+
| Backend proves a conflict happened before commit and the candidate cannot have been active | Retire the uncommitted journal and use the existing bounded merge attempts; exhausted attempts retain the typed conflict cause and classify as `stale`. |
|
|
15
|
+
| Upload possible-secret scan; remaining unsupported or refused Agent groups | `unsafe`; retain evidence, suppress unchanged resolution, and inspect changed evidence again. |
|
|
16
|
+
| Bounded/unsafe Agent disclosure, unsupported conflict, missing verified ancestor, or invalid candidate application | `unsafe`; no inferred ancestor or bypass of partial-sync policy. |
|
|
17
|
+
| Missing model or unusable/refused resolver output | `model`; unchanged evidence does not repeatedly dispatch. A valid cached refusal stays cached during ordinary Sync now. |
|
|
18
|
+
| Changed local, baseline, or remote evidence during resolver validation | `stale`; discard authorization for that observation. |
|
|
19
|
+
| Known HTTP/network/lock errors | Preserve the existing typed/status/code policy and bounded retry delay. |
|
|
20
|
+
| Settings fingerprint, selected model, physical session root, or idle/automatic authorization changes | Stop the old authorization; do not convert a generic authorization error to `stale`. Continuous cycle guards can cancel and load fresh authorization. |
|
|
21
|
+
| Weak automatic-publication capability, local-field/policy migration, unresolved partial state while partial sync is off, missing baseline/selection, path collisions, bounds, protected paths, or an unverified plan | Retain existing review/error paths; no new automatic permission. |
|
|
22
|
+
| Delegated preflight, filesystem, settings/content merge, or review errors | Preserve their structured category/code when present; otherwise remain conservative. |
|
|
23
|
+
| Journal identity/local-field/session-root mismatch; publication bytes or selection cannot be proved; interrupted baseline changes; unsafe apply-only remote advance; missing remote selection metadata; lost automatic apply idle; remote changes during local apply | Preserve the journal and existing conservative recovery. No new automatic republishing or rollback is authorized. |
|
|
24
|
+
| Other publication exceptions or opaque provider/Git errors | Retain the cause and recovery evidence; `unknown` when no authoritative category is available. |
|
|
25
|
+
|
|
26
|
+
Existing safe journal retirement is unchanged. An inactive candidate with unchanged local/baseline preimages can be retired without publication. An apply-only journal with an advanced head can be retired only when its original preimages are unchanged. A journal whose committed baseline is already accepted needs cleanup, not another transfer.
|
|
27
|
+
|
|
28
|
+
## Resolver cancellation
|
|
29
|
+
|
|
30
|
+
The resolver combines caller cancellation with its own deadline and passes that signal to pre-dispatch validation, reservation, post-reservation validation, and post-response validation. Snapshot reads and backend head requests receive that signal. Ownership, settings, model, baseline, local bytes, and remote revision are checked again before acceptance.
|
|
31
|
+
|
|
32
|
+
SDK runtime/session construction and atomic private-file writes have no interruptible publication boundary. Pi Sync awaits those operations, checks cancellation around them, and drains the actual prompt and callbacks before releasing its claim and disposing the SDK session. It does not abandon them with `Promise.race()`. Installed Pi `AgentSession.abort()` waits for idle; `dispose()` is not a substitute for awaiting abort.
|
|
33
|
+
|
|
34
|
+
A request reservation published before cancellation remains spent. An atomic candidate replacement or remote commit remains committed. Provider content and charges cannot be recalled. The resolver deadline and outer startup/Continuous deadlines are separate; cleanup can take additional time.
|
|
35
|
+
|
|
36
|
+
## Confirmed refusal retry
|
|
37
|
+
|
|
38
|
+
Ordinary Sync now retains its existing cached-result policy. The manager-only **Retry refused model result…** action uses the same `sync` operation with an internal control value, not a new public command, flag, or setting.
|
|
39
|
+
|
|
40
|
+
The action requires Agent mode, foreground TUI/RPC, an accepted baseline, matching current evidence, a valid cached refusal, and no pending merge journal. A pending journal must be reconciled through ordinary Sync now or reviewed recovery first. A missing, accepted, corrupt, stale, or unverified cached result is not retry authorization. Opening the manager may show the action before eligibility is known; activation checks it without dispatching when those conditions are absent.
|
|
41
|
+
|
|
42
|
+
The flow holds the existing resolver claim while the operation lock is released for review and inference. The safe-default review names the setup, connection, exact configured storage path and bucket/branch where applicable, selected provider/model, conflict paths, disclosure, cost, and possible writes. Confirmation binds the same candidate key and cache bytes. Changed settings, model, session, evidence, or cache invalidates it. A competing participant cannot obtain another live resolver claim.
|
|
43
|
+
|
|
44
|
+
One fresh request is permitted for the reviewed candidate. A second refusal, malformed response, cancellation before acceptance, or changed evidence does not replace the active refusal. A complete result passes the normal parser, assembled-file bounds, merged-target preflight, upload secret policy, and fresh local/baseline/remote checks before its cache publication callback can run. Under the claim and operation lock, Pi Sync checks the original cache again and writes a private content-keyed refusal archive before atomic active-candidate replacement. Failed replacement retains the old result; a failure after replacement publication still retains the archive. The existing candidate format is unchanged, and older readers ignore the archive names.
|
|
45
|
+
|
|
46
|
+
Retry does not reset Continuous request counts, remove candidates, or add background confirmation dialogs. A reviewed retry is a separate manual authorization and can incur another charge even when the automatic window is full. It does not authorize retries for another candidate if evidence changes later.
|
|
47
|
+
|
|
48
|
+
## Read-only diagnostics
|
|
49
|
+
|
|
50
|
+
Status normalizes only a detached record read. It reports the rolling-window allowance, next window eligibility, exhausted candidate counts, serialized accounting capacity, actual stored bytes, verified advisory owner, and category-specific recovery actions. Window allowance is not dispatch authority. Candidate, capacity, ownership, and safety checks still apply.
|
|
51
|
+
|
|
52
|
+
The owner's model is unavailable unless authoritative owner data supplies it; the current observing session is not evidence of another owner's model. Invalid records are retained and do not represent unused allowance. Status creates no directories, leases, reservations or files and does not clear accounting. Full accounting requires reviewed repair, not count pruning or deletion. Candidate and refusal archives remain retained without automatic pruning.
|
|
53
|
+
|
|
54
|
+
## Verification
|
|
55
|
+
|
|
56
|
+
The audit follows root and package `AGENTS.md`, `docs/extension-conventions.md`, `docs/extension-settings.md`, and `docs/readme-conventions.md`. It checks touched-area requirements, asynchronous cancellation/disposal/replacement/shutdown, prefix stability, atomic private publication, unchanged settings/accounting formats, TUI/RPC behavior, and package boundaries.
|
|
57
|
+
|
|
58
|
+
Focused tests cover recovery races and content repair, disclosure preflight, deadline propagation and draining, refusal review/replacement, structural merge fixtures, and read-only diagnostics. The [quality corpus](agent-quality-verification.md) defines structural expectations; mocked replies do not measure model accuracy.
|
|
59
|
+
|
|
60
|
+
Verification uses the Node version pinned by `.node-version` and its bundled npm. A full serial run used Vitest's public `VITEST_MAX_WORKERS=1` override on a busy host. The final full gate also passes with the standard worker configuration; the 5,000 ms test limit is unchanged.
|
|
61
|
+
|
|
62
|
+
| Check | Evidence |
|
|
63
|
+
| --- | --- |
|
|
64
|
+
| `npm run check` | Builds, Biome, package boundaries, and workspace typechecks pass. Existing informational lint notices remain. |
|
|
65
|
+
| Full `npm test` with pinned Node | 744 files pass; 13,103 tests pass and 19 existing tests are skipped; zero unhandled errors. The earlier full serial run also passed before two final owner-expiry cases were added. |
|
|
66
|
+
| Original-source regressions | Two recovery cases fail with `blocked/unknown`, the disclosure preflight fails with one request instead of zero, and all nine resolver deadline regressions fail before the fix. The fixed focused recovery/preflight/deadline/Jiti run passes 35 tests. |
|
|
67
|
+
| Generated Jiti runtime | Command, startup, Continuous, and confirmed-refusal retry resolve synthetic conflicts against conditional loopback WebDAV. The retry loads its lazy review chunk and retains a refusal archive. |
|
|
68
|
+
| Package-directory RPC, default Off | Command discovery and manager/Settings navigation pass; settings bytes remain unchanged and no agent run or scheduler/resolver resource starts. |
|
|
69
|
+
| Package-directory RPC, Continuous On | A synthetic local edit publishes automatically to loopback storage; durable provider count is zero and the scheduler lease is absent after orderly exit. |
|
|
70
|
+
| Package build and archives | Package build, `npm run package:pack -- sync`, and a real temporary archive pass. All 306 files match the runtime/docs boundary; no tests, private state, credentials, or `node_modules` are included, and Pi peers stay external. |
|
|
71
|
+
| README and semantic review | Required headings/order pass for all 36 package READMEs; changed local links resolve. Independent source review and the final diff audit cover correctness, trust boundaries, lifecycle, persistence, compatibility, regressions, and scope. |
|
|
72
|
+
|
|
73
|
+
Earlier verification exposed test typing/lint issues, fixture assumptions, and an asynchronous menu-factory adapter regression; these were corrected and the affected suites rerun. The final manager checks cover 35 refusal UI cases, including owner expiry before a recovery warning. Source review also corrected no-consent partial progress, premature refusal replacement, and silently dropped recovery decisions. A full run with the shell's older Node passed all 13,099 executed tests but failed the repository's pinned-Node setup assertion; it is not a passing gate. Earlier parallel attempts also hit host-load timeouts. No timeout was increased or failing suite skipped to obtain a result.
|
|
74
|
+
|
|
75
|
+
No live provider, production Git/S3/WebDAV, Windows, or Android verification is claimed. The corpus does not measure production semantic model accuracy. No package publication, tag, visibility change, release workflow, or live model request is part of this change.
|
|
76
|
+
|
|
77
|
+
## Downgrade and recovery
|
|
78
|
+
|
|
79
|
+
Stop Continuous sync and drain all participating owners before downgrade. Disable Agent mode too if autonomous startup work must stop. Reconcile pending journals with the current runtime. Preserve backups, snapshots, accepted and refused candidates, unresolved groups, and request accounting. This change adds no settings, accounting, or candidate schema migration. Do not delete private state to regain allowance or blindly republish an uncertain transfer.
|
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
This record describes the experimental implementation and its verification scope. The [settings reference](settings.md#experimental-agent-mode) is authoritative for user behavior, limits, privacy, and recovery.
|
|
4
4
|
|
|
5
|
+
Later recovery, cancellation, confirmed-refusal retry, and diagnostics changes are documented in [Agent and Continuous sync recovery boundaries](agent-continuous-hardening.md). The [synthetic quality corpus](agent-quality-verification.md) adds structural tests without claiming measured model accuracy. Historical verification below describes the original implementation.
|
|
6
|
+
|
|
5
7
|
## Boundaries and semantic review
|
|
6
8
|
|
|
7
9
|
- The implementation changes pi-sync only, plus its Changeset and matching bundled-Pi peer declarations in the manifest/lockfile. It does not modify Pi core or depend on another extension.
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# Synthetic Agent merge-quality verification
|
|
2
|
+
|
|
3
|
+
The [corpus](../test/agent-quality-corpus.ts) and [tests](../test/agent-quality.test.ts) check structural merge safety with synthetic data and fixed resolver responses. They do not measure real-model semantic accuracy. Agent mode remains experimental and default-off; the [settings reference](settings.md#experimental-agent-mode) and [implementation verification](agent-mode-verification.md) retain their authority.
|
|
4
|
+
|
|
5
|
+
## Deterministic evidence
|
|
6
|
+
|
|
7
|
+
Each fixture defines base/local/remote bytes, exact disclosed units, fixed result rows, and an accepted byte image or required refusal. `null` means a missing file; `""` means an existing zero-byte file. Text fixtures also define exact code-owned spans before, between, and after model-owned regions. Expected output is not generated by the production merge implementation.
|
|
8
|
+
|
|
9
|
+
| Cases | Assertions |
|
|
10
|
+
| --- | --- |
|
|
11
|
+
| Separate and bridged overlapping hunks | Unit boundaries, independent edits from both sides, whitespace, full accepted bytes and file hash. |
|
|
12
|
+
| Same-point insertions and insertions at both deletion boundaries | Empty ancestors/local hunks remain valid evidence; boundary ownership is symmetric. A nonempty replacement can retain an insertion while deleting old lines. |
|
|
13
|
+
| Delete/modify hunks and existing empty files | Fixture refusal leaves the whole path unresolved. Empty text replacements are invalid, independently of file eligibility. |
|
|
14
|
+
| Repeated lines, LF, CRLF, Unicode and missing final newlines | Exact code-owned bytes and exact fixed replacement bytes survive assembly. The validator does not enforce a model-owned newline policy. |
|
|
15
|
+
| Opposite hidden timeout policies | Identical disclosed hunks omit the policy needed to choose a value. Both fixtures require refusal, without adding surrounding context. |
|
|
16
|
+
| Coupled provider/model and analytics/tracking settings | Select complete existing units from either side, never a mixed pair. Preserve local BOM, CRLF, member spelling, unknown numeric spelling and independent theme changes. |
|
|
17
|
+
| Missing-file delete/modify conflicts | No eligible units; the conflict remains unresolved. Unchanged-versus-deleted files still use deterministic deletion, not model output. |
|
|
18
|
+
|
|
19
|
+
The resolver tests use the existing mock transport and isolated runner. They assert one request, no tools, exactly the declared units in the user payload, and the expected candidate outcome. Unsupported missing-file conflicts are tested locally, not sent to the runner. Candidate tests reject missing, duplicate or unowned IDs, extra fields, invalid refusals, forbidden empty replacements, and settings synthesis. They repeat validation at the persisted-candidate application boundary. One refusal withholds every unit in that file, including otherwise accepted units.
|
|
20
|
+
|
|
21
|
+
These tests prove fixture routing, contract validation and byte assembly for the listed inputs. A fixed response does not prove that a model can infer that response. Required semantic refusal is an evaluation oracle, not a runtime guarantee: a dedicated test shows that a schema-valid timeout choice can pass validation despite violating the hidden-context refusal oracle. No additional context, tool, production path, provider API or evaluation command is introduced.
|
|
22
|
+
|
|
23
|
+
## Separately approved provider evaluation
|
|
24
|
+
|
|
25
|
+
No provider evaluation is authorized or executed by this work. A future evaluation must follow this protocol:
|
|
26
|
+
|
|
27
|
+
1. Obtain explicit approval for the provider/model, model version when available, request count, cost ceiling, repetitions, deadline and retention policy. Keep Agent and Continuous settings unchanged. Stop after one clear external-service or entitlement failure unless a retry is separately requested.
|
|
28
|
+
2. Freeze the repository revision, corpus revision, resolver contract, model settings and scoring rules before requests. Register allowed exact outputs or whole-settings source choices for each resolvable case. The deterministic fixture response is one reference, not evidence that it is the only valid semantic merge. Do not add allowed results after seeing responses; report unregistered alternatives separately for review.
|
|
29
|
+
3. Use only the committed synthetic fixtures. Exclude user files, session history, credentials, real remote storage and discovered resources. Send only the current bounded unit payload and existing resolver instructions. Do not send full files, hidden policies, expected answers, scoring notes or neighboring context. Keep unsupported cases as local eligibility checks; they must not cause a provider request.
|
|
30
|
+
4. Record each attempt without overwriting failures: fixture ID, approved provider/model, outcome, schema validity, refused IDs, exact accepted bytes, elapsed time and provider-reported usage. Preserve raw synthetic output for review, but exclude authentication and provider error payloads. Do not retry refusals automatically.
|
|
31
|
+
5. Score the outcomes with the measures below. Review every semantic mismatch against the frozen oracle. Report counts and denominators, including failures, rather than only a success percentage. Keep provider/model results separate and state the small synthetic sample's limits.
|
|
32
|
+
|
|
33
|
+
| Measure | Definition |
|
|
34
|
+
| --- | --- |
|
|
35
|
+
| Incorrect acceptance | A completed acceptance on a required-refusal case, a byte change outside owned regions, a broken atomic settings choice, or output outside the registered accepted set. Report count divided by completed acceptances, plus affected fixture IDs. |
|
|
36
|
+
| Incorrect refusal | Any refused required unit in a resolvable case. Report count divided by resolvable attempts. Report correct refusals divided by required-refusal attempts separately. |
|
|
37
|
+
| Contract/eligibility failures | Report malformed/incomplete responses, timeouts, transport failures and unauthorized dispatches separately. A partial refusal leaves the path unresolved; it is not a successful acceptance. Do not remove failed attempts from totals or treat them as correct refusals. |
|
|
38
|
+
| Latency | Measure wall-clock duration with a monotonic clock from resolver invocation to completion/failure, including validation. Report per-case values, median and tail values with sample size; include timeout duration and do not infer provider-only latency. |
|
|
39
|
+
| Usage | Record request count and provider-reported input, output, cache-read and cache-write tokens, plus cost when available. Mark unavailable values as unknown; do not use mock usage or assume cancellation prevented charges. |
|
|
40
|
+
|
|
41
|
+
For a multi-unit file, an acceptance is complete only when every required unit is resolved and the entire assembled file passes the registered oracle. A required refusal is correct only when the file remains unresolved. Report any real-model observations as results for that provider, contract and synthetic corpus only. They do not establish production reliability or justify wider disclosure or model authority.
|
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
This record describes implementation evidence and test scope. The [settings reference](settings.md#experimental-continuous-sync) owns user-facing behavior, limits and recovery.
|
|
4
4
|
|
|
5
|
+
Later recovery classification, deadline propagation, confirmed-refusal retry, and read-only allowance/capacity diagnostics are documented in [Agent and Continuous sync recovery boundaries](agent-continuous-hardening.md). Historical verification below describes the original implementation.
|
|
6
|
+
|
|
5
7
|
## Boundaries and semantic audit
|
|
6
8
|
|
|
7
9
|
The change is confined to Pi Sync and its Changeset. It adds no dependency, provider, public command, interval setting, environment variable, Pi core change or dependency on another extension. Continuous sync is a separate experimental opt-in; Agent mode alone retains its existing behavior.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@narumitw/pi-sync",
|
|
3
|
-
"version": "0.57.
|
|
3
|
+
"version": "0.57.5",
|
|
4
4
|
"description": "Pi extension that syncs Pi configuration through Git, WebDAV, Cloudflare R2, or S3-compatible storage.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -45,14 +45,14 @@
|
|
|
45
45
|
"typecheck": "tsc --noEmit"
|
|
46
46
|
},
|
|
47
47
|
"dependencies": {
|
|
48
|
-
"@narumitw/pi-tui-kit": "^0.
|
|
48
|
+
"@narumitw/pi-tui-kit": "^0.67.0",
|
|
49
49
|
"fast-xml-parser": "^5.11.2",
|
|
50
50
|
"proper-lockfile": "^4.1.2",
|
|
51
51
|
"semver": "^7.8.5"
|
|
52
52
|
},
|
|
53
53
|
"devDependencies": {
|
|
54
|
-
"@earendil-works/pi-coding-agent": "1.
|
|
55
|
-
"@earendil-works/pi-tui": "1.
|
|
54
|
+
"@earendil-works/pi-coding-agent": "1.4.0",
|
|
55
|
+
"@earendil-works/pi-tui": "1.4.0",
|
|
56
56
|
"@types/proper-lockfile": "^4.1.4",
|
|
57
57
|
"@types/semver": "^7.8.0",
|
|
58
58
|
"esbuild": "0.28.2",
|