dsh-config-manager 0.8.2 → 0.9.0
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/lib/adapters/mcp.js +42 -13
- package/lib/adapters/messages.d.ts +1 -0
- package/lib/adapters/messages.js +2 -0
- package/lib/adapters/patch-key-guard.d.ts +23 -0
- package/lib/adapters/patch-key-guard.js +13 -0
- package/lib/adapters/plugin-data.d.ts +19 -5
- package/lib/adapters/plugin-data.js +76 -22
- package/lib/adapters/plugins.d.ts +14 -1
- package/lib/adapters/plugins.js +147 -4
- package/lib/cli/actions.d.ts +7 -105
- package/lib/cli/actions.js +16 -172
- package/lib/cli/control-state.d.ts +54 -0
- package/lib/cli/control-state.js +107 -0
- package/lib/cli/index.js +14 -0
- package/lib/cli/write-gates.d.ts +61 -0
- package/lib/cli/write-gates.js +110 -0
- package/lib/client.d.ts +104 -49
- package/lib/client.js +12536 -12006
- package/lib/core/backup.d.ts +0 -4
- package/lib/core/backup.js +21 -4
- package/lib/core/boot-rescue.d.ts +1 -1
- package/lib/core/boot-rescue.js +12 -1
- package/lib/core/boot-safety.js +37 -2
- package/lib/core/conflict-decisions.js +2 -1
- package/lib/core/exporter.js +22 -1
- package/lib/core/journal.d.ts +54 -4
- package/lib/core/journal.js +158 -35
- package/lib/core/local-plugin-host.d.ts +29 -0
- package/lib/core/local-plugin-host.js +55 -48
- package/lib/core/messages.d.ts +7 -0
- package/lib/core/messages.js +14 -0
- package/lib/core/migration-history.js +16 -9
- package/lib/core/model-tools.d.ts +2 -2
- package/lib/core/model-tools.js +14 -2
- package/lib/core/patch-secret-guard.d.ts +49 -0
- package/lib/core/patch-secret-guard.js +164 -0
- package/lib/core/reconcile.d.ts +8 -0
- package/lib/core/reconcile.js +18 -3
- package/lib/core/reinstall.d.ts +2 -0
- package/lib/core/reinstall.js +6 -2
- package/lib/core/restore.js +31 -6
- package/lib/core/section-sanitize.d.ts +32 -0
- package/lib/core/section-sanitize.js +13 -0
- package/lib/core/snapshot-diff.d.ts +30 -0
- package/lib/core/snapshot-diff.js +56 -20
- package/lib/core/startup-barrier.js +8 -2
- package/lib/core/types.d.ts +22 -0
- package/lib/core/update-check.js +51 -2
- package/lib/foreign/kernel.js +9 -2
- package/lib/foreign/read-claude-plugins.js +29 -11
- package/lib/foreign/read-dsh.js +31 -2
- package/lib/foreign/session-ir.js +50 -9
- package/lib/foreign/session-read.d.ts +8 -0
- package/lib/foreign/session-read.js +26 -0
- package/lib/index.d.ts +1 -1
- package/lib/index.js +1 -1
- package/lib/profiles/dsh-profile-io.d.ts +20 -0
- package/lib/profiles/dsh-profile-io.js +27 -0
- package/lib/profiles/dsh-profile-manager.d.ts +27 -0
- package/lib/profiles/dsh-profile-manager.js +45 -4
- package/lib/profiles/dsh-profile-runtime.d.ts +5 -1
- package/lib/profiles/dsh-profile-runtime.js +16 -3
- package/lib/profiles/process-control.d.ts +18 -1
- package/lib/profiles/process-control.js +25 -1
- package/lib/routes/profiles.js +2 -1
- package/lib/routes/sync.js +13 -1
- package/lib/schema/types.d.ts +11 -0
- package/lib/security/redaction.js +22 -6
- package/lib/sync/autosync-repeat.d.ts +27 -0
- package/lib/sync/autosync-repeat.js +23 -0
- package/lib/sync/autosync-scheduler.d.ts +34 -1
- package/lib/sync/autosync-scheduler.js +151 -43
- package/lib/sync/baseline-heal.js +7 -0
- package/lib/sync/baseline-record.d.ts +67 -0
- package/lib/sync/baseline-record.js +74 -0
- package/lib/sync/blob-store.js +13 -0
- package/lib/sync/content-diff.d.ts +39 -0
- package/lib/sync/content-diff.js +46 -0
- package/lib/sync/git/git-transport.d.ts +32 -1
- package/lib/sync/git/git-transport.js +146 -26
- package/lib/sync/github-auth.d.ts +17 -1
- package/lib/sync/github-auth.js +37 -1
- package/lib/sync/merge-apply-plan.d.ts +38 -0
- package/lib/sync/merge-apply-plan.js +76 -0
- package/lib/sync/messages.d.ts +1 -0
- package/lib/sync/messages.js +2 -0
- package/lib/sync/pending-merge.d.ts +34 -0
- package/lib/sync/pending-merge.js +53 -0
- package/lib/sync/s3/s3-transport.d.ts +14 -2
- package/lib/sync/s3/s3-transport.js +72 -48
- package/lib/sync/sync-engine.d.ts +23 -40
- package/lib/sync/sync-engine.js +115 -132
- package/lib/sync/sync-history.d.ts +7 -0
- package/lib/sync/sync-state.d.ts +28 -0
- package/lib/sync/sync-state.js +20 -0
- package/lib/sync/transport.d.ts +12 -3
- package/lib/sync/transport.js +13 -4
- package/lib/sync/webdav/webdav-transport.d.ts +19 -2
- package/lib/sync/webdav/webdav-transport.js +81 -40
- package/lib/ui/commands.js +5 -11
- package/lib/ui/dsh-profiles-view.d.ts +8 -3
- package/lib/ui/dsh-profiles-view.js +9 -5
- package/lib/ui/i18n.d.ts +2 -1
- package/lib/ui/i18n.js +4 -2
- package/lib/ui/menu-placement.js +1 -1
- package/lib/ui/migration-consult-view.d.ts +11 -0
- package/lib/ui/migration-consult-view.js +15 -0
- package/lib/ui/overview-view.d.ts +7 -0
- package/lib/ui/overview-view.js +3 -0
- package/lib/ui/report.d.ts +9 -0
- package/lib/ui/report.js +17 -4
- package/lib/ui/selection-model.d.ts +8 -0
- package/lib/ui/selection-model.js +16 -0
- package/lib/utils/patch-yaml.d.ts +39 -1
- package/lib/utils/patch-yaml.js +82 -2
- package/lib/utils/paths.d.ts +13 -0
- package/lib/utils/paths.js +35 -0
- package/lib/utils/workdir-lock.js +18 -3
- package/package.json +2 -1
- package/src/adapters/mcp.test.ts +29 -0
- package/src/adapters/mcp.ts +43 -12
- package/src/adapters/messages.ts +2 -0
- package/src/adapters/patch-key-guard.ts +29 -0
- package/src/adapters/plugin-data.test.ts +126 -0
- package/src/adapters/plugin-data.ts +97 -26
- package/src/adapters/plugins.test.ts +288 -0
- package/src/adapters/plugins.ts +141 -4
- package/src/cli/actions.test.ts +74 -1
- package/src/cli/actions.ts +27 -246
- package/src/cli/control-state.ts +143 -0
- package/src/cli/index.ts +18 -0
- package/src/cli/web/web.test.ts +27 -0
- package/src/cli/write-gates.ts +149 -0
- package/src/client/about/AboutPanel.tsx +7 -6
- package/src/client/about/release-notes-view.test.ts +17 -0
- package/src/client/about/release-notes-view.ts +49 -24
- package/src/client/chat/ChatEntryView.tsx +2 -2
- package/src/client/chat/rollback-entry-view.ts +6 -1
- package/src/client/common/CommandPalette.tsx +6 -3
- package/src/client/common/ConfirmDialog.tsx +29 -12
- package/src/client/common/ContentPicker.tsx +13 -12
- package/src/client/common/Modal.tsx +12 -5
- package/src/client/common/MoreMenu.tsx +4 -1
- package/src/client/common/RunsCenter.tsx +103 -32
- package/src/client/common/Select.tsx +2 -2
- package/src/client/common/floating-bounds.ts +1 -1
- package/src/client/common/floating-units.test.ts +1 -2
- package/src/client/common/plan-text-redaction.test.ts +188 -3
- package/src/client/common/runs-center-guard.test.ts +60 -0
- package/src/client/common/runs-center-view.test.ts +128 -0
- package/src/client/common/runs-center-view.ts +96 -0
- package/src/client/common/section-title-action.test.ts +66 -0
- package/src/client/common/ui.tsx +93 -30
- package/src/client/config-manager.module.css +1507 -272
- package/src/client/consult/ConsultCard.tsx +7 -6
- package/src/client/environment/EnvironmentPanel.tsx +20 -21
- package/src/client/environment/maintenance/DiskUsageCard.tsx +65 -91
- package/src/client/environment/profiles-incomplete-ui.test.ts +8 -8
- package/src/client/export/ExportView.tsx +7 -16
- package/src/client/history/HistoryPanel.tsx +88 -28
- package/src/client/history/history-locales.ts +3 -3
- package/src/client/home/BackupScheduleCard.tsx +35 -30
- package/src/client/home/HomePanel.tsx +45 -10
- package/src/client/import/ConflictList.tsx +13 -13
- package/src/client/import/ForeignImportView.tsx +7 -6
- package/src/client/import/ImportWizardView.tsx +2 -3
- package/src/client/import/PathMappingForm.tsx +4 -4
- package/src/client/import/PathPickerDialog.tsx +2 -1
- package/src/client/import/import-wizard-steps.tsx +51 -39
- package/src/client/import/use-import-wizard-controller.test.ts +129 -0
- package/src/client/import/use-import-wizard-controller.ts +116 -22
- package/src/client/library/ArtifactRow.tsx +2 -2
- package/src/client/library/BackupInspectView.tsx +19 -15
- package/src/client/library/LibraryActions.tsx +56 -16
- package/src/client/library/LibraryPanel.tsx +7 -7
- package/src/client/library/RestorePlanView.tsx +13 -8
- package/src/client/locales/about.ts +0 -2
- package/src/client/locales/backup.ts +10 -12
- package/src/client/locales/common.ts +2 -0
- package/src/client/locales/export.ts +5 -12
- package/src/client/locales/foreign.ts +2 -2
- package/src/client/locales/import.ts +3 -2
- package/src/client/locales/overview.ts +4 -0
- package/src/client/locales/profiles.ts +32 -4
- package/src/client/locales/restore.ts +0 -2
- package/src/client/locales/sessions.ts +0 -2
- package/src/client/locales/shell.ts +2 -2
- package/src/client/market/MarketPanel.tsx +38 -20
- package/src/client/market/MyConfigsList.tsx +34 -32
- package/src/client/market/MyConfigsLoginCard.tsx +12 -15
- package/src/client/market/MyConfigsView.tsx +5 -5
- package/src/client/market/MyConfigsWizard.tsx +7 -12
- package/src/client/market/market-locales.ts +0 -6
- package/src/client/market/my-configs-split.test.ts +2 -1
- package/src/client/nav-menu-clip-guard.test.ts +52 -0
- package/src/client/recovery/IncompleteCopiesSection.tsx +1 -3
- package/src/client/recovery/RecoveryPanel.tsx +31 -16
- package/src/client/recovery/RollbackCard.tsx +58 -16
- package/src/client/recovery/RollbackFileChanges.tsx +40 -27
- package/src/client/recovery/SessionHealthCard.tsx +2 -2
- package/src/client/recovery/SessionHealthDialog.tsx +5 -7
- package/src/client/recovery/SessionLayoutSection.tsx +3 -5
- package/src/client/recovery/recovery-locales.ts +12 -8
- package/src/client/run-store.test.ts +30 -0
- package/src/client/run-store.ts +21 -1
- package/src/client/sync/AddChannelCard.tsx +65 -0
- package/src/client/sync/AutosyncCard.tsx +182 -108
- package/src/client/sync/ChannelClearConfirmDialog.tsx +5 -1
- package/src/client/sync/ChannelConfigDialog.tsx +27 -48
- package/src/client/sync/MergePreviewView.tsx +3 -5
- package/src/client/sync/PushReportSections.tsx +35 -0
- package/src/client/sync/SyncChannelEntryCard.tsx +33 -24
- package/src/client/sync/SyncConfirmView.tsx +3 -3
- package/src/client/sync/SyncLogList.tsx +16 -5
- package/src/client/sync/SyncPanel.tsx +153 -159
- package/src/client/sync/SyncProbeRow.tsx +5 -7
- package/src/client/sync/SyncRepositoryPicker.tsx +17 -4
- package/src/client/sync/SyncSecuritySection.tsx +157 -0
- package/src/client/sync/SyncSettingsDialog.tsx +304 -0
- package/src/client/sync/SyncSettingsView.test.ts +26 -8
- package/src/client/sync/WorkDirCard.tsx +2 -4
- package/src/client/sync/config-clear-guard.test.ts +94 -0
- package/src/client/sync/config-clear-guard.ts +98 -0
- package/src/client/sync/config-dirty.test.ts +91 -0
- package/src/client/sync/config-dirty.ts +88 -0
- package/src/client/sync/history-model.test.ts +2 -0
- package/src/client/sync/history-model.ts +3 -0
- package/src/client/sync/merge-request.ts +20 -0
- package/src/client/sync/sync-api.ts +12 -0
- package/src/client/sync/sync-locales.ts +87 -47
- package/src/client/sync/sync-panel-clear.test.ts +44 -0
- package/src/client/sync/sync-view.test.ts +20 -0
- package/src/client/sync/sync-view.ts +42 -4
- package/src/core/backup.test.ts +61 -1
- package/src/core/backup.ts +21 -4
- package/src/core/boot-rescue.test.ts +35 -0
- package/src/core/boot-rescue.ts +13 -2
- package/src/core/boot-safety.test.ts +25 -0
- package/src/core/boot-safety.ts +37 -2
- package/src/core/conflict-decisions.ts +2 -1
- package/src/core/exporter.ts +21 -1
- package/src/core/journal.test.ts +183 -0
- package/src/core/journal.ts +163 -25
- package/src/core/local-plugin-host.test.ts +68 -2
- package/src/core/local-plugin-host.ts +31 -4
- package/src/core/messages.ts +14 -0
- package/src/core/migration-history.test.ts +27 -0
- package/src/core/migration-history.ts +12 -4
- package/src/core/model-tools.test.ts +67 -0
- package/src/core/model-tools.ts +16 -4
- package/src/core/patch-secret-guard.test.ts +110 -0
- package/src/core/patch-secret-guard.ts +176 -0
- package/src/core/reconcile.ts +32 -4
- package/src/core/reinstall.ts +8 -2
- package/src/core/restore.ts +32 -7
- package/src/core/section-sanitize.ts +37 -0
- package/src/core/snapshot-diff.test.ts +73 -1
- package/src/core/snapshot-diff.ts +66 -21
- package/src/core/startup-barrier.test.ts +64 -0
- package/src/core/startup-barrier.ts +8 -2
- package/src/core/types.ts +27 -1
- package/src/core/update-check.test.ts +40 -0
- package/src/core/update-check.ts +53 -2
- package/src/foreign/claude-code.test.ts +5 -0
- package/src/foreign/claude-plugins.test.ts +57 -0
- package/src/foreign/claude-sessions-bytes.test.ts +7 -1
- package/src/foreign/dsh.test.ts +23 -0
- package/src/foreign/kernel.ts +9 -2
- package/src/foreign/read-claude-plugins.ts +32 -11
- package/src/foreign/read-dsh.ts +33 -2
- package/src/foreign/session-ir.test.ts +67 -0
- package/src/foreign/session-ir.ts +54 -14
- package/src/foreign/session-read.ts +23 -0
- package/src/index.ts +1 -1
- package/src/profiles/dsh-profile-copy-rollback.test.ts +58 -4
- package/src/profiles/dsh-profile-io.ts +29 -0
- package/src/profiles/dsh-profile-manager.test.ts +30 -0
- package/src/profiles/dsh-profile-manager.ts +53 -5
- package/src/profiles/dsh-profile-runtime.test.ts +29 -7
- package/src/profiles/dsh-profile-runtime.ts +17 -3
- package/src/profiles/process-control.test.ts +97 -0
- package/src/profiles/process-control.ts +28 -1
- package/src/routes/profiles.ts +2 -1
- package/src/routes/sync.ts +13 -1
- package/src/schema/types.ts +16 -1
- package/src/security/redaction.test.ts +31 -0
- package/src/security/redaction.ts +23 -6
- package/src/sync/autosync-repeat.test.ts +58 -0
- package/src/sync/autosync-repeat.ts +55 -0
- package/src/sync/autosync-scheduler.test.ts +417 -0
- package/src/sync/autosync-scheduler.ts +154 -41
- package/src/sync/baseline-heal.ts +6 -0
- package/src/sync/baseline-record.ts +135 -0
- package/src/sync/blob-store.test.ts +16 -0
- package/src/sync/blob-store.ts +13 -0
- package/src/sync/content-diff.test.ts +95 -0
- package/src/sync/content-diff.ts +79 -0
- package/src/sync/git/git-transport.test.ts +151 -4
- package/src/sync/git/git-transport.ts +143 -27
- package/src/sync/github-auth.test.ts +26 -1
- package/src/sync/github-auth.ts +37 -1
- package/src/sync/merge-apply-plan.ts +117 -0
- package/src/sync/messages.ts +2 -0
- package/src/sync/pending-merge.ts +77 -0
- package/src/sync/s3/s3-delete-and-blob-index.test.ts +249 -0
- package/src/sync/s3/s3-transport.ts +76 -42
- package/src/sync/sync-config.test.ts +39 -12
- package/src/sync/sync-device-identity.test.ts +3 -0
- package/src/sync/sync-engine.test.ts +465 -12
- package/src/sync/sync-engine.ts +130 -135
- package/src/sync/sync-history.ts +7 -0
- package/src/sync/sync-state.ts +48 -0
- package/src/sync/transport.test.ts +13 -1
- package/src/sync/transport.ts +12 -4
- package/src/sync/webdav/webdav-delete-and-blob-index.test.ts +249 -0
- package/src/sync/webdav/webdav-transport.ts +86 -34
- package/src/ui/commands.test.ts +11 -0
- package/src/ui/commands.ts +5 -14
- package/src/ui/dsh-profiles-view.test.ts +16 -0
- package/src/ui/dsh-profiles-view.ts +11 -5
- package/src/ui/i18n.ts +4 -2
- package/src/ui/menu-placement.ts +1 -1
- package/src/ui/migration-consult-view.test.ts +20 -1
- package/src/ui/migration-consult-view.ts +17 -0
- package/src/ui/overview-view.ts +10 -0
- package/src/ui/report.test.ts +25 -1
- package/src/ui/report.ts +15 -4
- package/src/ui/selection-model.test.ts +15 -1
- package/src/ui/selection-model.ts +18 -0
- package/src/utils/js-yaml4.d.ts +35 -0
- package/src/utils/patch-yaml.test.ts +207 -1
- package/src/utils/patch-yaml.ts +98 -2
- package/src/utils/paths.test.ts +14 -1
- package/src/utils/paths.ts +35 -0
- package/src/utils/workdir-lock.test.ts +69 -0
- package/src/utils/workdir-lock.ts +17 -3
- package/lib/ui/path-mapping.d.ts +0 -38
- package/lib/ui/path-mapping.js +0 -75
- package/src/client/common/InfoHint.tsx +0 -289
- package/src/client/common/info-hint-guard.test.ts +0 -1119
- package/src/client/sync/DecryptPasswordCard.tsx +0 -48
- package/src/client/sync/SecurityOptionsCard.tsx +0 -97
- package/src/client/sync/SyncSectionPickerDialog.tsx +0 -213
- package/src/ui/path-mapping.test.ts +0 -67
- package/src/ui/path-mapping.ts +0 -103
package/src/foreign/read-dsh.ts
CHANGED
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
* detail = too-large / max-logs-reached / session-byte-budget),绝不静默截断。
|
|
23
23
|
*/
|
|
24
24
|
import { envValue, joinFor, normalizePlatform } from './platform-paths.ts';
|
|
25
|
-
import { listDirNames, listFileNames, readBytesSafe, statOrNull } from './session-read.ts';
|
|
25
|
+
import { listDirNames, listFileNames, readBytesPrefixSafe, readBytesSafe, statOrNull } from './session-read.ts';
|
|
26
26
|
import { readLogHeaderFromBytes } from '../utils/session-log.ts';
|
|
27
27
|
import type { SessionLogHeader } from '../utils/session-log.ts';
|
|
28
28
|
import type { RootProbeOptions, SessionReadOutcome } from './session-source.ts';
|
|
@@ -38,6 +38,13 @@ export type DshGeneration = 'v3' | 'v4';
|
|
|
38
38
|
const DEFAULT_MAX_LOGS = 2000;
|
|
39
39
|
const DEFAULT_MAX_FILE_BYTES = 32 * 1024 * 1024;
|
|
40
40
|
const DEFAULT_MAX_TOTAL_BYTES = 256 * 1024 * 1024;
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* 代次嗅探窗口(审计 P7-7):header 是第一行 JSON,64 KiB 覆盖任何真实 cwd/标题组合
|
|
44
|
+
* (首行实测 < 1 KiB)。窗口内解析不出 header 时退回整读,因此这个值只影响「能不能提前
|
|
45
|
+
* 跳过非目标代次」,不会改变任何判定结果。
|
|
46
|
+
*/
|
|
47
|
+
const HEADER_SNIFF_BYTES = 64 * 1024;
|
|
41
48
|
const HEADER_WINDOW_BYTES = 64 * 1024;
|
|
42
49
|
|
|
43
50
|
export interface DshResolvedHome { readonly home: string; readonly overridden: boolean }
|
|
@@ -158,6 +165,23 @@ export async function readDshLogs(opts: DshReadOptions): Promise<SessionReadOutc
|
|
|
158
165
|
scanned += 1;
|
|
159
166
|
if (st.size > maxFileBytes) { truncated = truncated ?? 'too-large'; continue; }
|
|
160
167
|
if (bytesRead + st.size > maxTotalBytes) { truncated = 'byte-budget'; break outer; }
|
|
168
|
+
/**
|
|
169
|
+
* 代次嗅探(审计 P7-7):日志的 header 就在第一行,而 dsh 与 dsh4 两代并存的机器上
|
|
170
|
+
* 一半文件属于「非目标代次」——旧实现为了看那 1 KB header 把 31 MiB 的日志整份读进来
|
|
171
|
+
* 再丢掉。现在先只读头部窗口,判定为别的代次就直接 countedContinue,一次整读都不做。
|
|
172
|
+
*
|
|
173
|
+
* 退化路径保持旧行为:头部窗口解析不出 header(首行比窗口还长 / 读不出)时仍整读一次,
|
|
174
|
+
* 让 log-header-unreadable / log-read-error 这些既有码的触发条件逐字不变。
|
|
175
|
+
*/
|
|
176
|
+
const head = await readBytesPrefixSafe(abs, HEADER_SNIFF_BYTES);
|
|
177
|
+
if (head !== null) {
|
|
178
|
+
const sniffed = dshHeaderOfLogBytes(head);
|
|
179
|
+
const sniffedGeneration = sniffed === undefined ? undefined : dshGenerationOfVersion(sniffed.version);
|
|
180
|
+
if (sniffedGeneration !== undefined && sniffedGeneration !== opts.generation) {
|
|
181
|
+
otherGeneration += 1;
|
|
182
|
+
continue;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
161
185
|
const data = await readBytesSafe(abs, maxFileBytes);
|
|
162
186
|
if (data === null) {
|
|
163
187
|
findings.push({ code: 'source-unreadable', origin: name, detail: 'log-read-error' });
|
|
@@ -178,7 +202,14 @@ export async function readDshLogs(opts: DshReadOptions): Promise<SessionReadOutc
|
|
|
178
202
|
findings.push({ code: 'source-unreadable', origin: name, detail: 'log-header-incomplete' });
|
|
179
203
|
continue;
|
|
180
204
|
}
|
|
181
|
-
if (seen.has(header.id))
|
|
205
|
+
if (seen.has(header.id)) {
|
|
206
|
+
/**
|
|
207
|
+
* 同一 id 出现在两个会话目录(复制/迁移残留):只保留第一个,但**必须留码** ——
|
|
208
|
+
* 静默丢会让「导入少了一条会话」在计划里无从解释(本文件顶部第 21-22 行的硬约束)。
|
|
209
|
+
*/
|
|
210
|
+
findings.push({ code: 'session-id-conflict', origin: header.id, detail: 'duplicate-session-id' });
|
|
211
|
+
continue;
|
|
212
|
+
}
|
|
182
213
|
seen.add(header.id);
|
|
183
214
|
bytesRead += data.length;
|
|
184
215
|
files.push({ id: header.id, cwd: header.cwd, version: header.version, name, data });
|
|
@@ -252,3 +252,70 @@ test('未闭合工具调用:不伪造 result、callId 非空、后续事件与
|
|
|
252
252
|
assert.equal(rows.filter((r) => r.type === 'user/message').length, 2, '中断之后的消息不得被吞掉');
|
|
253
253
|
assert.equal(rows[rows.length - 1]?.type, 'user/message');
|
|
254
254
|
});
|
|
255
|
+
|
|
256
|
+
/* ---------------- 工具结果的三种「静默丢失」路径(2026-11-14 审计 P7-1/2/4/5) ---------------- */
|
|
257
|
+
|
|
258
|
+
function synthOf(messages: readonly IrMessage[]): { rows: DshSessionRow[]; stats: SynthesisStats } {
|
|
259
|
+
const s = stats();
|
|
260
|
+
const rows = synthesizeDshRows(
|
|
261
|
+
{ id: 's9', cwd: 'D:/proj', createdAt: NOW, records: messages.length, messages },
|
|
262
|
+
{ title: '', titleSource: { kind: 'fallback' }, emptyBlocks: [], provider: 'claude-code', reasoningEffort: 'medium', maxTokens: 8192 },
|
|
263
|
+
s,
|
|
264
|
+
NOW,
|
|
265
|
+
);
|
|
266
|
+
return { rows, stats: s };
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** P7-1:同一条 user 记录既含 tool_result 又含 text —— 文本必须另发一条 user/message,不能消失且不能无计数。 */
|
|
270
|
+
test('user 记录同时含 tool_result 与 text:文本作为独立 user/message 发出', () => {
|
|
271
|
+
const { rows, stats: s } = synthOf([
|
|
272
|
+
irMessage(irFallbackMessageId(0), 'user', [irTextBlock('开始')], { time: NOW }),
|
|
273
|
+
irMessage(irFallbackMessageId(1), 'assistant', [irToolCallBlock('t1', 'terminal', { command: 'ls' })], { time: NOW + 1 }),
|
|
274
|
+
irMessage(irFallbackMessageId(2), 'user', [irToolResultBlock('t1', 'ok', false), irTextBlock('MARKER-TEXT')], { time: NOW + 2 }),
|
|
275
|
+
]);
|
|
276
|
+
const humanTexts = rows
|
|
277
|
+
.filter((r) => r.type === 'user/message')
|
|
278
|
+
.map((r) => (r.data as { source: { kind: string }; content: { text?: string }[] }));
|
|
279
|
+
const fromUser = humanTexts.filter((m) => m.source.kind === 'user').flatMap((m) => m.content.map((c) => c.text ?? ''));
|
|
280
|
+
assert.ok(fromUser.join('|').includes('MARKER-TEXT'), '用户文本被静默吞掉了:' + JSON.stringify(rows.map((r) => r.type)));
|
|
281
|
+
assert.equal(s.userMessages, 2, '结果块之后的文本也要计入 userMessages');
|
|
282
|
+
assert.equal(s.toolResults, 1, '同一条记录里的 tool/result 仍必须发出');
|
|
283
|
+
assert.equal(rows.filter((r) => r.type === 'tool/result').length, 1);
|
|
284
|
+
});
|
|
285
|
+
|
|
286
|
+
/** P7-4:非空 id 但不在未决表里 = 悬空引用,必须计数丢弃(不得发指向不存在调用的结果)。 */
|
|
287
|
+
test('tool_result 带未知 id:按 orphan-tool-result 计数,不产出悬空 callId', () => {
|
|
288
|
+
const { rows, stats: s } = synthOf([
|
|
289
|
+
irMessage(irFallbackMessageId(0), 'user', [irTextBlock('开始')], { time: NOW }),
|
|
290
|
+
irMessage(irFallbackMessageId(1), 'assistant', [irToolCallBlock('t1', 'terminal', { command: 'ls' })], { time: NOW + 1 }),
|
|
291
|
+
irMessage(irFallbackMessageId(2), 'user', [irToolResultBlock('t1', 'ok', false), irToolResultBlock('t-unknown', 'x', false)], { time: NOW + 2 }),
|
|
292
|
+
]);
|
|
293
|
+
const results = rows.filter((r) => r.type === 'tool/result');
|
|
294
|
+
assert.deepEqual(results.map((r) => (r.data as { message: { source: { callId: string } } }).message.source.callId), ['t1']);
|
|
295
|
+
assert.equal(s.ignored['orphan-tool-result'], 1, '悬空 id 必须可见地计数');
|
|
296
|
+
});
|
|
297
|
+
|
|
298
|
+
/** P7-2:缺 id 的结果不得回填到**上一个回合**已闭合的调用上(openCallIds 必须按回合清空)。 */
|
|
299
|
+
test('回合闭合后缺 id 的 tool_result 不回填上一回合的调用', () => {
|
|
300
|
+
const { rows } = synthOf([
|
|
301
|
+
irMessage(irFallbackMessageId(0), 'user', [irTextBlock('turn1')], { time: NOW }),
|
|
302
|
+
irMessage(irFallbackMessageId(1), 'assistant', [irToolCallBlock('turn1-call', 'terminal', { command: 'a' })], { time: NOW + 1 }),
|
|
303
|
+
irMessage(irFallbackMessageId(2), 'user', [irTextBlock('turn2')], { time: NOW + 2 }),
|
|
304
|
+
irMessage(irFallbackMessageId(3), 'assistant', [irToolCallBlock('turn2-call', 'terminal', { command: 'b' })], { time: NOW + 3 }),
|
|
305
|
+
irMessage(irFallbackMessageId(4), 'user', [irToolResultBlock('', 'late', false)], { time: NOW + 4 }),
|
|
306
|
+
]);
|
|
307
|
+
const result = rows.find((r) => r.type === 'tool/result');
|
|
308
|
+
const callId = (result?.data as { message: { source: { callId: string } } } | undefined)?.message.source.callId;
|
|
309
|
+
assert.equal(callId, 'turn2-call', '缺 id 的结果只能配对当前回合仍未结算的调用,不能跨回合回填');
|
|
310
|
+
});
|
|
311
|
+
|
|
312
|
+
/** P7-5:assistant 记录里携带的 tool_result 无处归位 —— 必须计数(绝不静默丢弃)。 */
|
|
313
|
+
test('assistant 记录携带 tool_result:按 assistant-tool-result 计数', () => {
|
|
314
|
+
const { rows, stats: s } = synthOf([
|
|
315
|
+
irMessage(irFallbackMessageId(0), 'user', [irTextBlock('开始')], { time: NOW }),
|
|
316
|
+
irMessage(irFallbackMessageId(1), 'assistant', [irToolCallBlock('t1', 'terminal', { command: 'ls' }), irToolResultBlock('t1', 'ok', false)], { time: NOW + 1 }),
|
|
317
|
+
]);
|
|
318
|
+
assert.equal(s.ignored['assistant-tool-result'], 1, '助手记录里的结果块不得无声消失');
|
|
319
|
+
assert.equal(s.toolResults, 0);
|
|
320
|
+
assert.equal(rows.filter((r) => r.type === 'tool/result').length, 0);
|
|
321
|
+
});
|
|
@@ -330,6 +330,12 @@ export function synthesizeDshRows(
|
|
|
330
330
|
};
|
|
331
331
|
const closeTurn = (): void => {
|
|
332
332
|
closeStep();
|
|
333
|
+
/**
|
|
334
|
+
* 回合闭合后再到的结果**不许**回填到本回合的调用上:`openCallIds` 是跨 step 共享的 FIFO,
|
|
335
|
+
* 若不在回合边界清空,下一回合缺 id 的 tool_result 会消费到上一回合已结束的 callId
|
|
336
|
+
* (结果落在 turn N+1、却引用 turn N 的调用,DSH 侧配对不上)。
|
|
337
|
+
*/
|
|
338
|
+
openCallIds.length = 0;
|
|
333
339
|
if (turnOpen) {
|
|
334
340
|
push('turn/end', now, { turn, reason: { kind: 'completed' } });
|
|
335
341
|
turnOpen = false;
|
|
@@ -344,6 +350,21 @@ export function synthesizeDshRows(
|
|
|
344
350
|
});
|
|
345
351
|
turnOpen = true;
|
|
346
352
|
};
|
|
353
|
+
/** 发一条**人类** user/message(唯一形状出口:两条路径共用,避免字段漂移) */
|
|
354
|
+
const emitUserMessage = (text: string, at: number, id: string): void => {
|
|
355
|
+
push(
|
|
356
|
+
'user/message',
|
|
357
|
+
at,
|
|
358
|
+
{
|
|
359
|
+
content: [irTextBlock(text)],
|
|
360
|
+
source: { kind: 'user' },
|
|
361
|
+
role: 'user',
|
|
362
|
+
id,
|
|
363
|
+
},
|
|
364
|
+
'append',
|
|
365
|
+
);
|
|
366
|
+
stats.userMessages++;
|
|
367
|
+
};
|
|
347
368
|
|
|
348
369
|
for (const message of session.messages) {
|
|
349
370
|
// time 缺省(源没给可解析时间)→ 用调用方的时间兜底;安全整数校验在 IR 层已完成
|
|
@@ -354,6 +375,15 @@ export function synthesizeDshRows(
|
|
|
354
375
|
if (message.role === 'assistant') {
|
|
355
376
|
const text = irTextOfBlocks(blocks);
|
|
356
377
|
const calls = blocks.filter((b): b is IrToolCallBlock => b.type === 'tool_call');
|
|
378
|
+
/**
|
|
379
|
+
* 助手记录里携带的 tool_result:本分支只消费 text/tool_call,这类结果**无处归位**
|
|
380
|
+
* (opencode 等来源把 call 与 result 写进同一条记录,由 `splitToolResults` 先拆开;
|
|
381
|
+
* 没拆到这里的不能静默消失)。计数后丢弃 —— 绝不产出悬空引用,也绝不无声丢内容。
|
|
382
|
+
*/
|
|
383
|
+
const assistantResults = blocks.filter((b): b is IrToolResultBlock => b.type === 'tool_result');
|
|
384
|
+
if (assistantResults.length > 0) {
|
|
385
|
+
irBump(stats.ignored, 'assistant-tool-result', assistantResults.length);
|
|
386
|
+
}
|
|
357
387
|
const source = message.passthrough?.['source'];
|
|
358
388
|
const m = irStr((source as Record<string, unknown> | undefined)?.['model']);
|
|
359
389
|
if (m !== undefined) model = m;
|
|
@@ -361,7 +391,8 @@ export function synthesizeDshRows(
|
|
|
361
391
|
const providerName = hints.provider === '' ? 'foreign' : hints.provider;
|
|
362
392
|
const modelName = model === '' ? 'unknown' : model;
|
|
363
393
|
if (text.trim() === '' && calls.length === 0) {
|
|
364
|
-
|
|
394
|
+
// 只有 tool_result 的助手记录已按 assistant-tool-result 计数,不再重复记 assistant-empty
|
|
395
|
+
if (assistantResults.length === 0) irBump(stats.ignored, 'assistant-empty');
|
|
365
396
|
continue;
|
|
366
397
|
}
|
|
367
398
|
if (!turnOpen) openTurn(at);
|
|
@@ -468,7 +499,17 @@ export function synthesizeDshRows(
|
|
|
468
499
|
callId = next === undefined ? '' : next;
|
|
469
500
|
} else {
|
|
470
501
|
const idx = openCallIds.indexOf(callId);
|
|
471
|
-
if (idx >= 0)
|
|
502
|
+
if (idx >= 0) {
|
|
503
|
+
openCallIds.splice(idx, 1);
|
|
504
|
+
} else {
|
|
505
|
+
/**
|
|
506
|
+
* 非空 id 但不在未决表里 = 悬空引用(调用已在上一回合闭合,或源侧 id 与真正发出的
|
|
507
|
+
* callId 不同)。与「缺 id 且无未决调用」同口径:计数后丢弃,绝不发指向不存在
|
|
508
|
+
* tool/call 的结果(DSH 侧会按损坏流拒读整条会话)。
|
|
509
|
+
*/
|
|
510
|
+
irBump(stats.ignored, 'orphan-tool-result');
|
|
511
|
+
continue;
|
|
512
|
+
}
|
|
472
513
|
}
|
|
473
514
|
if (callId === '') {
|
|
474
515
|
irBump(stats.ignored, 'orphan-tool-result');
|
|
@@ -498,6 +539,16 @@ export function synthesizeDshRows(
|
|
|
498
539
|
'append',
|
|
499
540
|
);
|
|
500
541
|
}
|
|
542
|
+
/**
|
|
543
|
+
* 同一条 user 记录里既有 tool_result 又有 text(Anthropic 形状里很常见:结果块后跟人类补充):
|
|
544
|
+
* 结果先收进当前 step,文本必须**再发一条真正的 user/message** —— 否则这段用户输入
|
|
545
|
+
* 既到不了目标机、也不进 ignored,属于静默丢失。
|
|
546
|
+
*/
|
|
547
|
+
const trailing = irTextOfBlocks(blocks);
|
|
548
|
+
if (trailing.trim() !== '') {
|
|
549
|
+
closeTurn();
|
|
550
|
+
emitUserMessage(trailing, at, message.id);
|
|
551
|
+
}
|
|
501
552
|
messageIndex++;
|
|
502
553
|
continue;
|
|
503
554
|
}
|
|
@@ -509,18 +560,7 @@ export function synthesizeDshRows(
|
|
|
509
560
|
continue;
|
|
510
561
|
}
|
|
511
562
|
closeTurn();
|
|
512
|
-
|
|
513
|
-
'user/message',
|
|
514
|
-
at,
|
|
515
|
-
{
|
|
516
|
-
content: [irTextBlock(text)],
|
|
517
|
-
source: { kind: 'user' },
|
|
518
|
-
role: 'user',
|
|
519
|
-
id: message.id,
|
|
520
|
-
},
|
|
521
|
-
'append',
|
|
522
|
-
);
|
|
523
|
-
stats.userMessages++;
|
|
563
|
+
emitUserMessage(text, at, message.id);
|
|
524
564
|
messageIndex++;
|
|
525
565
|
}
|
|
526
566
|
closeTurn();
|
|
@@ -65,6 +65,29 @@ export async function readBytesSafe(p: string, maxBytes: number = DEFAULT_MAX_FI
|
|
|
65
65
|
}
|
|
66
66
|
}
|
|
67
67
|
|
|
68
|
+
/**
|
|
69
|
+
* 只读文件**头部窗口**(审计 P7-7):给「先看 header 再决定要不要整读」的场景用。
|
|
70
|
+
*
|
|
71
|
+
* 与 readBytesSafe 的区别只有一点:不超过 maxBytes 时只取前 maxBytes 字节,而不是整份读。
|
|
72
|
+
* 语义仍守四条硬边界(读不到返回 null、绝不抛、超上限不读)。调用方必须自己处理
|
|
73
|
+
* 「头部窗口不足以判定」的退化路径 —— 不要把它当成整份内容。
|
|
74
|
+
*/
|
|
75
|
+
export async function readBytesPrefixSafe(p: string, maxBytes: number): Promise<Uint8Array | null> {
|
|
76
|
+
const st = await statOrNull(p);
|
|
77
|
+
if (st === null || !st.isFile() || maxBytes <= 0) return null;
|
|
78
|
+
let handle: fs.FileHandle | null = null;
|
|
79
|
+
try {
|
|
80
|
+
handle = await fs.open(p, 'r');
|
|
81
|
+
const buf = new Uint8Array(Math.min(maxBytes, st.size));
|
|
82
|
+
const { bytesRead } = await handle.read(buf, 0, buf.byteLength, 0);
|
|
83
|
+
return bytesRead === buf.byteLength ? buf : buf.subarray(0, bytesRead);
|
|
84
|
+
} catch {
|
|
85
|
+
return null;
|
|
86
|
+
} finally {
|
|
87
|
+
if (handle !== null) await handle.close().catch(() => undefined);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
68
91
|
export async function readTextSafe(p: string, maxBytes: number = DEFAULT_MAX_FILE_BYTES): Promise<string | null> {
|
|
69
92
|
const st = await statOrNull(p);
|
|
70
93
|
if (st === null || !st.isFile() || st.size > maxBytes) return null;
|
package/src/index.ts
CHANGED
|
@@ -184,7 +184,7 @@ export const name = 'config-manager'
|
|
|
184
184
|
export const inject = ['settings', 'credentials']
|
|
185
185
|
|
|
186
186
|
/** Plugin version, kept in sync with package.json ("version"). */
|
|
187
|
-
export const PLUGIN_VERSION = '0.
|
|
187
|
+
export const PLUGIN_VERSION = '0.9.0'
|
|
188
188
|
|
|
189
189
|
/** Plugin own package name — excluded from its own exported plugins list. */
|
|
190
190
|
const PLUGIN_NAME = 'dsh-config-manager'
|
|
@@ -14,12 +14,14 @@
|
|
|
14
14
|
*/
|
|
15
15
|
import test from 'node:test'
|
|
16
16
|
import assert from 'node:assert/strict'
|
|
17
|
-
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
|
17
|
+
import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs'
|
|
18
18
|
import { join } from 'node:path'
|
|
19
19
|
import { tmpdir } from 'node:os'
|
|
20
20
|
|
|
21
|
-
import { DshProfileManager, rollbackCopiedProfileDir } from './dsh-profile-manager.ts'
|
|
21
|
+
import { DshProfileError, DshProfileManager, rollbackCopiedProfileDir } from './dsh-profile-manager.ts'
|
|
22
|
+
import type { DshProfileManagerOptions } from './dsh-profile-manager.ts'
|
|
22
23
|
import type { DshProfileCopyMarker } from './dsh-profile-shared.ts'
|
|
24
|
+
import type { AtomicIoSync } from '../utils/atomic-write.ts'
|
|
23
25
|
|
|
24
26
|
/** 磁盘契约字面量:改名即等于把旧版本留下的残留重新变成「查不到」(与 dsh-profile-incomplete-copy.test.ts 同口径)。 */
|
|
25
27
|
const MARKER = '.dcm-copy-in-progress.json'
|
|
@@ -33,14 +35,40 @@ const MARKER_OBJ: DshProfileCopyMarker = {
|
|
|
33
35
|
pid: 4242,
|
|
34
36
|
}
|
|
35
37
|
|
|
36
|
-
function makeManager(): { mgr: DshProfileManager; home: string; cleanup: () => void } {
|
|
38
|
+
function makeManager(extra: Partial<DshProfileManagerOptions> = {}): { mgr: DshProfileManager; home: string; cleanup: () => void } {
|
|
37
39
|
const root = mkdtempSync(join(tmpdir(), 'dsh-copy-rollback-'))
|
|
38
40
|
const home = join(root, 'home')
|
|
39
41
|
mkdirSync(join(home, 'profiles'), { recursive: true })
|
|
40
|
-
const mgr = new DshProfileManager({ homeDir: home, currentProfile: () => 'web' })
|
|
42
|
+
const mgr = new DshProfileManager({ homeDir: home, currentProfile: () => 'web', ...extra })
|
|
41
43
|
return { mgr, home, cleanup: () => { rmSync(root, { recursive: true, force: true }) } }
|
|
42
44
|
}
|
|
43
45
|
|
|
46
|
+
/**
|
|
47
|
+
* 只让「标记那一次写入」失败:除 open(atomicWriteFileSync 唯一会真的动盘前的最后一步)之外
|
|
48
|
+
* 全部转发真实 fs。用它复现「目录已建好、标记却写不出来」这条窄缝。
|
|
49
|
+
*/
|
|
50
|
+
function failingMarkerIo(): AtomicIoSync {
|
|
51
|
+
return {
|
|
52
|
+
mkdir: (dir, opts) => { mkdirSync(dir, { recursive: opts.recursive }) },
|
|
53
|
+
lstat: (target) => {
|
|
54
|
+
try {
|
|
55
|
+
const stat = lstatSync(target)
|
|
56
|
+
return { isSymbolicLink: () => stat.isSymbolicLink(), mode: stat.mode }
|
|
57
|
+
} catch {
|
|
58
|
+
return null
|
|
59
|
+
}
|
|
60
|
+
},
|
|
61
|
+
realpath: (target) => realpathSync(target),
|
|
62
|
+
open: () => { throw new Error('EIO: simulated copy-marker write failure') },
|
|
63
|
+
writeFd: () => {},
|
|
64
|
+
fsyncFd: () => {},
|
|
65
|
+
closeFd: () => {},
|
|
66
|
+
rename: (from, to) => { renameSync(from, to) },
|
|
67
|
+
unlink: (target) => { rmSync(target, { force: true }) },
|
|
68
|
+
fsyncDir: () => {},
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
44
72
|
/** 造一个「复制中途失败」的目标目录:部分内容 + 标记,**没有 package.json**。 */
|
|
45
73
|
function writeHalfCopy(home: string, name = 'work-copy'): string {
|
|
46
74
|
const dir = join(home, 'profiles', name)
|
|
@@ -154,3 +182,29 @@ test('#5-D:copy() 失败路径确实走回滚(整体接线)—— 目标
|
|
|
154
182
|
cleanup()
|
|
155
183
|
}
|
|
156
184
|
})
|
|
185
|
+
|
|
186
|
+
test('#5-E:标记写不出来 ⇒ 连目标目录一起回滚,绝不留「list() 看不到、remove() 报 notFound」的空壳', async () => {
|
|
187
|
+
const { mgr, home, cleanup } = makeManager({ markerIo: failingMarkerIo() })
|
|
188
|
+
try {
|
|
189
|
+
const src = join(home, 'profiles', 'work')
|
|
190
|
+
mkdirSync(src, { recursive: true })
|
|
191
|
+
writeFileSync(join(src, 'package.json'), JSON.stringify({ name: 'dsh-profile-work', dependencies: {} }), 'utf8')
|
|
192
|
+
|
|
193
|
+
const dest = join(home, 'profiles', 'work-copy')
|
|
194
|
+
await assert.rejects(
|
|
195
|
+
mgr.copy('work', 'work-copy'),
|
|
196
|
+
(err: unknown) => err instanceof DshProfileError && err.code === 'copyFailed',
|
|
197
|
+
'标记写失败也是复制失败:必须走统一错误码,不得把底层 fs 错误原样抛给调用方',
|
|
198
|
+
)
|
|
199
|
+
|
|
200
|
+
// 三个视角同时成立,才算没有孤儿:
|
|
201
|
+
// ① 盘上没有那个目录(旧实现会留下一个空目录)
|
|
202
|
+
assert.equal(existsSync(dest), false, '标记写失败必须连目录一起清掉')
|
|
203
|
+
// ② 档案列表里没有它
|
|
204
|
+
assert.deepEqual(mgr.list().map((meta) => meta.name), ['work'], '列表里只有源档案')
|
|
205
|
+
// ③ 残留列举里也没有它(残留应该是「有标记的半截副本」,而不是空壳)
|
|
206
|
+
assert.deepEqual(mgr.listIncompleteCopies(), [])
|
|
207
|
+
} finally {
|
|
208
|
+
cleanup()
|
|
209
|
+
}
|
|
210
|
+
})
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
* `sanitizeFilePart`(同一正则)。
|
|
12
12
|
*/
|
|
13
13
|
import { readFileSync } from 'node:fs'
|
|
14
|
+
import { createHash } from 'node:crypto'
|
|
14
15
|
|
|
15
16
|
/**
|
|
16
17
|
* 读文本文件;不可读返回 **null** —— 语义差异由调用方显式表达(**不得把 null 统一成 ''**):
|
|
@@ -29,3 +30,31 @@ export function readTextSafe(path: string): string | null {
|
|
|
29
30
|
export function sanitizeFilePart(name: string): string {
|
|
30
31
|
return name.replace(/[^A-Za-z0-9._-]/g, '_')
|
|
31
32
|
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* 运行心跳文件名(**唯一实现**)—— 可读前缀 + 名字哈希。
|
|
36
|
+
*
|
|
37
|
+
* 为什么必须带哈希(审计 P11-2 P1,2026-11-13 实测):心跳文件此前叫
|
|
38
|
+
* `<sanitizeFilePart(name)>.json`,而清洗是**多对一**的 —— `web` 与 `web!` 都落到
|
|
39
|
+
* `web.json`,于是两个实例共享同一个心跳文件:后写的覆盖先写的,`listActive()` 只看得到
|
|
40
|
+
* 一个,`stopExternal` 可能停错人,`withdraw()` 也会删掉别人的心跳(对方从此「不可见」,
|
|
41
|
+
* 界面上又能被重复启动 —— 正是这套机制要防的事)。
|
|
42
|
+
*
|
|
43
|
+
* 判据:清洗只用于可读性(截断到 48 字符、去掉结尾的点/空格,Windows 会吃掉结尾点),
|
|
44
|
+
* **唯一性由 sha256(原名) 的前 12 hex 保证**;\0 之类不可达字符也天然被哈希区隔。
|
|
45
|
+
*/
|
|
46
|
+
export function runtimeFileName(name: string): string {
|
|
47
|
+
const readable = sanitizeFilePart(name).replace(/[. ]+$/, '').slice(0, 48)
|
|
48
|
+
const digest = createHash('sha256').update(name, 'utf8').digest('hex').slice(0, 12)
|
|
49
|
+
return readable === '' ? `${digest}.json` : `${readable}-${digest}.json`
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* 旧版心跳文件名(升级清理专用):`<sanitizeFilePart(name)>.json`。
|
|
54
|
+
*
|
|
55
|
+
* 只用于「自报/自撤时顺手删掉自己那份旧文件」—— 否则升级后同一个 profile 会留下两份心跳,
|
|
56
|
+
* `listActive` 对同名记录会看到两条。绝不用于读别人的记录。
|
|
57
|
+
*/
|
|
58
|
+
export function legacyRuntimeFileName(name: string): string {
|
|
59
|
+
return `${sanitizeFilePart(name)}.json`
|
|
60
|
+
}
|
|
@@ -349,6 +349,36 @@ test('remove:物理删除目录;当前 profile 需显式确认', () => {
|
|
|
349
349
|
}
|
|
350
350
|
})
|
|
351
351
|
|
|
352
|
+
test('removeAsync(审计 P11-9):同一套护栏 + 删除期间事件循环不被独占', async () => {
|
|
353
|
+
const { mgr, home, cleanup } = makeManager()
|
|
354
|
+
try {
|
|
355
|
+
mgr.create('work', 'base')
|
|
356
|
+
const dir = join(home, 'profiles', 'work')
|
|
357
|
+
mkdirSync(join(dir, 'node_modules', 'pkg'), { recursive: true })
|
|
358
|
+
for (let i = 0; i < 400; i += 1) writeFileSync(join(dir, 'node_modules', 'pkg', `f-${i}.js`), 'x')
|
|
359
|
+
|
|
360
|
+
// 删除期间每 5 ms 一次的心跳(真机对应宿主里的定时探测):同步实现期间一次都不会触发
|
|
361
|
+
let ticks = 0
|
|
362
|
+
const timer = setInterval(() => { ticks += 1 }, 5)
|
|
363
|
+
try {
|
|
364
|
+
await mgr.removeAsync('work')
|
|
365
|
+
} finally {
|
|
366
|
+
clearInterval(timer)
|
|
367
|
+
}
|
|
368
|
+
assert.equal(existsSync(dir), false, '目录必须真的删净')
|
|
369
|
+
assert.ok(ticks > 0, `异步删除期间事件循环必须能跑定时器,实际 ticks=${ticks}`)
|
|
370
|
+
|
|
371
|
+
// 护栏与同步版一致
|
|
372
|
+
mgr.create('live', 'web')
|
|
373
|
+
const current = new DshProfileManager({ homeDir: home, currentProfile: () => 'live' })
|
|
374
|
+
await assert.rejects(() => current.removeAsync('live'), (e: unknown) => e instanceof DshProfileError && e.code === 'currentProfile')
|
|
375
|
+
await assert.rejects(() => mgr.removeAsync('desktop'), (e: unknown) => e instanceof DshProfileError && e.code === 'managedProfile')
|
|
376
|
+
await assert.rejects(() => mgr.removeAsync('gone'), (e: unknown) => e instanceof DshProfileError && e.code === 'notFound')
|
|
377
|
+
} finally {
|
|
378
|
+
cleanup()
|
|
379
|
+
}
|
|
380
|
+
})
|
|
381
|
+
|
|
352
382
|
test('remove:含悬空 junction 的档案也能删净(fs.rm 静默失效的回归)', () => {
|
|
353
383
|
const { mgr, home, cleanup } = makeManager()
|
|
354
384
|
try {
|
|
@@ -27,7 +27,7 @@ import { existsSync, mkdirSync, readdirSync, renameSync, rmSync, statSync, type
|
|
|
27
27
|
// 复制走 async fs(整档案上万个文件,cpSync 会把宿主事件循环卡住二十多秒)
|
|
28
28
|
import { copyFile, cp, mkdir, readdir, readlink, stat, symlink, unlink } from 'node:fs/promises'
|
|
29
29
|
import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
|
|
30
|
-
import { atomicWriteFileSync } from '../utils/atomic-write.ts'
|
|
30
|
+
import { atomicWriteFileSync, type AtomicIoSync } from '../utils/atomic-write.ts'
|
|
31
31
|
import { removeTree, removeTreeSync } from '../utils/remove-tree.ts'
|
|
32
32
|
import { isRecord } from '../utils/guards.ts'
|
|
33
33
|
import { resolveProfileDir, validateProfileName } from '../core/plugin-cli.ts'
|
|
@@ -81,6 +81,13 @@ export interface DshProfileManagerOptions {
|
|
|
81
81
|
/** 插件 dataDir(保留给调用方复用;本引擎不再落任何状态) */
|
|
82
82
|
/** 当前运行中的 profile 名(惰性读取,宿主注入) */
|
|
83
83
|
currentProfile?: () => string
|
|
84
|
+
/**
|
|
85
|
+
* 「复制进行中标记」那一次写盘用的可注入同步 io(缺省 undefined = 真实 fs)。
|
|
86
|
+
*
|
|
87
|
+
* 只给单测用:Windows 上造不出「目录建好、标记写不出来」的真实故障(写完立刻腾空间就失败了),
|
|
88
|
+
* 而这条窄缝恰恰会留下既不在 list() 里、remove() 又报 notFound 的空目录。
|
|
89
|
+
*/
|
|
90
|
+
markerIo?: AtomicIoSync
|
|
84
91
|
}
|
|
85
92
|
|
|
86
93
|
/**
|
|
@@ -182,10 +189,13 @@ export async function rollbackCopiedProfileDir(
|
|
|
182
189
|
export class DshProfileManager {
|
|
183
190
|
private readonly homeDir: string
|
|
184
191
|
private readonly currentProfile: () => string
|
|
192
|
+
/** 见 DshProfileManagerOptions.markerIo:只作用于「复制进行中标记」的写入 */
|
|
193
|
+
private readonly markerIo: AtomicIoSync | undefined
|
|
185
194
|
|
|
186
195
|
constructor(options: DshProfileManagerOptions) {
|
|
187
196
|
this.homeDir = options.homeDir
|
|
188
197
|
this.currentProfile = options.currentProfile ?? ((): string => 'web')
|
|
198
|
+
this.markerIo = options.markerIo
|
|
189
199
|
}
|
|
190
200
|
|
|
191
201
|
/** profiles 根目录(`$DSH_HOME/profiles`) */
|
|
@@ -297,9 +307,6 @@ export class DshProfileManager {
|
|
|
297
307
|
if (existsSync(destDir)) throw new DshProfileError('exists')
|
|
298
308
|
const includeNodeModules = opts.includeNodeModules !== false
|
|
299
309
|
const startedAt = Date.now()
|
|
300
|
-
await mkdir(destDir, { recursive: true })
|
|
301
|
-
// cross-F3:**先落标记再拷文件**。进程被强杀时标记留在目标目录里,使这个半截副本可被
|
|
302
|
-
// 档案列表 / 恢复面板辨识并物理删除;不留标记的话它既不在列表里、删除又报 notFound。
|
|
303
310
|
const marker: DshProfileCopyMarker = {
|
|
304
311
|
sourceName: name,
|
|
305
312
|
newName,
|
|
@@ -307,8 +314,13 @@ export class DshProfileManager {
|
|
|
307
314
|
includeNodeModules,
|
|
308
315
|
pid: process.pid,
|
|
309
316
|
}
|
|
310
|
-
|
|
317
|
+
// 建目录与落标记同属一个回滚范围:标记写不出来时这个目录还没有任何可辨认身份,
|
|
318
|
+
// 留在盘上就是「list() 看不到、remove() 报 notFound」的空壳 —— 必须在 catch 里一并清掉。
|
|
311
319
|
try {
|
|
320
|
+
await mkdir(destDir, { recursive: true })
|
|
321
|
+
// cross-F3:**先落标记再拷文件**。进程被强杀时标记留在目标目录里,使这个半截副本可被
|
|
322
|
+
// 档案列表 / 恢复面板辨识并物理删除;不留标记的话它既不在列表里、删除又报 notFound。
|
|
323
|
+
this.writeCopyMarker(destDir, marker)
|
|
312
324
|
const entries = await readdir(srcDir, { withFileTypes: true })
|
|
313
325
|
for (const entry of entries) {
|
|
314
326
|
// node_modules 与 DSH 投影出来的 .dsh-module-fallback 同进同出(后者的链接都指向前者)
|
|
@@ -449,6 +461,30 @@ export class DshProfileManager {
|
|
|
449
461
|
}
|
|
450
462
|
}
|
|
451
463
|
|
|
464
|
+
/**
|
|
465
|
+
* remove() 的异步版本:语义、护栏、错误码完全一致,只是不阻塞事件循环(审计 P11-9)。
|
|
466
|
+
*
|
|
467
|
+
* 为什么需要两份:档案目录是整仓里最大的一棵树(含 node_modules,真机 2 万文件)。实测
|
|
468
|
+
* removeTreeSync 删 2 万文件耗 15.5 s,期间宿主 20 ms 定时器 0/776 次触发 —— 心跳、实例
|
|
469
|
+
* 存活探测、同步定时器全停摆,面板表现成「后端卡死」。HTTP 删除走这里;只有确实同步
|
|
470
|
+
* 上下文(脚本、收尾清理)才用 remove(),且必须是自己知道很小的树。
|
|
471
|
+
*/
|
|
472
|
+
async removeAsync(name: string, opts: { allowCurrent?: boolean } = {}): Promise<void> {
|
|
473
|
+
if (isManagedProfileName(name)) throw new DshProfileError('managedProfile')
|
|
474
|
+
const dir = this.requireManagedDir(name)
|
|
475
|
+
if (name === this.currentProfile() && opts.allowCurrent !== true) {
|
|
476
|
+
throw new DshProfileError('currentProfile')
|
|
477
|
+
}
|
|
478
|
+
try {
|
|
479
|
+
await removeTree(dir)
|
|
480
|
+
} catch (error) {
|
|
481
|
+
throw new DshProfileError('deleteFailed', error instanceof Error ? error.message : String(error))
|
|
482
|
+
}
|
|
483
|
+
if (existsSync(dir)) {
|
|
484
|
+
throw new DshProfileError('deleteFailed', `profile directory still exists after removal: ${dir}`)
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
|
|
452
488
|
/**
|
|
453
489
|
* cross-F3:目标目录 = **正常 profile(有 package.json)** 或 **中断的复制残留(有进行中标记)**;
|
|
454
490
|
* 两者都没有 → notFound。残余标记的目录必须能被定位与删除,否则就是孤儿。
|
|
@@ -465,6 +501,18 @@ export class DshProfileManager {
|
|
|
465
501
|
throw new DshProfileError('notFound')
|
|
466
502
|
}
|
|
467
503
|
|
|
504
|
+
/**
|
|
505
|
+
* 落「复制进行中标记」(cross-F3 的唯一凭据)。
|
|
506
|
+
*
|
|
507
|
+
* 单独抽出来只为把注入点收窄到这一处写入:调用方(copy)据此保证「标记写失败 ⇒ 目录一起回滚」。
|
|
508
|
+
*/
|
|
509
|
+
private writeCopyMarker(dir: string, marker: DshProfileCopyMarker): void {
|
|
510
|
+
atomicWriteFileSync(this.copyMarkerPath(dir), `${JSON.stringify(marker, null, 2)}\n`, {
|
|
511
|
+
mode: 0o644,
|
|
512
|
+
...(this.markerIo === undefined ? {} : { syncIo: this.markerIo }),
|
|
513
|
+
})
|
|
514
|
+
}
|
|
515
|
+
|
|
468
516
|
/** 复制进行中标记的路径。 */
|
|
469
517
|
private copyMarkerPath(dir: string): string {
|
|
470
518
|
return join(dir, PROFILE_COPY_MARKER_FILENAME)
|
|
@@ -16,6 +16,7 @@ import {
|
|
|
16
16
|
parseRuntimeRecord, runtimeRecordLive,
|
|
17
17
|
} from './dsh-profile-runtime.ts'
|
|
18
18
|
import { DshProfileError } from './dsh-profile-manager.ts'
|
|
19
|
+
import { runtimeFileName } from './dsh-profile-io.ts'
|
|
19
20
|
|
|
20
21
|
interface HarnessOptions {
|
|
21
22
|
name?: string
|
|
@@ -75,13 +76,13 @@ test('announce / listActive / withdraw:自报 → 可见 → 自撤', () => {
|
|
|
75
76
|
assert.equal(written.name, 'web')
|
|
76
77
|
assert.equal(written.pid, 111)
|
|
77
78
|
assert.equal(written.port, 3080)
|
|
78
|
-
assert.equal(existsSync(join(h.dir, 'web
|
|
79
|
+
assert.equal(existsSync(join(h.dir, runtimeFileName('web'))), true)
|
|
79
80
|
const active = h.registry.listActive()
|
|
80
81
|
assert.deepEqual(active.map((r) => r.name), ['web'])
|
|
81
82
|
assert.equal(active[0]?.port, 3080)
|
|
82
83
|
h.registry.withdraw()
|
|
83
84
|
assert.deepEqual(h.registry.listActive(), [])
|
|
84
|
-
assert.equal(existsSync(join(h.dir, 'web
|
|
85
|
+
assert.equal(existsSync(join(h.dir, runtimeFileName('web'))), false)
|
|
85
86
|
} finally { h.cleanup() }
|
|
86
87
|
})
|
|
87
88
|
|
|
@@ -118,10 +119,31 @@ test('listActive:死心跳 / 过期心跳 / 坏文件都会被清掉(进程
|
|
|
118
119
|
writeFileSync(join(h.dir, 'stale.json'), JSON.stringify(stale))
|
|
119
120
|
const active = h.registry.listActive()
|
|
120
121
|
assert.deepEqual(active.map((r) => r.name), ['web'], '只留活着的自己')
|
|
121
|
-
assert.deepEqual(readdirSync(h.dir).sort(), ['web
|
|
122
|
+
assert.deepEqual(readdirSync(h.dir).sort(), [runtimeFileName('web')], '死/坏心跳文件已清理')
|
|
122
123
|
} finally { h.cleanup() }
|
|
123
124
|
})
|
|
124
125
|
|
|
126
|
+
test('心跳文件名必须唯一:清洗后同形的两个 profile 不得共用/互删心跳(审计 P11-2 回归)', () => {
|
|
127
|
+
// 旧实现 <sanitizeFilePart(name)>.json:'web' 与 'web!' 都落成 web.json ⇒ 后写的覆盖先写的,
|
|
128
|
+
// listActive 只看得到一个,withdraw 还会删掉别人的心跳(对方从此「不可见」,又能被重复启动)。
|
|
129
|
+
const dir = mkdtempSync(join(tmpdir(), 'dsh-runtime-'))
|
|
130
|
+
try {
|
|
131
|
+
const mk = (name: string, pid: number) => new DshProfileRuntimeRegistry({
|
|
132
|
+
dataDir: dir, name, pid,
|
|
133
|
+
deps: { isAlivePid: (p) => p === pid, killPid: () => {}, now: () => 1_000_000, sleep: () => Promise.resolve() },
|
|
134
|
+
})
|
|
135
|
+
const a = mk('web', 111)
|
|
136
|
+
const b = mk('web!', 222)
|
|
137
|
+
a.announce()
|
|
138
|
+
b.announce()
|
|
139
|
+
assert.notEqual(a.fileFor('web'), b.fileFor('web!'), '清洗同形的两个名字必须落到不同文件')
|
|
140
|
+
assert.equal(readdirSync(join(dir, 'running')).length, 2, '两个实例各留一份心跳')
|
|
141
|
+
b.withdraw()
|
|
142
|
+
assert.equal(existsSync(a.fileFor('web')), true, 'B 自撤不得删掉 A 的心跳')
|
|
143
|
+
assert.deepEqual(a.listActive().map((r) => r.name), ['web'], 'A 仍可见')
|
|
144
|
+
} finally { rmSync(dir, { recursive: true, force: true }) }
|
|
145
|
+
})
|
|
146
|
+
|
|
125
147
|
test('stopExternal:停**别的**实例(按它的心跳 pid),成功后删除它的心跳', async () => {
|
|
126
148
|
const a = makeHarness({ name: 'web', pid: 111, alive: 'die-on-kill' })
|
|
127
149
|
const b = makeHarness({ name: 'cmtest', pid: 222, alive: 'die-on-kill' })
|
|
@@ -142,7 +164,7 @@ test('stopExternal:停**别的**实例(按它的心跳 pid),成功后删
|
|
|
142
164
|
assert.equal(stopped.name, 'cmtest')
|
|
143
165
|
assert.deepEqual(a.killed, ['222:graceful'])
|
|
144
166
|
assert.deepEqual(a.registry.listActive().map((r) => r.name), ['web'], 'B 的心跳已被删')
|
|
145
|
-
assert.equal(existsSync(join(a.dir, 'cmtest
|
|
167
|
+
assert.equal(existsSync(join(a.dir, runtimeFileName('cmtest'))), false)
|
|
146
168
|
} finally { a.cleanup(); b.cleanup() }
|
|
147
169
|
})
|
|
148
170
|
|
|
@@ -165,7 +187,7 @@ test('stopExternal:没有心跳 → notRunning;停自己 → currentProfile
|
|
|
165
187
|
() => h.registry.stopExternal('cmtest'),
|
|
166
188
|
(e: unknown) => e instanceof DshProfileError && e.code === 'stopFailed' && e.message.includes('222'),
|
|
167
189
|
)
|
|
168
|
-
assert.equal(existsSync(join(h.dir, 'cmtest
|
|
190
|
+
assert.equal(existsSync(join(h.dir, runtimeFileName('cmtest'))), true, '杀不掉就不删心跳(否则会以为它已经没了)')
|
|
169
191
|
forced.cleanup()
|
|
170
192
|
} finally { h.cleanup() }
|
|
171
193
|
})
|
|
@@ -184,10 +206,10 @@ test('startHeartbeat:按 refreshMs 定期 announce,stop() 之后不再刷',
|
|
|
184
206
|
const stop = h.registry.startHeartbeat()
|
|
185
207
|
assert.equal(intervalMs, RUNTIME_REFRESH_MS)
|
|
186
208
|
assert.notEqual(box.fn, null)
|
|
187
|
-
const before = JSON.parse(readFileSync(join(h.dir, 'web
|
|
209
|
+
const before = JSON.parse(readFileSync(join(h.dir, runtimeFileName('web')), 'utf8')) as { updatedAt: number }
|
|
188
210
|
h.tick(5_000)
|
|
189
211
|
box.fn?.()
|
|
190
|
-
const after = JSON.parse(readFileSync(join(h.dir, 'web
|
|
212
|
+
const after = JSON.parse(readFileSync(join(h.dir, runtimeFileName('web')), 'utf8')) as { updatedAt: number }
|
|
191
213
|
assert.equal(after.updatedAt, before.updatedAt + 5_000, '心跳被刷新(判活靠它)')
|
|
192
214
|
stop()
|
|
193
215
|
stop()
|