evolcore 0.0.49 → 0.0.51
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/CHANGELOG.md +103 -3
- package/bin/ec-build.mjs +60 -0
- package/bin/ecmsg.js +64 -57
- package/dist/ability/caller/authorization.js +21 -0
- package/dist/ability/caller/command.js +173 -0
- package/dist/ability/caller/contract.js +117 -0
- package/dist/ability/caller/credential-files.js +132 -0
- package/dist/ability/caller/daemon.js +183 -0
- package/dist/ability/caller/schema-view.js +157 -0
- package/dist/ability/caller/service.js +519 -0
- package/dist/ability/command-contract.js +5 -0
- package/dist/ability/daemon.js +5 -1
- package/dist/ability/interop-v1.js +156 -106
- package/dist/ability/management.js +1 -0
- package/dist/agent-template/jobs.js +79 -3
- package/dist/agent-template/runtime.js +459 -47
- package/dist/agent-template/service.js +1242 -198
- package/dist/agent-template/share.js +103 -0
- package/dist/agent-template/tool-runner.js +25 -0
- package/dist/agent-template/types.js +10 -2
- package/dist/agents/claude/availability.js +94 -0
- package/dist/agents/claude/capability-provider.js +154 -0
- package/dist/agents/claude/index.js +145 -0
- package/dist/agents/{claude-runner.js → claude/runner.js} +78 -166
- package/dist/agents/claude/session-file-adapter.js +246 -0
- package/dist/agents/codex/app-server-client.js +90 -10
- package/dist/agents/codex/availability.js +164 -0
- package/dist/agents/codex/capability-provider.js +138 -0
- package/dist/agents/codex/cli.js +38 -0
- package/dist/agents/codex/index.js +345 -0
- package/dist/agents/codex/mcp-elicitation.js +135 -0
- package/dist/agents/{codex-runner.js → codex/runner.js} +652 -383
- package/dist/agents/codex/session-file-adapter.js +834 -0
- package/dist/agents/dsh/availability.js +28 -0
- package/dist/agents/dsh/capability-provider.js +56 -0
- package/dist/agents/dsh/desktop-locations.ps1 +66 -0
- package/dist/agents/dsh/desktop-probe.cjs +37 -0
- package/dist/agents/dsh/index.js +98 -0
- package/dist/agents/dsh/installation.js +400 -0
- package/dist/agents/dsh/resources.js +755 -0
- package/dist/agents/dsh/runner.js +1183 -0
- package/dist/agents/dsh/runtime/README.md +243 -0
- package/dist/agents/dsh/runtime/authorization.js +23 -0
- package/dist/agents/dsh/runtime/bridge.js +837 -0
- package/dist/agents/dsh/runtime/config.js +271 -0
- package/dist/agents/dsh/runtime/entry.js +229 -0
- package/dist/agents/dsh/runtime/session-inspector.js +340 -0
- package/dist/agents/dsh/runtime/tool-policy.js +49 -0
- package/dist/agents/dsh/session-file-adapter.js +145 -0
- package/dist/agents/ecagent/index.js +215 -0
- package/dist/agents/{ecagent-runner.js → ecagent/runner.js} +592 -106
- package/dist/agents/ecagent/session-file-adapter.js +134 -0
- package/dist/agents/gemini/index.js +96 -0
- package/dist/agents/{gemini-runner.js → gemini/runner.js} +18 -23
- package/dist/{core/session/adapters/gemini-session-file-adapter.js → agents/gemini/session-file-adapter.js} +2 -2
- package/dist/aun/ability-device-routing.js +11 -17
- package/dist/aun/aid/agentmd.js +27 -1
- package/dist/aun/aid/control-aid.js +52 -32
- package/dist/aun/aid/managed-operation.js +6 -4
- package/dist/aun/group/invite-service.js +7 -37
- package/dist/aun/group/operations.js +6 -0
- package/dist/aun/menu/client.js +1 -1
- package/dist/aun/msg/history.js +1 -1
- package/dist/aun/msg/managed-operation.js +93 -21
- package/dist/aun/msg/mention-schema.js +1 -1
- package/dist/aun/msg/p2p.js +32 -4
- package/dist/aun/msg/upload.js +126 -3
- package/dist/aun/service-proxy.js +1 -1
- package/dist/aun/storage/index.js +242 -0
- package/dist/build-identity.json +1 -1
- package/dist/channels/aun.js +698 -213
- package/dist/channels/daemon.js +3 -2
- package/dist/channels/dingtalk.js +1 -1
- package/dist/channels/feishu.js +9 -9
- package/dist/channels/qqbot.js +1 -1
- package/dist/channels/wechat.js +2 -2
- package/dist/channels/wecom.js +1 -1
- package/dist/claude-gateway/agent-registration.js +389 -0
- package/dist/claude-gateway/binding.js +96 -0
- package/dist/claude-gateway/inbox.js +138 -0
- package/dist/claude-gateway/index.js +125 -0
- package/dist/claude-gateway/listing.js +330 -0
- package/dist/claude-gateway/router.js +328 -0
- package/dist/claude-gateway/sessions.js +128 -0
- package/dist/claude-gateway/terminal.js +250 -0
- package/dist/claude-gateway/transcript.js +272 -0
- package/dist/claude-gateway/types.js +14 -0
- package/dist/cli/ability-command.js +45 -0
- package/dist/cli/ability-output.js +182 -0
- package/dist/cli/agent-command.js +21 -2
- package/dist/cli/agent-create.js +197 -56
- package/dist/cli/agent-template.js +400 -27
- package/dist/cli/agent.js +105 -11
- package/dist/cli/aun-commands.js +237 -123
- package/dist/cli/bench.js +5 -2
- package/dist/cli/config.js +22 -6
- package/dist/cli/daemon-commands.js +283 -109
- package/dist/cli/data-command.js +1 -1
- package/dist/cli/debug-mode.js +9 -0
- package/dist/cli/directory.js +1 -2
- package/dist/cli/ecmsg-gateway.js +64 -26
- package/dist/cli/fs-command.js +67 -39
- package/dist/cli/index.js +45 -12
- package/dist/cli/init.js +161 -90
- package/dist/cli/managed-command-guard.js +3 -0
- package/dist/cli/menu-client.js +32 -7
- package/dist/cli/model.js +1 -1
- package/dist/cli/pay-command.js +30 -0
- package/dist/cli/provider-command.js +6 -2
- package/dist/cli/restart-monitor.js +4 -4
- package/dist/cli/services-command.js +35 -10
- package/dist/cli/skill-command.js +4 -4
- package/dist/cli/task-context.js +24 -14
- package/dist/cli/team-workspace-command.js +50 -52
- package/dist/cli/thread-command.js +81 -14
- package/dist/cli/trigger-command.js +47 -12
- package/dist/cli/watch-logs.js +2 -1
- package/dist/config/access-policy.js +16 -3
- package/dist/config/boot-log.js +3 -0
- package/dist/config/builtin-role-templates.js +1 -1
- package/dist/config/config-field-policy.js +26 -13
- package/dist/config/config-manager.js +113 -52
- package/dist/config/config-operation-service.js +22 -1
- package/dist/config/gateway-config.js +29 -44
- package/dist/config/invoke-ipc-service.js +1 -1
- package/dist/config/owner-config.js +5 -19
- package/dist/config/peer-book-store.js +2 -3
- package/dist/config/peer-book.js +2 -2
- package/dist/config/peer-role-resolver.js +3 -9
- package/dist/config/provider-identity-migration.js +24 -105
- package/dist/config/provider-ipc-service.js +13 -3
- package/dist/config/provider-local-sync.js +4 -1
- package/dist/config/provider-menu-request.js +21 -3
- package/dist/config/provider-templates.js +1 -1
- package/dist/config/providers-config.js +138 -31
- package/dist/config/providers-import.js +3 -3
- package/dist/config/providers-management.js +109 -118
- package/dist/config/resolved-config-op.js +1 -42
- package/dist/config/schema-migration.js +254 -15
- package/dist/config/schema-registry.js +53 -8
- package/dist/config-store.js +1343 -63
- package/dist/core/{agent-application-service.js → agent/agent-application-service.js} +228 -9
- package/dist/core/{agent-create-status.js → agent/agent-create-status.js} +112 -4
- package/dist/core/{agent-creation-claim.js → agent/agent-creation-claim.js} +3 -3
- package/dist/core/{agent-ipc-registration.js → agent/agent-ipc-registration.js} +119 -25
- package/dist/core/{agent-reload-coordinator.js → agent/agent-reload-coordinator.js} +65 -0
- package/dist/core/{agent-runtime.js → agent/agent-runtime.js} +249 -79
- package/dist/core/{evolagent-registry.js → agent/evolagent-registry.js} +23 -18
- package/dist/core/{evolagent.js → agent/evolagent.js} +11 -11
- package/dist/core/auth/agent-delegation.js +15 -8
- package/dist/core/auth/delegation-authorization.js +28 -0
- package/dist/core/auth/operation-authorizer.js +20 -2
- package/dist/core/auth/operation-catalog.js +80 -8
- package/dist/core/baseagent/baseagent-availability.js +197 -0
- package/dist/core/baseagent/baseagent-capability-adapter.js +288 -0
- package/dist/core/baseagent/baseagent-config-shared.js +56 -0
- package/dist/core/baseagent/baseagent-identity.js +68 -0
- package/dist/core/{baseagent-loader.js → baseagent/baseagent-loader.js} +89 -6
- package/dist/core/baseagent/baseagent-model-defaults.js +26 -0
- package/dist/core/baseagent/baseagent-plugin-descriptor.js +357 -0
- package/dist/core/baseagent/baseagent-plugin-loader.js +367 -0
- package/dist/core/baseagent/baseagent.js +157 -0
- package/dist/{agents → core/baseagent}/runner-types.js +36 -4
- package/dist/core/capability/capability-manager.js +91 -33
- package/dist/core/capability/providers/claude-capability-provider.js +2 -154
- package/dist/core/capability/providers/codex-capability-provider.js +2 -136
- package/dist/core/{channel-loader.js → channel/channel-loader.js} +226 -38
- package/dist/core/{channel-runtime.js → channel/channel-runtime.js} +21 -19
- package/dist/core/command/agent-control.js +80 -17
- package/dist/core/command/agent-template-menu.js +23 -10
- package/dist/core/command/agentmd-menu-request.js +19 -8
- package/dist/core/command/agentmd-menu.js +14 -5
- package/dist/core/command/cli-intent-parser.js +15 -0
- package/dist/core/command/command-handler.js +127 -57
- package/dist/core/command/context-policy-menu.js +122 -0
- package/dist/core/command/data-root-resolver.js +157 -20
- package/dist/core/command/memory-slash.js +6 -6
- package/dist/core/command/menu-catalog.js +95 -19
- package/dist/core/command/menu-file-path.js +70 -0
- package/dist/core/command/menu-handler.js +392 -93
- package/dist/core/command/menu-protocol.js +47 -8
- package/dist/core/command/menu-query-batch.js +9 -5
- package/dist/core/command/private-mention-menu.js +71 -0
- package/dist/core/command/provider-menu.js +7 -11
- package/dist/core/command/role-menu.js +1 -1
- package/dist/core/command/skill-slash.js +17 -5
- package/dist/core/command/slash-gate.js +2 -4
- package/dist/core/command/slash-handler.js +143 -121
- package/dist/core/command/team-workspace-bootstrap.js +2 -1
- package/dist/core/command/team-workspace-team.js +3 -3
- package/dist/core/command/topic-slash.js +16 -10
- package/dist/core/{daemon-bootstrap.js → daemon/daemon-bootstrap.js} +14 -18
- package/dist/core/{daemon-control.js → daemon/daemon-control.js} +48 -21
- package/dist/core/{daemon-lifecycle.js → daemon/daemon-lifecycle.js} +28 -20
- package/dist/core/{host-snapshot.js → daemon/host-snapshot.js} +10 -5
- package/dist/core/{ipc-registration.js → daemon/ipc-registration.js} +101 -37
- package/dist/core/{lifecycle-notice.js → daemon/lifecycle-notice.js} +4 -5
- package/dist/core/file-integrity/store.js +1 -1
- package/dist/core/handoff/ipc-registration.js +3 -3
- package/dist/core/handoff/runtime.js +2 -2
- package/dist/{agents → core/inference}/request-identity.js +2 -2
- package/dist/core/inference/text-inference.js +4 -4
- package/dist/core/{bootstrap-messages.js → initialization/bootstrap-messages.js} +10 -10
- package/dist/core/{bootstrap-service.js → initialization/bootstrap-service.js} +24 -23
- package/dist/core/initialization/service.js +57 -9
- package/dist/core/invoke/executors/media.js +1 -1
- package/dist/core/invoke/executors/text.js +1 -1
- package/dist/core/memory/consolidation-context.js +3 -2
- package/dist/core/memory/consolidation-trigger.js +9 -3
- package/dist/core/memory/consolidation.js +39 -68
- package/dist/core/memory/memory-admin.js +6 -6
- package/dist/core/memory/memory-writer.js +1 -1
- package/dist/core/memory/relation-idle-monitor.js +1 -1
- package/dist/core/message/aun-ipc-sender.js +204 -88
- package/dist/core/message/aun-request-registry.js +44 -5
- package/dist/core/message/auto-mention-gate.js +1 -1
- package/dist/core/message/contact-admission.js +1 -1
- package/dist/core/message/im-renderer.js +19 -0
- package/dist/core/{interaction-router.js → message/interaction-router.js} +131 -1
- package/dist/core/message/items-formatter.js +5 -5
- package/dist/core/message/message-admission.js +1 -1
- package/dist/core/message/message-bridge.js +239 -59
- package/dist/core/message/message-log.js +8 -0
- package/dist/core/message/message-queue.js +88 -7
- package/dist/core/message/message-utils.js +1 -1
- package/dist/core/message/peer-mode.js +16 -5
- package/dist/core/message/response-engine.js +351 -152
- package/dist/core/message/send-options.js +44 -7
- package/dist/core/message/send-routing.js +55 -115
- package/dist/core/message/stream-idle-monitor.js +1 -1
- package/dist/core/{data-migration.js → migration/data-migration.js} +29 -1
- package/dist/core/model/catalog-service.js +29 -8
- package/dist/core/model/model-capabilities.js +88 -0
- package/dist/core/model/model-catalog.js +18 -7
- package/dist/core/model/model-diagnostics.js +4 -4
- package/dist/core/ownership/owner-resolver.js +107 -101
- package/dist/core/{pack-auth.js → pack/pack-auth.js} +34 -3
- package/dist/core/{pack-install.js → pack/pack-install.js} +95 -17
- package/dist/core/permission/approval-gateway.js +9 -18
- package/dist/core/permission/ec-command-parser.js +242 -82
- package/dist/core/permission/managed-file.js +234 -0
- package/dist/core/permission/protected-paths.js +120 -9
- package/dist/core/permission/sandbox-runtime.js +267 -3
- package/dist/core/permission/services-path-acl.js +9 -2
- package/dist/core/permission/session-path-grants.js +1 -1
- package/dist/core/permission/shell-environment.js +15 -1
- package/dist/core/permission/tool-policy.js +21 -9
- package/dist/core/plugin/plugin-lifecycle.js +442 -0
- package/dist/core/session/adapters/claude-session-file-adapter.js +2 -242
- package/dist/core/session/adapters/codex-session-file-adapter.js +2 -562
- package/dist/core/session/adapters/ecagent-session-file-adapter.js +2 -134
- package/dist/core/{background-session → session/background}/session-cleanup.js +2 -2
- package/dist/core/{background-session → session/background}/types.js +1 -1
- package/dist/core/session/session-file-health.js +2 -272
- package/dist/core/session/session-idle-monitor.js +1 -1
- package/dist/core/session/session-manager.js +76 -12
- package/dist/core/session/session-mapper.js +16 -0
- package/dist/core/session/session-terminal.js +185 -0
- package/dist/core/session/session-title.js +8 -11
- package/dist/core/{system-session → session/system}/memory.js +43 -9
- package/dist/core/{system-session → session/system}/registry.js +1 -1
- package/dist/core/{system-session → session/system}/types.js +1 -1
- package/dist/core/skill/index-generator.js +3 -3
- package/dist/core/skill/switch-resolver.js +3 -0
- package/dist/core/task/task-activity-store.js +112 -0
- package/dist/core/task/task-recovery-service.js +2 -2
- package/dist/core/thread/command-parser.js +4 -1
- package/dist/core/thread/ipc-operation.js +6 -4
- package/dist/core/thread/thread-operation.js +27 -11
- package/dist/core/thread/thread-route.js +5 -3
- package/dist/core/thread/thread-service.js +307 -58
- package/dist/core/thread/topic-id.js +52 -2
- package/dist/core/thread/types.js +15 -1
- package/dist/directory/{owner-directory-admission.js → admission.js} +3 -3
- package/dist/directory/{owner-directory-cache.js → cache.js} +90 -8
- package/dist/directory/{owner-directory-markdown.js → markdown.js} +2 -2
- package/dist/directory/{owner-directory-query-operation.js → query-operation.js} +83 -9
- package/dist/directory/{owner-directory-search.js → search.js} +50 -2
- package/dist/directory/{owner-directory-store.js → store.js} +2 -2
- package/dist/eck/kit-renderer.js +3 -2
- package/dist/eck/manifest-engine.js +64 -2
- package/dist/eck/message-renderer.js +35 -0
- package/dist/ecweb/basic-settings-service.js +12 -10
- package/dist/{contracts → ecweb/contracts}/ecweb-service-protocol.js +2 -1
- package/dist/ecweb/dsh-native-service.js +413 -0
- package/dist/ecweb/providers-service.js +5 -3
- package/dist/ecweb/runtime/lifecycle.js +1 -1
- package/dist/ecweb/runtime/supervisor.js +1 -1
- package/dist/event-center/center-config.js +2 -2
- package/dist/event-center/dispatcher.js +1 -1
- package/dist/event-center/ipc-operation.js +12 -3
- package/dist/event-center/pack-loader.js +2 -2
- package/dist/event-center/registry.js +6 -6
- package/dist/event-center/runtime.js +2 -2
- package/dist/index.js +181 -77
- package/dist/ipc.js +161 -12
- package/dist/outputs/authorization.js +27 -0
- package/dist/outputs/events.js +10 -1
- package/dist/outputs/panel-cards.js +960 -0
- package/dist/paths.js +60 -1
- package/dist/pay/command.js +38 -0
- package/dist/pay/protocol.js +136 -0
- package/dist/pay/runtime.js +196 -0
- package/dist/pay/service.js +384 -0
- package/dist/pay/store.js +81 -0
- package/dist/response-system/engines/v1/proactive-flow.js +30 -3
- package/dist/services/dispatcher.js +25 -7
- package/dist/services/host/main.js +397 -0
- package/dist/services/host/protocol.js +125 -0
- package/dist/services/host/resident.js +347 -0
- package/dist/services/host-client.js +398 -0
- package/dist/services/host-deploy.js +180 -0
- package/dist/services/host-launch.js +117 -0
- package/dist/services/host-recycle.js +208 -0
- package/dist/services/host-runtime.js +841 -0
- package/dist/services/idempotency.js +44 -86
- package/dist/services/index-generator.js +4 -3
- package/dist/services/index.js +258 -36
- package/dist/services/ipc-operation.js +503 -78
- package/dist/services/pack-manager.js +2 -2
- package/dist/services/router.js +43 -3
- package/dist/services/script-runner.js +541 -100
- package/dist/services/service-payload.js +28 -1
- package/dist/services/validation.js +136 -5
- package/dist/stats/context-usage.js +110 -0
- package/dist/stats/model-resolver.js +103 -17
- package/dist/stats/query.js +5 -0
- package/dist/trigger/application-service.js +9 -6
- package/dist/trigger/authorization.js +36 -33
- package/dist/trigger/ipc-service.js +4 -4
- package/dist/trigger/local-files.js +8 -166
- package/dist/trigger/manager.js +2 -2
- package/dist/trigger/parser.js +48 -0
- package/dist/trigger/scheduler.js +35 -13
- package/dist/trigger/script-executor.js +21 -0
- package/dist/trigger/script-sandbox.js +77 -232
- package/dist/trigger/system-definitions.js +25 -0
- package/dist/trigger/validation.js +1 -1
- package/dist/utils/aid-bind.js +3 -0
- package/dist/utils/atomic-write.js +88 -1
- package/dist/utils/cross-platform.js +4 -42
- package/dist/utils/error-dict.json +22 -1
- package/dist/utils/error-utils.js +193 -6
- package/dist/utils/evolcore-version.js +2 -2
- package/dist/utils/host-info.js +74 -1
- package/dist/utils/logger.js +5 -3
- package/dist/utils/media-cache.js +284 -42
- package/dist/utils/restart-safety.js +14 -1
- package/dist/utils/startup-trace.js +20 -4
- package/dist/utils/system-memory.js +113 -25
- package/dist/utils/systemd-lifecycle.js +154 -0
- package/dist/utils/welcome.js +64 -20
- package/dist/utils/windows-shell-trust.js +7 -3
- package/ecagent/README.md +35 -0
- package/ecagent/dist/agent-loop.js +80 -30
- package/ecagent/dist/harness/env/nodejs.d.ts +16 -0
- package/ecagent/dist/harness/env/nodejs.js +49 -20
- package/ecagent/dist/harness/messages.js +3 -2
- package/ecagent/dist/harness/types.d.ts +1 -0
- package/ecagent/dist/runtime/types.d.ts +2 -0
- package/ecagent/dist/runtime/utils/validation.d.ts +7 -1
- package/ecagent/dist/runtime/utils/validation.js +42 -0
- package/ecagent/dist/types.d.ts +2 -0
- package/kits/docs/INDEX.md +3 -2
- package/kits/docs/aun/AUN/346/266/210/346/201/257/347/261/273/345/236/213/344/270/216/345/261/236/346/200/247.md +1 -0
- package/kits/docs/channels/aun.md +1 -1
- package/kits/docs/channels/feishu.md +1 -1
- package/kits/docs/evolcore/INDEX.md +13 -9
- package/kits/docs/evolcore/agent-create.md +2 -0
- package/kits/docs/evolcore/agent.md +133 -11
- package/kits/docs/evolcore/aid.md +39 -6
- package/kits/docs/evolcore/config.md +95 -1
- package/kits/docs/evolcore/ctl.md +2 -1
- package/kits/docs/evolcore/ec-capabilities.md +7 -10
- package/kits/docs/evolcore/ecweb-lifecycle.md +5 -1
- package/kits/docs/evolcore/event.md +1 -1
- package/kits/docs/evolcore/fs.md +49 -3
- package/kits/docs/evolcore/group.md +5 -4
- package/kits/docs/evolcore/memory-consolidation.md +1 -1
- package/kits/docs/evolcore/memory-tags.md +2 -0
- package/kits/docs/evolcore/menu-client.md +3 -3
- package/kits/docs/evolcore/menu-protocol.md +31 -2
- package/kits/docs/evolcore/model.md +12 -1
- package/kits/docs/evolcore/msg.md +96 -36
- package/kits/docs/evolcore/pay.md +22 -0
- package/kits/docs/evolcore/plugin.md +74 -0
- package/kits/docs/evolcore/provider.md +29 -2
- package/kits/docs/evolcore/rpc.md +2 -2
- package/kits/docs/evolcore/services.md +46 -18
- package/kits/docs/evolcore/skill.md +17 -1
- package/kits/docs/evolcore/stats.md +5 -0
- package/kits/docs/evolcore/storage.md +22 -0
- package/kits/docs/evolcore/thread-chain.md +20 -9
- package/kits/docs/evolcore/tool-authorization.md +14 -0
- package/kits/docs/evolcore/trigger.md +89 -13
- package/kits/docs/identity/AID_PROFILE_SPEC.md +1 -1
- package/kits/docs/venues/feishu-group.md +3 -2
- package/kits/docs/venues/feishu-private.md +3 -2
- package/kits/rules/01-overview.md +11 -32
- package/kits/rules/02-navigation.md +20 -6
- package/kits/rules/06-channel.md +20 -4
- package/kits/schemas/_meta.json +42 -5
- package/kits/schemas/agent-config.schema.21.json +974 -0
- package/kits/schemas/agent-config.schema.22.json +977 -0
- package/kits/schemas/agent-config.schema.23.json +974 -0
- package/kits/schemas/agent-config.schema.24.json +986 -0
- package/kits/schemas/agent-config.schema.25.json +986 -0
- package/kits/schemas/daemon.schema.10.json +373 -0
- package/kits/schemas/daemon.schema.11.json +487 -0
- package/kits/schemas/daemon.schema.12.json +505 -0
- package/kits/schemas/daemon.schema.9.json +12 -0
- package/kits/schemas/defaults.schema.7.json +472 -0
- package/kits/schemas/defaults.schema.8.json +484 -0
- package/kits/schemas/providers.schema.1.json +1 -1
- package/kits/schemas/providers.schema.2.json +1 -1
- package/kits/schemas/providers.schema.3.json +26 -4
- package/kits/schemas/relation-config.schema.13.json +289 -0
- package/kits/skills/.switches.json +17 -1
- package/kits/skills/ability/SKILL.md +395 -33
- package/kits/skills/ability/STRUCTURE.md +338 -0
- package/kits/skills/ability/references/cli.md +208 -0
- package/kits/skills/ability/references/development.md +107 -37
- package/kits/skills/ability/references/management.md +106 -46
- package/kits/skills/ability/references/runtime-protocol.md +65 -63
- package/kits/skills/agent-output-cards/SKILL.md +80 -37
- package/kits/skills/agent-output-cards/examples/html-surface.json +11 -0
- package/kits/skills/agent-output-cards/examples/meeting-followups.json +16 -0
- package/kits/skills/agent-output-cards/examples/meeting-latest.json +24 -0
- package/kits/skills/agent-output-cards/examples/project-metrics.json +16 -0
- package/kits/skills/agent-output-cards/examples/quick-links.json +18 -0
- package/kits/skills/agent-output-cards/examples/surface.html +8 -0
- package/kits/skills/agent-template-project/SKILL.md +51 -0
- package/kits/skills/agent-template-project/references/01-collect-and-pack.md +174 -0
- package/kits/skills/agent-template-project/references/02-upload-and-share.md +109 -0
- package/kits/skills/agent-template-project/references/03-download-and-install.md +189 -0
- package/kits/skills/agent-template-project/references/04-upgrade-and-recovery.md +74 -0
- package/kits/skills/agent-template-project/references/05-publish-to-platform.md +62 -0
- package/kits/skills/ec-group/SKILL.md +8 -6
- package/kits/skills/ec-group/TASK.md +186 -0
- package/kits/skills/ec-group/WORKLOG.md +180 -0
- package/kits/skills/ec-group-collaboration/SKILL.md +5 -5
- package/kits/skills/ec-identity/SKILL.md +9 -6
- package/kits/skills/ec-pay/SKILL.md +223 -0
- package/kits/skills/ec-provider/SKILL.md +6 -6
- package/kits/skills/{ec-service-proxy → ec-proxy}/SKILL.md +8 -5
- package/kits/skills/ec-service-call/SKILL.md +138 -0
- package/kits/skills/ec-service-pack/SKILL.md +277 -0
- package/kits/skills/ec-skill/SKILL.md +25 -9
- package/kits/skills/ec-skill/scripts/cli.mjs +7 -7
- package/kits/skills/ec-skill/scripts/skill.mjs +55 -41
- package/kits/skills/ec-skill/scripts/template/SKILL.md.tmpl +9 -0
- package/kits/skills/ec-trigger/SKILL.md +3 -3
- package/kits/skills/personal-assistant/SKILL.md +22 -22
- package/kits/skills/personal-assistant/references/03-data-flow-and-gaps.md +1 -1
- package/kits/skills/scrapling-article-fetch/SKILL.md +5 -5
- package/kits/skills/thread-ops/SKILL.md +19 -9
- package/kits/skills/wechat-article-media-download/SKILL.md +2 -2
- package/kits/skills/wechat-article-reader/SKILL.md +2 -2
- package/kits/templates/memory-consolidation/notes.md +2 -2
- package/kits/templates/memory-consolidation/workflow.md +46 -0
- package/kits/templates/system-fragments/channel.md +13 -4
- package/kits/templates/system-fragments/commands.md +5 -4
- package/kits/templates/system-fragments/personal-assistant.md +2 -2
- package/kits/templates/system-fragments/reply.md +15 -9
- package/kits/templates/system-fragments/session.md +2 -2
- package/kits/templates/system-fragments/thread.md +30 -127
- package/kits/templates/system-fragments/venue.md +16 -0
- package/package.json +7 -7
- package/scripts/agent-template/index.mjs +7 -1
- package/scripts/agent-template/inspect.mjs +99 -39
- package/scripts/agent-template/overlay.mjs +126 -2
- package/scripts/agent-template/shared/common.mjs +49 -5
- package/scripts/agent-template/shared/plan.mjs +4 -2
- package/scripts/agent-template/shared/service-packs.mjs +104 -0
- package/scripts/agent-template/shared/team-schema.json +468 -39
- package/scripts/agent-template/shared/template-contract.mjs +93 -51
- package/scripts/agent-template/shared/template-package.mjs +225 -44
- package/scripts/agent-template/shared/template-runtime.mjs +137 -15
- package/scripts/agent-template/shared/template.mjs +31 -8
- package/scripts/agent-template/team-pack.mjs +528 -56
- package/scripts/agent-template/team-preview.mjs +102 -9
- package/scripts/aid-batch/identity-batch.mjs +1 -1
- package/dist/agents/baseagent-availability.js +0 -152
- package/dist/agents/baseagent.js +0 -750
- package/dist/agents/codex/catalog.js +0 -80
- package/dist/agents/ecagent-plugin-lazy.js +0 -41
- package/dist/agents/tool-time-context.js +0 -55
- package/dist/core/legacy-rename.js +0 -41
- package/dist/core/plugin-lifecycle.js +0 -137
- package/dist/core/rate-window.js +0 -53
- package/dist/core/runner-reload-transaction.js +0 -60
- package/dist/core/runtime-lock.js +0 -90
- package/dist/core/soul.js +0 -66
- package/dist/core/system-session/grants.js +0 -40
- package/dist/directory/owner-directory-agentmd-sync.js +0 -89
- package/dist/directory/owner-directory-request-operation.js +0 -79
- package/dist/directory/owner-directory-text.js +0 -60
- package/kits/docs/aun/ABILITY_CALLING.md +0 -280
- package/kits/docs/evolcore/ability.md +0 -185
- package/kits/skills/ability/references/calling.md +0 -56
- package/kits/skills/ability/references/contract-checklist.md +0 -37
- package/kits/skills/ability/references/recovery.md +0 -27
- /package/dist/{core/capability/providers/gemini-capability-provider.js → agents/gemini/capability-provider.js} +0 -0
- /package/dist/core/{system-channels.js → channel/system-channels.js} +0 -0
- /package/dist/core/{daemon-file-cache.js → daemon/daemon-file-cache.js} +0 -0
- /package/dist/core/{event-bus.js → event/event-bus.js} +0 -0
- /package/dist/core/{event-catalog.js → event/event-catalog.js} +0 -0
- /package/dist/core/{pack-ledger.js → pack/pack-ledger.js} +0 -0
- /package/dist/directory/{owner-directory-identity.js → identity.js} +0 -0
- /package/dist/directory/{owner-directory-policy.js → policy.js} +0 -0
- /package/dist/directory/{owner-directory-remarks.js → remarks.js} +0 -0
- /package/dist/directory/{owner-directory-scope.js → scope.js} +0 -0
- /package/dist/{contracts → ecweb/contracts}/ecweb-instance.js +0 -0
- /package/kits/templates/{bootstrap-welcome.md → bootstrap-intro.md} +0 -0
package/dist/config-store.js
CHANGED
|
@@ -16,23 +16,27 @@
|
|
|
16
16
|
* 旧 data/daemon.json / agents/<name>.json 不识别、不兼容——视若不存在。
|
|
17
17
|
*/
|
|
18
18
|
import fs from 'fs';
|
|
19
|
+
import crypto from 'node:crypto';
|
|
20
|
+
import * as projectSessionStore from './core/session/session-fs-store.js';
|
|
21
|
+
import { validateBaseagentPluginConfigs } from './core/baseagent/baseagent-plugin-descriptor.js';
|
|
19
22
|
import path from 'path';
|
|
20
|
-
import { resolvePaths, agentDir, agentOutputDir, agentPersonalDir, kitsTemplatesDir, SOUL_PERSONA_FILE, } from './paths.js';
|
|
23
|
+
import { resolvePaths, agentConfig as agentConfigPath, agentDir, agentOutputDir, agentPersonalDir, kitsTemplatesDir, SOUL_PERSONA_FILE, } from './paths.js';
|
|
21
24
|
import { atomicReadJson, atomicWriteJson } from './utils/atomic-write.js';
|
|
22
|
-
import { registerFile as registerFileIntegrity } from './core/file-integrity/store.js';
|
|
25
|
+
import { registerFile as registerFileIntegrity, verifyFile as verifyFileIntegrity } from './core/file-integrity/store.js';
|
|
23
26
|
import { checkAgentDir, isValidAid } from './aun/aid/validation.js';
|
|
24
27
|
import { normalizeAidDomain } from './aun/aid/domain.js';
|
|
25
|
-
import {
|
|
28
|
+
import { validateChannelConfigs } from './core/channel/channel-loader.js';
|
|
26
29
|
import { CONFIG_SCHEMA_VERSION } from './types.js';
|
|
27
|
-
import { ConfigTarget, assertAgentAidAvailable, assertControlAidAvailable, assertNoLegacyAunGatewayConfig, read as cfgRead, normalizeProcessConfigCompat, stripLegacyAunGatewayConfig, write as cfgWrite, } from './config/config-manager.js';
|
|
30
|
+
import { ConfigTarget, assertAgentAidAvailable, assertControlAidAvailable, assertNoLegacyAunGatewayConfig, read as cfgRead, resolveEffective, normalizeProcessConfigCompat, stripLegacyAunGatewayConfig, write as cfgWrite, } from './config/config-manager.js';
|
|
28
31
|
import { expandVars, buildEnvResolver } from './config/merge.js';
|
|
29
32
|
import { isAgentLifecycle } from './config/lifecycle.js';
|
|
30
33
|
import { logger } from './utils/logger.js';
|
|
31
34
|
import { parseStableSemver } from './utils/stable-semver.js';
|
|
32
|
-
import { isSupportedBaseagent } from './
|
|
35
|
+
import { isSupportedBaseagent, listSupportedBaseagents } from './core/baseagent/baseagent.js';
|
|
33
36
|
import { normalizeDaemonServices } from './config/daemon-services.js';
|
|
34
|
-
import { currentVersion } from './config/schema-registry.js';
|
|
35
|
-
import {
|
|
37
|
+
import { loadSchema, currentVersion } from './config/schema-registry.js';
|
|
38
|
+
import { preserveBaseagentDeclarationsOnWrite, migrateBaseagentDefaultsOnWrite } from './config/schema-migration.js';
|
|
39
|
+
import { assertProjectPathReference, resolveProjectDefaultPath } from './utils/project-path.js';
|
|
36
40
|
import { assertOwnerConfigRecord } from './config/owner-config.js';
|
|
37
41
|
const SERVICE_METADATA_SENSITIVE_KEY = /(?:^|[_-])(endpoint|url|uri|token|access[_-]?token|authorization|cookie|secret|password|private[_-]?key|key|cert|certificate)(?:$|[_-])/i;
|
|
38
42
|
function assertLocalServiceEndpoint(value, fieldPath) {
|
|
@@ -102,6 +106,21 @@ export function saveDaemonConfig(value) {
|
|
|
102
106
|
assertNoLegacyAunGatewayConfig(value, configPath);
|
|
103
107
|
assertControlAidAvailable(value.aid);
|
|
104
108
|
const current = atomicReadJson(configPath);
|
|
109
|
+
const requested = normalizeProcessConfigCompat(normalizeDaemonServices(value));
|
|
110
|
+
// Keep existing field-specific diagnostics before the general schema check.
|
|
111
|
+
validateDaemonConfig(requested, current === null || current.aun?.defaultAidDomain !== requested.aun?.defaultAidDomain);
|
|
112
|
+
const checked = structuredClone({ ...requested, $schema_version: currentVersion('daemon') });
|
|
113
|
+
if (current?.aid && current.aun?.defaultAidDomain === checked.aun?.defaultAidDomain && checked.aun) {
|
|
114
|
+
delete checked.aun.defaultAidDomain;
|
|
115
|
+
}
|
|
116
|
+
const schema = loadSchema('daemon');
|
|
117
|
+
if (!schema.validate(checked))
|
|
118
|
+
throw new Error('daemon configuration validation failed: ' + JSON.stringify(schema.validate.errors));
|
|
119
|
+
value = preserveBaseagentDeclarationsOnWrite(value);
|
|
120
|
+
// Seed the initial template once; an existing empty plugins object stays empty.
|
|
121
|
+
if (current === null && value.plugins === undefined) {
|
|
122
|
+
value = { ...value, plugins: structuredClone(loadSchema('daemon').raw.properties.plugins.default) };
|
|
123
|
+
}
|
|
105
124
|
// A legacy default is irrelevant while an existing control AID is retained.
|
|
106
125
|
// Validate the field when it is created or changed, but do not make unrelated
|
|
107
126
|
// daemon.json updates fail because of a persisted, unused legacy value.
|
|
@@ -323,15 +342,35 @@ function validateDaemonConfig(value, validateAidDomain) {
|
|
|
323
342
|
}
|
|
324
343
|
}
|
|
325
344
|
}
|
|
345
|
+
if (value.ccAgent !== undefined) {
|
|
346
|
+
if (!value.ccAgent || typeof value.ccAgent !== 'object' || Array.isArray(value.ccAgent)) {
|
|
347
|
+
throw new Error('daemon.json.ccAgent must be an object');
|
|
348
|
+
}
|
|
349
|
+
const unknownCcAgentFields = Object.keys(value.ccAgent).filter(key => !['enabled', 'aid', 'status', 'lastError'].includes(key));
|
|
350
|
+
if (value.ccAgent.enabled !== undefined && typeof value.ccAgent.enabled !== 'boolean')
|
|
351
|
+
throw new Error('daemon.json.ccAgent.enabled must be a boolean');
|
|
352
|
+
if (unknownCcAgentFields.length > 0) {
|
|
353
|
+
throw new Error('daemon.json.ccAgent contains unsupported fields: ' + unknownCcAgentFields.join(', '));
|
|
354
|
+
}
|
|
355
|
+
if (value.ccAgent.aid !== undefined) {
|
|
356
|
+
if (typeof value.ccAgent.aid !== 'string' || !isValidAid(value.ccAgent.aid)) {
|
|
357
|
+
throw new Error('daemon.json.ccAgent.aid must be a valid AID');
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
if (value.ccAgent.status !== undefined
|
|
361
|
+
&& !['registering', 'owner_pending', 'card_pending', 'ready'].includes(value.ccAgent.status)) {
|
|
362
|
+
throw new Error('daemon.json.ccAgent.status must be one of registering, owner_pending, card_pending, ready');
|
|
363
|
+
}
|
|
364
|
+
if (value.ccAgent.lastError !== undefined && typeof value.ccAgent.lastError !== 'string') {
|
|
365
|
+
throw new Error('daemon.json.ccAgent.lastError must be a string');
|
|
366
|
+
}
|
|
367
|
+
}
|
|
326
368
|
if (validateAidDomain && value.aun?.defaultAidDomain !== undefined) {
|
|
327
369
|
const defaultAidDomain = normalizeAidDomain(value.aun.defaultAidDomain, 'daemon.json.aun.defaultAidDomain');
|
|
328
370
|
return { ...value, aun: { ...value.aun, defaultAidDomain } };
|
|
329
371
|
}
|
|
330
372
|
return value;
|
|
331
373
|
}
|
|
332
|
-
const SUPPORTED_CHANNEL_TYPES = new Set([
|
|
333
|
-
'aun', 'feishu', 'wechat', 'dingtalk', 'qqbot', 'wecom',
|
|
334
|
-
]);
|
|
335
374
|
// ── env 展开(${VAR},design §五)─────────────────────────────────────────
|
|
336
375
|
//
|
|
337
376
|
// 仅支持 ${VAR}(旧 $ENV:NAME 已废弃)。展开经 merge.ts 的 expandVars + 三级 .env 解析器
|
|
@@ -364,6 +403,10 @@ export function saveDefaults(value) {
|
|
|
364
403
|
assertNoLegacyAunGatewayConfig(value, resolvePaths().defaultsConfig);
|
|
365
404
|
if (typeof value.projects?.defaultPath === 'string')
|
|
366
405
|
assertProjectPathReference(value.projects.defaultPath);
|
|
406
|
+
value = migrateBaseagentDefaultsOnWrite(value);
|
|
407
|
+
const errors = validateBaseagentPluginConfigs(value.baseagents, true);
|
|
408
|
+
if (errors.length)
|
|
409
|
+
throw new Error(errors.join('; '));
|
|
367
410
|
backupDefaults(resolvePaths().defaultsConfig);
|
|
368
411
|
atomicWriteJson(resolvePaths().defaultsConfig, stripLegacyAunGatewayConfig(value, resolvePaths().defaultsConfig, message => logger.warn(message)));
|
|
369
412
|
}
|
|
@@ -400,6 +443,7 @@ export function saveDefaultsSafe(patch) {
|
|
|
400
443
|
assertNoLegacyAunGatewayConfig(patch, p);
|
|
401
444
|
if (typeof patch.projects?.defaultPath === 'string')
|
|
402
445
|
assertProjectPathReference(patch.projects.defaultPath);
|
|
446
|
+
patch = migrateBaseagentDefaultsOnWrite(patch);
|
|
403
447
|
let existing = null;
|
|
404
448
|
try {
|
|
405
449
|
existing = atomicReadJson(p);
|
|
@@ -407,11 +451,14 @@ export function saveDefaultsSafe(patch) {
|
|
|
407
451
|
catch (e) {
|
|
408
452
|
logger.warn(`[config] existing defaults.json unparsable, will be backed up and replaced: ${e}`);
|
|
409
453
|
}
|
|
410
|
-
fs.mkdirSync(path.dirname(p), { recursive: true });
|
|
411
|
-
backupDefaults(p);
|
|
412
454
|
const merged = existing
|
|
413
455
|
? deepMergeObject(existing, patch)
|
|
414
456
|
: { $schema_version: CONFIG_SCHEMA_VERSION, ...patch };
|
|
457
|
+
const errors = validateBaseagentPluginConfigs(merged.baseagents, true);
|
|
458
|
+
if (errors.length)
|
|
459
|
+
throw new Error(errors.join('; '));
|
|
460
|
+
fs.mkdirSync(path.dirname(p), { recursive: true });
|
|
461
|
+
backupDefaults(p);
|
|
415
462
|
atomicWriteJson(p, stripLegacyAunGatewayConfig(merged, p, message => logger.warn(message)));
|
|
416
463
|
}
|
|
417
464
|
/** 递归对象合并:overlay 覆盖 base;标量与数组按 overlay 替换;plain object 递归。
|
|
@@ -574,7 +621,7 @@ export function loadAllAgents(opts = {}) {
|
|
|
574
621
|
* 见 docs/config-v2-inconsistencies-analysis.md 问题 B / config-system-v2-implementation-status.md。
|
|
575
622
|
*/
|
|
576
623
|
export function validateAgentConfig(cfg) {
|
|
577
|
-
const errs =
|
|
624
|
+
const errs = validateBaseagentPluginConfigs(cfg.baseagents);
|
|
578
625
|
if (!cfg.aid || !isValidAid(cfg.aid))
|
|
579
626
|
errs.push(`invalid aid: ${cfg.aid}`);
|
|
580
627
|
else {
|
|
@@ -586,15 +633,10 @@ export function validateAgentConfig(cfg) {
|
|
|
586
633
|
}
|
|
587
634
|
}
|
|
588
635
|
if (cfg.active_baseagent !== undefined && !isSupportedBaseagent(cfg.active_baseagent)) {
|
|
589
|
-
errs.push(`unsupported active_baseagent: ${cfg.active_baseagent} (
|
|
590
|
-
}
|
|
591
|
-
if (cfg.baseagents && typeof cfg.baseagents === 'object') {
|
|
592
|
-
for (const name of Object.keys(cfg.baseagents)) {
|
|
593
|
-
if (!isSupportedBaseagent(name)) {
|
|
594
|
-
errs.push(`unsupported baseagent config: ${name} (choose claude/codex/gemini/ecagent)`);
|
|
595
|
-
}
|
|
596
|
-
}
|
|
636
|
+
errs.push(`unsupported active_baseagent: ${cfg.active_baseagent} (declared: ${listSupportedBaseagents().join('/')})`);
|
|
597
637
|
}
|
|
638
|
+
// Saved settings for a removed optional backend remain inert. Only the
|
|
639
|
+
// selected identity must be declared; retaining settings does not load code.
|
|
598
640
|
if (cfg.lifecycle !== undefined && !isAgentLifecycle(cfg.lifecycle)) {
|
|
599
641
|
errs.push(`invalid lifecycle: ${String(cfg.lifecycle)}`);
|
|
600
642
|
}
|
|
@@ -602,48 +644,8 @@ export function validateAgentConfig(cfg) {
|
|
|
602
644
|
errs.push('channels must be an array');
|
|
603
645
|
return errs;
|
|
604
646
|
}
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
}
|
|
608
|
-
if (cfg.owners !== undefined) {
|
|
609
|
-
if (!Array.isArray(cfg.owners))
|
|
610
|
-
errs.push('owners must be an array');
|
|
611
|
-
else
|
|
612
|
-
cfg.owners.forEach((owner, i) => {
|
|
613
|
-
if (typeof owner !== 'string' || !isValidAid(owner))
|
|
614
|
-
errs.push(`owners[${i}] invalid aid: ${owner}`);
|
|
615
|
-
});
|
|
616
|
-
}
|
|
617
|
-
let aunCount = 0;
|
|
618
|
-
const seenNamesByType = new Map();
|
|
619
|
-
for (const [i, ch] of cfg.channels.entries()) {
|
|
620
|
-
if (!ch || typeof ch !== 'object') {
|
|
621
|
-
errs.push(`channels[${i}] must be an object`);
|
|
622
|
-
continue;
|
|
623
|
-
}
|
|
624
|
-
if (ch.type === 'aun') {
|
|
625
|
-
// AUN 是隐式的(从 agent.aid 派生),不应出现在 channels[] 里
|
|
626
|
-
// 容忍但 warn——不算 error,跳过校验
|
|
627
|
-
aunCount++;
|
|
628
|
-
continue;
|
|
629
|
-
}
|
|
630
|
-
if (!SUPPORTED_CHANNEL_TYPES.has(ch.type)) {
|
|
631
|
-
errs.push(`channels[${i}].type "${ch.type}" not supported`);
|
|
632
|
-
continue;
|
|
633
|
-
}
|
|
634
|
-
if (!isValidChannelName(ch.name)) {
|
|
635
|
-
errs.push(`channels[${i}].name invalid (empty or contains '#'): ${JSON.stringify(ch.name)}`);
|
|
636
|
-
continue;
|
|
637
|
-
}
|
|
638
|
-
const set = seenNamesByType.get(ch.type) ?? new Set();
|
|
639
|
-
if (set.has(ch.name)) {
|
|
640
|
-
errs.push(`channels[${i}]: duplicate name "${ch.name}" within type "${ch.type}"`);
|
|
641
|
-
}
|
|
642
|
-
else {
|
|
643
|
-
set.add(ch.name);
|
|
644
|
-
seenNamesByType.set(ch.type, set);
|
|
645
|
-
}
|
|
646
|
-
}
|
|
647
|
+
errs.push(...validateChannelConfigs(cfg.channels));
|
|
648
|
+
const aunCount = cfg.channels.filter(channel => channel?.type === 'aun').length;
|
|
647
649
|
if (aunCount > 0) {
|
|
648
650
|
logger.warn(`[config] agent ${cfg.aid}: channels[] contains ${aunCount} AUN entry(s) — AUN is implicit, these will be ignored`);
|
|
649
651
|
}
|
|
@@ -890,3 +892,1281 @@ export async function migrateProject(oldPath, newPath) {
|
|
|
890
892
|
}
|
|
891
893
|
return result;
|
|
892
894
|
}
|
|
895
|
+
function projectChangeError(code, message) {
|
|
896
|
+
return Object.assign(new Error(message), { code });
|
|
897
|
+
}
|
|
898
|
+
function projectChangeDirectory(aid) {
|
|
899
|
+
if (!isValidAid(aid))
|
|
900
|
+
throw projectChangeError('INVALID_ARGUMENT', 'Invalid Agent AID');
|
|
901
|
+
return path.join(agentDir(aid), 'data', 'project-migration');
|
|
902
|
+
}
|
|
903
|
+
function projectChangeFile(aid, planId) {
|
|
904
|
+
if (!/^project_[0-9a-f-]{36}$/.test(planId))
|
|
905
|
+
throw projectChangeError('INVALID_ARGUMENT', 'Invalid project plan ID');
|
|
906
|
+
return path.join(projectChangeDirectory(aid), planId, 'plan.json');
|
|
907
|
+
}
|
|
908
|
+
function projectPersist(file, value) {
|
|
909
|
+
atomicWriteJson(file, value);
|
|
910
|
+
fs.chmodSync(file, 0o600);
|
|
911
|
+
const fd = fs.openSync(file, 'r+');
|
|
912
|
+
try {
|
|
913
|
+
fs.fsyncSync(fd);
|
|
914
|
+
}
|
|
915
|
+
finally {
|
|
916
|
+
fs.closeSync(fd);
|
|
917
|
+
}
|
|
918
|
+
registerFileIntegrity(file);
|
|
919
|
+
}
|
|
920
|
+
function projectReadTrusted(file) {
|
|
921
|
+
projectNoLinks(file);
|
|
922
|
+
const verified = verifyFileIntegrity(file, { restoreOnFail: false, requireRegistered: true });
|
|
923
|
+
if (verified.status !== 'verified' || !verified.bytes) {
|
|
924
|
+
throw projectChangeError('INTEGRITY_FAILED', 'Project operation record failed integrity validation');
|
|
925
|
+
}
|
|
926
|
+
return JSON.parse(verified.bytes.toString('utf8'));
|
|
927
|
+
}
|
|
928
|
+
function projectNoLinks(file) {
|
|
929
|
+
let current = path.resolve(file);
|
|
930
|
+
for (;;) {
|
|
931
|
+
const stat = fs.lstatSync(current, { throwIfNoEntry: false });
|
|
932
|
+
if (stat?.isSymbolicLink())
|
|
933
|
+
throw projectChangeError('PATH_CONFLICT', 'Symbolic path is not supported: ' + current);
|
|
934
|
+
const parent = path.dirname(current);
|
|
935
|
+
if (parent === current)
|
|
936
|
+
break;
|
|
937
|
+
current = parent;
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
async function projectStamp(file) {
|
|
941
|
+
projectNoLinks(file);
|
|
942
|
+
const stat = fs.statSync(file, { throwIfNoEntry: false });
|
|
943
|
+
if (!stat)
|
|
944
|
+
return null;
|
|
945
|
+
if (!stat.isFile())
|
|
946
|
+
throw projectChangeError('PATH_CONFLICT', 'Expected a regular file: ' + file);
|
|
947
|
+
const { createHash } = await import('node:crypto');
|
|
948
|
+
const hash = createHash('sha256');
|
|
949
|
+
for await (const bytes of fs.createReadStream(file))
|
|
950
|
+
hash.update(bytes);
|
|
951
|
+
const after = fs.statSync(file);
|
|
952
|
+
if (after.size !== stat.size || after.mtimeMs !== stat.mtimeMs) {
|
|
953
|
+
throw projectChangeError('SOURCE_CHANGED', 'File changed while reading: ' + file);
|
|
954
|
+
}
|
|
955
|
+
return { sha256: hash.digest('hex'), size: stat.size, mode: stat.mode & 0o777, mtimeMs: stat.mtimeMs };
|
|
956
|
+
}
|
|
957
|
+
function projectEqual(a, b) {
|
|
958
|
+
return a === null || b === null ? a === b
|
|
959
|
+
: a.sha256 === b.sha256 && a.size === b.size && a.mode === b.mode && Math.abs(a.mtimeMs - b.mtimeMs) < 1;
|
|
960
|
+
}
|
|
961
|
+
function projectInside(root, file) {
|
|
962
|
+
const relative = path.relative(root, file);
|
|
963
|
+
return !relative || relative !== '..' && !relative.startsWith('..' + path.sep) && !path.isAbsolute(relative);
|
|
964
|
+
}
|
|
965
|
+
async function projectWalk(root, directories) {
|
|
966
|
+
projectNoLinks(root);
|
|
967
|
+
if (!fs.existsSync(root))
|
|
968
|
+
return [];
|
|
969
|
+
directories?.push(root);
|
|
970
|
+
const result = [];
|
|
971
|
+
for (const entry of await fs.promises.readdir(root, { withFileTypes: true })) {
|
|
972
|
+
const file = path.join(root, entry.name);
|
|
973
|
+
if (entry.isDirectory())
|
|
974
|
+
result.push(...await projectWalk(file, directories));
|
|
975
|
+
else if (entry.isFile())
|
|
976
|
+
result.push(file);
|
|
977
|
+
else
|
|
978
|
+
throw projectChangeError('PATH_CONFLICT', 'Unsupported project entry: ' + file);
|
|
979
|
+
}
|
|
980
|
+
return result.sort();
|
|
981
|
+
}
|
|
982
|
+
export function readAgentProjectChange(aid, planId, actor) {
|
|
983
|
+
const gate = agentProjectChangeGate(aid);
|
|
984
|
+
const anchor = gate?.planId === planId ? gate.anchorAid ?? aid : aid;
|
|
985
|
+
const value = projectReadTrusted(projectChangeFile(anchor, planId));
|
|
986
|
+
if (value.version !== 1 || value.aid !== anchor || value.planId !== planId || actor && value.actor !== actor
|
|
987
|
+
|| anchor !== aid && !value.affectedAids?.includes(aid)) {
|
|
988
|
+
throw projectChangeError('NOT_ALLOWED', 'Project plan does not belong to this Agent and actor');
|
|
989
|
+
}
|
|
990
|
+
return value;
|
|
991
|
+
}
|
|
992
|
+
export function agentProjectChangeView(plan) {
|
|
993
|
+
if (plan.revision === 2)
|
|
994
|
+
return projectRevisionView(plan);
|
|
995
|
+
return { aid: plan.aid, source: plan.source, target: plan.target, status: plan.status,
|
|
996
|
+
executable: !plan.conflicts.length, conflicts: plan.conflicts, fileCount: plan.files.length,
|
|
997
|
+
sessionCount: plan.sessions, bytes: plan.bytes, ...(plan.error ? { error: plan.error } : {}) };
|
|
998
|
+
}
|
|
999
|
+
export function agentProjectChangeGate(aid) {
|
|
1000
|
+
const file = path.join(projectChangeDirectory(aid), 'gate.json');
|
|
1001
|
+
try {
|
|
1002
|
+
if (!fs.existsSync(file))
|
|
1003
|
+
return null;
|
|
1004
|
+
const gate = projectReadTrusted(file);
|
|
1005
|
+
if (!/^project_[0-9a-f-]{36}$/.test(gate.planId) || !['recovery', 'stopped'].includes(gate.state)
|
|
1006
|
+
|| gate.anchorAid !== undefined && !isValidAid(gate.anchorAid)) {
|
|
1007
|
+
throw new Error('Invalid project change gate');
|
|
1008
|
+
}
|
|
1009
|
+
return gate;
|
|
1010
|
+
}
|
|
1011
|
+
catch (error) {
|
|
1012
|
+
if (error.code === 'ENOENT')
|
|
1013
|
+
return null;
|
|
1014
|
+
throw projectChangeError('PROJECT_RECOVERY_REQUIRED', 'Cannot read project change state for ' + aid);
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
export function assertAgentProjectChangeReady(aid, allowStopped = false) {
|
|
1018
|
+
const gate = agentProjectChangeGate(aid);
|
|
1019
|
+
if (gate && (gate.state === 'recovery' || !allowStopped)) {
|
|
1020
|
+
throw projectChangeError('PROJECT_RECOVERY_REQUIRED', gate.state === 'recovery'
|
|
1021
|
+
? 'Recover the original project directory before starting this Agent'
|
|
1022
|
+
: 'Project change completed; explicitly start this Agent through its lifecycle operation');
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
1025
|
+
export function acknowledgeAgentProjectStart(aid) {
|
|
1026
|
+
assertAgentProjectChangeReady(aid, true);
|
|
1027
|
+
fs.rmSync(path.join(projectChangeDirectory(aid), 'gate.json'), { force: true });
|
|
1028
|
+
}
|
|
1029
|
+
const PROJECT_PHASES = ['checking', 'freezing', 'preparing', 'copying', 'sessions', 'committing', 'finalizing'];
|
|
1030
|
+
const projectSame = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
|
1031
|
+
const projectBinding = (meta) => ({ projectPath: meta?.projectPath, baseagent: meta?.baseagent,
|
|
1032
|
+
agentSessionId: meta?.agentSessionId ?? null, selfAID: meta?.selfAID ?? null, id: meta?.id });
|
|
1033
|
+
export function saveAgentProjectChange(plan) {
|
|
1034
|
+
plan.updatedAt = Date.now();
|
|
1035
|
+
projectPersist(projectChangeFile(plan.aid, plan.planId), plan);
|
|
1036
|
+
}
|
|
1037
|
+
export function advanceAgentProjectChange(plan, step) {
|
|
1038
|
+
if (plan.status === 'preview')
|
|
1039
|
+
plan.status = 'running';
|
|
1040
|
+
for (const row of plan.steps ?? [])
|
|
1041
|
+
if (row.state === 'in_progress')
|
|
1042
|
+
row.state = 'done';
|
|
1043
|
+
plan.currentStep = step;
|
|
1044
|
+
plan.currentPhase = PROJECT_PHASES[step - 1];
|
|
1045
|
+
const existing = plan.steps?.find(row => row.phase === plan.currentPhase);
|
|
1046
|
+
if (existing)
|
|
1047
|
+
existing.state = 'in_progress';
|
|
1048
|
+
else
|
|
1049
|
+
(plan.steps ??= []).push({ phase: plan.currentPhase, state: 'in_progress', ts: Date.now() });
|
|
1050
|
+
saveAgentProjectChange(plan);
|
|
1051
|
+
}
|
|
1052
|
+
function projectGroupActive(plan, group) {
|
|
1053
|
+
const aid = group.startsWith('agent:') ? group.slice(6) : plan.groups?.[group]?.aid;
|
|
1054
|
+
return !!aid && !plan.skippedAgents?.includes(aid) && !plan.skippedGroups?.includes(group);
|
|
1055
|
+
}
|
|
1056
|
+
function projectResourceActive(plan, resource) {
|
|
1057
|
+
return resource.groups.length ? resource.groups.some(group => projectGroupActive(plan, group))
|
|
1058
|
+
: (plan.affectedAids ?? [plan.aid]).some(aid => !plan.skippedAgents?.includes(aid));
|
|
1059
|
+
}
|
|
1060
|
+
function projectRevisionView(plan) {
|
|
1061
|
+
const resources = plan.resources ?? [];
|
|
1062
|
+
return { aid: plan.aid, source: plan.source, target: plan.target, status: plan.status,
|
|
1063
|
+
executable: !plan.conflicts.length, conflicts: plan.conflicts,
|
|
1064
|
+
relatedAgents: plan.relatedAgents ?? [], affectedAids: plan.affectedAids ?? [plan.aid],
|
|
1065
|
+
currentStep: plan.currentStep ?? 0, totalSteps: 7, currentPhase: plan.currentPhase ?? null,
|
|
1066
|
+
steps: plan.steps ?? [], updatedAt: plan.updatedAt ?? null,
|
|
1067
|
+
fileCount: resources.filter(row => row.kind === 'project').length, sessionCount: Object.keys(plan.groups ?? {}).length,
|
|
1068
|
+
bytes: plan.bytes, sourceRetained: true,
|
|
1069
|
+
noneMigrated: plan.status === 'succeeded' && plan.affectedAids.every(aid => plan.skippedAgents?.includes(aid)),
|
|
1070
|
+
results: (plan.affectedAids ?? [plan.aid]).map(aid => ({ aid,
|
|
1071
|
+
status: plan.skippedAgents?.includes(aid) ? 'skipped' : plan.status === 'succeeded' ? 'migrated' : 'pending',
|
|
1072
|
+
projectPath: resolveProjectDefaultPath(resolveEffective({ self: aid }, { cache: false }).projects?.defaultPath) ?? null })),
|
|
1073
|
+
skippedSessions: Object.entries(plan.groups ?? {}).filter(([id, group]) => plan.skippedGroups?.includes(id)
|
|
1074
|
+
|| plan.skippedAgents?.includes(group.aid)).map(([, group]) => group),
|
|
1075
|
+
skippedFiles: resources.filter(row => row.state === 'skipped' && ['project', 'directory', 'issue'].includes(row.kind)).map(row => row.path),
|
|
1076
|
+
warnings: plan.warnings ?? [], ...(plan.pendingConflict ? { conflict: plan.pendingConflict } : {}),
|
|
1077
|
+
...(plan.error ? { error: plan.error } : {}) };
|
|
1078
|
+
}
|
|
1079
|
+
export function registerAgentProjectChange(plan) {
|
|
1080
|
+
saveAgentProjectChange(plan);
|
|
1081
|
+
projectPersist(path.join(projectChangeDirectory(plan.aid), 'latest.json'), { planId: plan.planId });
|
|
1082
|
+
for (const aid of plan.protectedAids ?? plan.affectedAids ?? [plan.aid]) {
|
|
1083
|
+
const gate = agentProjectChangeGate(aid);
|
|
1084
|
+
if (gate?.state === 'recovery' && gate.planId !== plan.planId)
|
|
1085
|
+
throw projectChangeError('PROJECT_RECOVERY_REQUIRED', 'Another migration owns ' + aid);
|
|
1086
|
+
}
|
|
1087
|
+
for (const aid of plan.protectedAids ?? plan.affectedAids ?? [plan.aid])
|
|
1088
|
+
projectPersist(path.join(projectChangeDirectory(aid), 'gate.json'), { planId: plan.planId, anchorAid: plan.aid, state: 'recovery' });
|
|
1089
|
+
}
|
|
1090
|
+
export function latestAgentProjectChange(aid) {
|
|
1091
|
+
const gate = agentProjectChangeGate(aid);
|
|
1092
|
+
if (gate)
|
|
1093
|
+
return readAgentProjectChange(aid, gate.planId);
|
|
1094
|
+
const file = path.join(projectChangeDirectory(aid), 'latest.json');
|
|
1095
|
+
if (!fs.existsSync(file))
|
|
1096
|
+
return undefined;
|
|
1097
|
+
return readAgentProjectChange(aid, projectReadTrusted(file).planId);
|
|
1098
|
+
}
|
|
1099
|
+
export function suspendAgentProjectIssue(plan) {
|
|
1100
|
+
const row = plan.resources.find(row => row.kind === 'issue' && row.state === 'pending' && projectResourceActive(plan, row));
|
|
1101
|
+
if (!row?.issue)
|
|
1102
|
+
return false;
|
|
1103
|
+
projectAsk(plan, row, row.issue.code, row.issue.reason, row.issue.scope);
|
|
1104
|
+
return true;
|
|
1105
|
+
}
|
|
1106
|
+
function projectFinishGates(plan) {
|
|
1107
|
+
for (const aid of plan.protectedAids ?? plan.affectedAids ?? [plan.aid]) {
|
|
1108
|
+
if (plan.skippedAgents?.includes(aid)) {
|
|
1109
|
+
if (agentProjectChangeGate(aid)?.planId === plan.planId)
|
|
1110
|
+
fs.rmSync(path.join(projectChangeDirectory(aid), 'gate.json'), { force: true });
|
|
1111
|
+
}
|
|
1112
|
+
else
|
|
1113
|
+
projectPersist(path.join(projectChangeDirectory(aid), 'gate.json'), { planId: plan.planId, anchorAid: plan.aid, state: 'stopped' });
|
|
1114
|
+
}
|
|
1115
|
+
}
|
|
1116
|
+
export function addAgentProjectIssue(plan, key, file, groups, code, reason, scope) {
|
|
1117
|
+
const existing = plan.resources?.find(row => row.key === key);
|
|
1118
|
+
if (existing)
|
|
1119
|
+
existing.groups = [...new Set([...existing.groups, ...groups])];
|
|
1120
|
+
else
|
|
1121
|
+
(plan.resources ??= []).push({ key, kind: 'issue', path: file,
|
|
1122
|
+
groups, state: 'pending', issue: { code, reason, scope } });
|
|
1123
|
+
}
|
|
1124
|
+
function projectAsk(plan, resource, code, reason, scope, current, expected) {
|
|
1125
|
+
const groups = resource.groups.map(id => plan.groups?.[id]).filter(Boolean);
|
|
1126
|
+
const aids = [...new Set([...groups.map(group => group.aid), ...resource.groups.filter(id => id.startsWith('agent:')).map(id => id.slice(6))])];
|
|
1127
|
+
plan.status = 'awaiting_decision';
|
|
1128
|
+
plan.error = reason;
|
|
1129
|
+
plan.pendingConflict = { id: 'conflict_' + crypto.randomUUID(), code, reason, resource: resource.path,
|
|
1130
|
+
resourceKey: resource.key, scope, aids: aids.length ? aids : plan.affectedAids, sessions: groups.map(group => group.sessionId),
|
|
1131
|
+
skipEffect: scope === 'agent' ? '排除该 Agent,保留当前配置并恢复本次修改'
|
|
1132
|
+
: scope === 'session' ? '跳过整组会话及其绑定迁移,保留原绑定;不会修复原有损坏'
|
|
1133
|
+
: scope === 'all' ? '排除全部迁移对象,不向无效目标写入'
|
|
1134
|
+
: scope === 'optional' ? '跳过该可选索引更新,保留原记录' : '跳过该文件或目录子树,保留源数据和目标现有数据',
|
|
1135
|
+
...(current !== undefined ? { current } : {}), ...(expected !== undefined ? { expected } : {}) };
|
|
1136
|
+
saveAgentProjectChange(plan);
|
|
1137
|
+
}
|
|
1138
|
+
/** Read-only discovery includes historical project references, not only Agent defaults. */
|
|
1139
|
+
export function relatedAgentProjects(source) {
|
|
1140
|
+
const result = new Map();
|
|
1141
|
+
for (const agent of loadAllAgents().agents) {
|
|
1142
|
+
const project = resolveProjectDefaultPath(resolveEffective({ self: agent.aid }, { cache: false }).projects?.defaultPath);
|
|
1143
|
+
result.set(agent.aid, { aid: agent.aid, defaultProject: !!project && path.resolve(project) === source, sessionCount: 0 });
|
|
1144
|
+
}
|
|
1145
|
+
const { scanChatDirs, scanMetaFiles, readLastJsonlLineStrict } = projectSessionStore;
|
|
1146
|
+
const seen = new Set();
|
|
1147
|
+
for (const chat of scanChatDirs(resolvePaths().sessionsDir)) {
|
|
1148
|
+
for (const name of [...scanMetaFiles(chat.dirPath), 'active.json']) {
|
|
1149
|
+
const file = path.join(chat.dirPath, name);
|
|
1150
|
+
if (!fs.existsSync(file))
|
|
1151
|
+
continue;
|
|
1152
|
+
let meta;
|
|
1153
|
+
try {
|
|
1154
|
+
meta = name === 'active.json' ? JSON.parse(fs.readFileSync(file, 'utf8')) : readLastJsonlLineStrict(file);
|
|
1155
|
+
}
|
|
1156
|
+
catch {
|
|
1157
|
+
continue;
|
|
1158
|
+
}
|
|
1159
|
+
const owner = [...result.keys()].find(aid => projectInside(agentDir(aid), file));
|
|
1160
|
+
if (!owner || !meta?.projectPath || path.resolve(meta.projectPath) !== source)
|
|
1161
|
+
continue;
|
|
1162
|
+
const key = owner + ':' + meta.id;
|
|
1163
|
+
if (!seen.has(key)) {
|
|
1164
|
+
result.get(owner).sessionCount++;
|
|
1165
|
+
seen.add(key);
|
|
1166
|
+
}
|
|
1167
|
+
}
|
|
1168
|
+
}
|
|
1169
|
+
return [...result.values()].filter(row => row.defaultProject || row.sessionCount);
|
|
1170
|
+
}
|
|
1171
|
+
export async function previewAgentProjectChange(options) {
|
|
1172
|
+
const source = path.resolve(options.currentProject), target = path.resolve(options.target);
|
|
1173
|
+
const aids = [...new Set(options.aids ?? [options.aid])].sort();
|
|
1174
|
+
if (![options.currentProject, options.target].every(value => path.isAbsolute(value) && !value.includes('\0'))
|
|
1175
|
+
|| !aids.length || !aids.every(isValidAid) || !isValidAid(options.aid))
|
|
1176
|
+
throw projectChangeError('INVALID_ARGUMENT', 'Absolute paths and valid selected AIDs required');
|
|
1177
|
+
for (const value of [source, target])
|
|
1178
|
+
projectNoLinks(value);
|
|
1179
|
+
if (projectInside(source, target) || projectInside(target, source))
|
|
1180
|
+
throw projectChangeError('PATH_CONFLICT', 'Source and target must be distinct, non-nested directories');
|
|
1181
|
+
const root = resolvePaths().root;
|
|
1182
|
+
for (const value of [source, target]) {
|
|
1183
|
+
if (projectInside(value, root) || ['agents', 'AIDs', 'data', 'logs', 'backups', 'eck', 'kits', 'node_modules']
|
|
1184
|
+
.some(name => projectInside(path.join(root, name), value)))
|
|
1185
|
+
throw projectChangeError('PATH_CONFLICT', 'Project overlaps protected runtime data');
|
|
1186
|
+
for (const native of [path.join(os.homedir(), '.claude'), process.env.CODEX_HOME || path.join(os.homedir(), '.codex'), path.join(os.homedir(), '.gemini')]) {
|
|
1187
|
+
if (projectInside(native, value) || projectInside(value, native))
|
|
1188
|
+
throw projectChangeError('PATH_CONFLICT', 'Project overlaps backend data');
|
|
1189
|
+
}
|
|
1190
|
+
}
|
|
1191
|
+
if (!fs.statSync(source).isDirectory())
|
|
1192
|
+
throw projectChangeError('PATH_CONFLICT', 'Source must be a directory');
|
|
1193
|
+
const related = relatedAgentProjects(source);
|
|
1194
|
+
if (aids.some(aid => !related.some(row => row.aid === aid)))
|
|
1195
|
+
throw projectChangeError('INVALID_ARGUMENT', 'Selected Agent no longer references the source project');
|
|
1196
|
+
const plan = { version: 1, revision: 2, planId: 'project_' + crypto.randomUUID(), aid: options.aid,
|
|
1197
|
+
actor: options.actor, source, target, status: 'preview', affectedAids: aids, relatedAgents: related,
|
|
1198
|
+
skippedAgents: [], skippedGroups: [], groups: {}, resources: [], steps: [], warnings: [],
|
|
1199
|
+
conflicts: [], files: [], sql: [], sources: {}, cleanup: [], directories: [], backups: {}, sessions: 0, bytes: 0 };
|
|
1200
|
+
if (!options.deferInventory)
|
|
1201
|
+
await prepareAgentProjectChange(plan);
|
|
1202
|
+
return plan;
|
|
1203
|
+
}
|
|
1204
|
+
export async function prepareAgentProjectChange(plan) {
|
|
1205
|
+
if (plan.inventoryReady)
|
|
1206
|
+
return;
|
|
1207
|
+
const resources = plan.resources;
|
|
1208
|
+
const add = (row) => {
|
|
1209
|
+
const existing = resources.find(value => value.key === row.key);
|
|
1210
|
+
if (existing) {
|
|
1211
|
+
if (existing.from !== row.from || existing.content !== row.content || !projectSame(existing.after, row.after)) {
|
|
1212
|
+
addAgentProjectIssue(plan, 'collision:' + row.key, row.path, [...existing.groups, ...row.groups], 'C9', '不同来源映射到同一目标且期望内容不同', 'session');
|
|
1213
|
+
}
|
|
1214
|
+
else
|
|
1215
|
+
existing.groups = [...new Set([...existing.groups, ...row.groups])];
|
|
1216
|
+
}
|
|
1217
|
+
else
|
|
1218
|
+
resources.push({ ...row, state: 'pending' });
|
|
1219
|
+
};
|
|
1220
|
+
const walk = async (directory) => {
|
|
1221
|
+
let entries;
|
|
1222
|
+
try {
|
|
1223
|
+
entries = await fs.promises.readdir(directory, { withFileTypes: true });
|
|
1224
|
+
}
|
|
1225
|
+
catch (error) {
|
|
1226
|
+
if (error.code === 'ENOENT')
|
|
1227
|
+
return;
|
|
1228
|
+
const to = path.join(plan.target, path.relative(plan.source, directory));
|
|
1229
|
+
addAgentProjectIssue(plan, 'walk:' + to, to, [], 'IO_ERROR', '目录清单无法读取: ' + String(error), directory === plan.source ? 'all' : 'file');
|
|
1230
|
+
return;
|
|
1231
|
+
}
|
|
1232
|
+
const destination = path.join(plan.target, path.relative(plan.source, directory));
|
|
1233
|
+
add({ key: 'directory:' + destination, kind: 'directory', path: destination, groups: [] });
|
|
1234
|
+
for (const entry of entries) {
|
|
1235
|
+
const from = path.join(directory, entry.name), to = path.join(destination, entry.name);
|
|
1236
|
+
if (entry.isDirectory())
|
|
1237
|
+
await walk(from);
|
|
1238
|
+
else if (entry.isFile()) {
|
|
1239
|
+
add({ key: 'project:' + to, kind: 'project', path: to, from, groups: [] });
|
|
1240
|
+
try {
|
|
1241
|
+
plan.bytes += fs.statSync(from).size;
|
|
1242
|
+
}
|
|
1243
|
+
catch (error) {
|
|
1244
|
+
if (error.code !== 'ENOENT')
|
|
1245
|
+
throw error;
|
|
1246
|
+
}
|
|
1247
|
+
}
|
|
1248
|
+
else
|
|
1249
|
+
addAgentProjectIssue(plan, 'entry:' + to, to, [], 'C9', '不支持的目录项(符号链接或特殊文件),跳过后不复制该项', 'file');
|
|
1250
|
+
}
|
|
1251
|
+
};
|
|
1252
|
+
await walk(plan.source);
|
|
1253
|
+
const groups = plan.groups;
|
|
1254
|
+
const selected = new Set(plan.affectedAids);
|
|
1255
|
+
const foreign = new Set();
|
|
1256
|
+
const sessions = new Map();
|
|
1257
|
+
for (const chat of projectSessionStore.scanChatDirs(resolvePaths().sessionsDir)) {
|
|
1258
|
+
for (const name of [...projectSessionStore.scanMetaFiles(chat.dirPath), 'active.json']) {
|
|
1259
|
+
const file = path.join(chat.dirPath, name);
|
|
1260
|
+
if (!fs.existsSync(file))
|
|
1261
|
+
continue;
|
|
1262
|
+
const owner = plan.relatedAgents.find(row => projectInside(agentDir(row.aid), file))?.aid;
|
|
1263
|
+
let meta;
|
|
1264
|
+
try {
|
|
1265
|
+
meta = name === 'active.json' ? JSON.parse(fs.readFileSync(file, 'utf8')) : projectSessionStore.readLastJsonlLineStrict(file);
|
|
1266
|
+
}
|
|
1267
|
+
catch (error) {
|
|
1268
|
+
if (owner && selected.has(owner))
|
|
1269
|
+
addAgentProjectIssue(plan, 'invalid:' + file, file, ['agent:' + owner], 'C10', 'EC 会话结构无法读取: ' + String(error), 'agent');
|
|
1270
|
+
continue;
|
|
1271
|
+
}
|
|
1272
|
+
if (!owner || !meta?.projectPath || path.resolve(meta.projectPath) !== plan.source)
|
|
1273
|
+
continue;
|
|
1274
|
+
const nativeKey = meta.baseagent + ':' + meta.agentSessionId;
|
|
1275
|
+
if (!selected.has(owner)) {
|
|
1276
|
+
if (meta.agentSessionId)
|
|
1277
|
+
foreign.add(nativeKey);
|
|
1278
|
+
continue;
|
|
1279
|
+
}
|
|
1280
|
+
const group = 'session:' + owner + ':' + meta.id;
|
|
1281
|
+
groups[group] = { aid: owner, sessionId: meta.id, nativeId: meta.agentSessionId ?? undefined };
|
|
1282
|
+
if (!sessions.has(group))
|
|
1283
|
+
sessions.set(group, { aid: owner, meta, files: [] });
|
|
1284
|
+
sessions.get(group).files.push(file);
|
|
1285
|
+
if (meta.selfAID && meta.selfAID !== owner)
|
|
1286
|
+
addAgentProjectIssue(plan, 'identity:' + group, file, ['agent:' + owner], 'C2', '会话身份不属于目录所属 Agent', 'agent');
|
|
1287
|
+
if (meta.activeTask || meta.metadata?.turnState?.active)
|
|
1288
|
+
addAgentProjectIssue(plan, 'active:' + group, file, [group], 'C4', '核心会话仍有在途写入', 'session');
|
|
1289
|
+
const before = projectBinding(meta), after = { ...before, projectPath: plan.target };
|
|
1290
|
+
add({ key: 'meta:' + file, kind: 'meta', path: file, aid: owner, groups: [group], before, after });
|
|
1291
|
+
}
|
|
1292
|
+
}
|
|
1293
|
+
// Native dependencies precede EC binding updates, even when multiple Agents reference one file.
|
|
1294
|
+
const metaRows = resources.filter(row => row.kind === 'meta');
|
|
1295
|
+
plan.resources = resources.filter(row => row.kind !== 'meta');
|
|
1296
|
+
const nativeAdd = async (from, to, group, content, validatedBytes) => {
|
|
1297
|
+
const stamp = await projectStamp(from);
|
|
1298
|
+
if (!stamp)
|
|
1299
|
+
throw projectChangeError('C3', '原生会话文件缺失: ' + from);
|
|
1300
|
+
if (validatedBytes && crypto.createHash('sha256').update(validatedBytes).digest('hex') !== stamp.sha256)
|
|
1301
|
+
throw projectChangeError('C4', '原生会话在格式校验后变化: ' + from);
|
|
1302
|
+
add({ key: 'file:' + to, kind: 'file', path: to, from, stamp, groups: [group], ...(content ? { content: content.toString('base64') } : {}) });
|
|
1303
|
+
};
|
|
1304
|
+
// Keep add() bound to the same resource list while reordering in place.
|
|
1305
|
+
resources.splice(0, resources.length, ...plan.resources);
|
|
1306
|
+
plan.resources = resources;
|
|
1307
|
+
for (const [group, entry] of sessions) {
|
|
1308
|
+
const { meta, aid } = entry, id = meta.agentSessionId;
|
|
1309
|
+
if (!id || plan.skippedAgents?.includes(aid))
|
|
1310
|
+
continue;
|
|
1311
|
+
try {
|
|
1312
|
+
if (typeof id !== 'string' || !/^[a-zA-Z0-9_-]+$/.test(id))
|
|
1313
|
+
throw projectChangeError('C3', '原生会话 ID 无效');
|
|
1314
|
+
if (meta.baseagent === 'claude') {
|
|
1315
|
+
const fromDir = path.join(os.homedir(), '.claude', 'projects', encodePath(plan.source));
|
|
1316
|
+
const toDir = path.join(os.homedir(), '.claude', 'projects', encodePath(plan.target));
|
|
1317
|
+
const file = path.join(fromDir, id + '.jsonl');
|
|
1318
|
+
const bytes = fs.readFileSync(file), lines = bytes.toString('utf8').split('\n').filter(Boolean);
|
|
1319
|
+
if (!lines.length)
|
|
1320
|
+
throw new Error('Claude session is empty');
|
|
1321
|
+
for (const line of lines) {
|
|
1322
|
+
const value = JSON.parse(line);
|
|
1323
|
+
if (value.sessionId && value.sessionId !== id)
|
|
1324
|
+
throw new Error('Claude session ID mismatch');
|
|
1325
|
+
}
|
|
1326
|
+
await nativeAdd(file, path.join(toDir, id + '.jsonl'), group, undefined, bytes);
|
|
1327
|
+
for (const companion of await projectWalk(path.join(fromDir, id)))
|
|
1328
|
+
await nativeAdd(companion, path.join(toDir, id, path.relative(path.join(fromDir, id), companion)), group);
|
|
1329
|
+
}
|
|
1330
|
+
else if (meta.baseagent === 'codex') {
|
|
1331
|
+
const home = process.env.CODEX_HOME || path.join(os.homedir(), '.codex');
|
|
1332
|
+
const names = fs.existsSync(home) ? fs.readdirSync(home).filter(name => /^state_\d+\.sqlite$/.test(name))
|
|
1333
|
+
.sort((a, b) => Number(b.match(/\d+/)[0]) - Number(a.match(/\d+/)[0])) : [];
|
|
1334
|
+
const database = names[0] ? path.join(home, names[0]) : undefined;
|
|
1335
|
+
let row;
|
|
1336
|
+
if (database) {
|
|
1337
|
+
projectNoLinks(database);
|
|
1338
|
+
const { DatabaseSync } = await import('node:sqlite'), db = new DatabaseSync(database, { readOnly: true });
|
|
1339
|
+
try {
|
|
1340
|
+
row = db.prepare('SELECT cwd, rollout_path FROM threads WHERE id = ?').get(id);
|
|
1341
|
+
}
|
|
1342
|
+
finally {
|
|
1343
|
+
db.close();
|
|
1344
|
+
}
|
|
1345
|
+
}
|
|
1346
|
+
const { CodexSessionFileAdapter } = await import('./agents/codex/session-file-adapter.js');
|
|
1347
|
+
const file = row?.rollout_path ?? new CodexSessionFileAdapter(home).findSessionFile(id);
|
|
1348
|
+
if (!file)
|
|
1349
|
+
throw new Error('Codex rollout is missing');
|
|
1350
|
+
let header;
|
|
1351
|
+
await projectSessionStore.visitSessionHistoryLines(file, line => {
|
|
1352
|
+
if (!line.trim())
|
|
1353
|
+
return;
|
|
1354
|
+
const value = JSON.parse(line);
|
|
1355
|
+
if (value.type === 'session_meta')
|
|
1356
|
+
header = value.payload;
|
|
1357
|
+
});
|
|
1358
|
+
if (header?.id !== id)
|
|
1359
|
+
throw new Error('Codex rollout ID mismatch');
|
|
1360
|
+
add({ key: 'check:' + file, kind: 'check', path: file, stamp: (await projectStamp(file)), groups: [group] });
|
|
1361
|
+
if (row && database) {
|
|
1362
|
+
if (foreign.has('codex:' + id))
|
|
1363
|
+
addAgentProjectIssue(plan, 'shared:' + database + ':' + id, database, [group], 'C7', '同一 Codex 全局记录仍被未选中 Agent 使用,不能同时改到新旧目录', 'session');
|
|
1364
|
+
else
|
|
1365
|
+
add({ key: 'sqlite:' + database + ':' + id, kind: 'sqlite', path: database, rowId: id, groups: [group], before: row,
|
|
1366
|
+
after: { ...row, cwd: plan.target } });
|
|
1367
|
+
}
|
|
1368
|
+
}
|
|
1369
|
+
else if (meta.baseagent === 'gemini') {
|
|
1370
|
+
const { GeminiSessionFileAdapter } = await import('./agents/gemini/session-file-adapter.js');
|
|
1371
|
+
const file = new GeminiSessionFileAdapter().findSessionFile(plan.source, id);
|
|
1372
|
+
if (!file)
|
|
1373
|
+
throw new Error('Gemini session is missing');
|
|
1374
|
+
const sourceBytes = fs.readFileSync(file), data = JSON.parse(sourceBytes.toString('utf8'));
|
|
1375
|
+
if (data.sessionId !== id || !Array.isArray(data.messages))
|
|
1376
|
+
throw new Error('Gemini session structure mismatch');
|
|
1377
|
+
const home = path.join(os.homedir(), '.gemini'), mappingFile = path.join(home, 'projects.json');
|
|
1378
|
+
const mapping = fs.existsSync(mappingFile) ? JSON.parse(fs.readFileSync(mappingFile, 'utf8')) : {};
|
|
1379
|
+
const key = mapping.projects?.[plan.target] ?? crypto.createHash('sha256').update(plan.target).digest('hex');
|
|
1380
|
+
if (typeof key !== 'string' || !/^[a-zA-Z0-9._-]+$/.test(key))
|
|
1381
|
+
throw new Error('Gemini project key is unsupported');
|
|
1382
|
+
const destination = path.join(home, 'tmp', key);
|
|
1383
|
+
await nativeAdd(file, path.join(destination, 'chats', path.basename(file)), group, Buffer.from(JSON.stringify({ ...data, projectHash: key }) + '\n'), sourceBytes);
|
|
1384
|
+
add({ key: 'file:' + path.join(destination, '.project_root'), kind: 'file', path: path.join(destination, '.project_root'), content: Buffer.from(plan.target).toString('base64'), groups: [group] });
|
|
1385
|
+
// Gemini supports .project_root discovery; never rewrite its shared projects.json.
|
|
1386
|
+
}
|
|
1387
|
+
else if (meta.baseagent === 'ecagent') {
|
|
1388
|
+
const { EcagentSessionFileAdapter } = await import('./agents/ecagent/session-file-adapter.js');
|
|
1389
|
+
const file = new EcagentSessionFileAdapter().findSessionFile(plan.source, id, aid);
|
|
1390
|
+
if (!file)
|
|
1391
|
+
throw new Error('ecagent session is missing');
|
|
1392
|
+
const destination = path.join(agentDir(aid), 'sessions', '--' + plan.target.replace(/^[/\\]/, '').replace(/[/\\:]/g, '-') + '--');
|
|
1393
|
+
const visited = new Set();
|
|
1394
|
+
const collect = async (from, expectedId) => {
|
|
1395
|
+
if (visited.has(from))
|
|
1396
|
+
throw new Error('ecagent parent reference cycle');
|
|
1397
|
+
if (!projectInside(path.dirname(file), from))
|
|
1398
|
+
throw new Error('ecagent parent is outside the source session directory');
|
|
1399
|
+
visited.add(from);
|
|
1400
|
+
const bytes = fs.readFileSync(from), newline = bytes.indexOf(10);
|
|
1401
|
+
if (newline < 0)
|
|
1402
|
+
throw new Error('ecagent session is truncated');
|
|
1403
|
+
const header = JSON.parse(bytes.subarray(0, newline).toString('utf8'));
|
|
1404
|
+
if (expectedId && header.id !== expectedId || path.resolve(header.cwd ?? '') !== plan.source)
|
|
1405
|
+
throw new Error('ecagent session binding mismatch');
|
|
1406
|
+
for (const line of bytes.subarray(newline + 1).toString('utf8').split('\n').filter(Boolean))
|
|
1407
|
+
JSON.parse(line);
|
|
1408
|
+
if (header.parentSession) {
|
|
1409
|
+
if (typeof header.parentSession !== 'string')
|
|
1410
|
+
throw new Error('Invalid ecagent parent session');
|
|
1411
|
+
await collect(header.parentSession);
|
|
1412
|
+
header.parentSession = path.join(destination, path.basename(header.parentSession));
|
|
1413
|
+
}
|
|
1414
|
+
await nativeAdd(from, path.join(destination, path.basename(from)), group, Buffer.concat([Buffer.from(JSON.stringify({ ...header, cwd: plan.target }) + '\n'), bytes.subarray(newline + 1)]), bytes);
|
|
1415
|
+
visited.delete(from);
|
|
1416
|
+
};
|
|
1417
|
+
await collect(file, id);
|
|
1418
|
+
}
|
|
1419
|
+
else
|
|
1420
|
+
throw projectChangeError('C10', '不识别的基座: ' + meta.baseagent);
|
|
1421
|
+
}
|
|
1422
|
+
catch (error) {
|
|
1423
|
+
addAgentProjectIssue(plan, 'native:' + group, entry.files[0], [group], ['C10', 'C4'].includes(error.code) ? error.code : 'C3', '原生会话或依赖无法读取: ' + String(error), 'session');
|
|
1424
|
+
}
|
|
1425
|
+
}
|
|
1426
|
+
// Preflight every issue before changing any core dependency for its group.
|
|
1427
|
+
const issues = resources.filter(row => row.kind === 'issue');
|
|
1428
|
+
const rest = resources.filter(row => row.kind !== 'issue');
|
|
1429
|
+
resources.splice(0, resources.length, ...issues, ...rest, ...metaRows);
|
|
1430
|
+
for (const aid of plan.affectedAids) {
|
|
1431
|
+
if (!plan.relatedAgents?.find(row => row.aid === aid)?.defaultProject)
|
|
1432
|
+
continue;
|
|
1433
|
+
const config = cfgRead(ConfigTarget.Agent, { self: aid }, { cache: false });
|
|
1434
|
+
add({ key: 'config:' + aid, kind: 'config', path: agentConfigPath(aid), aid, groups: ['agent:' + aid],
|
|
1435
|
+
before: { present: Object.hasOwn(config?.projects ?? {}, 'defaultPath'), value: config?.projects?.defaultPath ?? null },
|
|
1436
|
+
after: { present: true, value: plan.target } });
|
|
1437
|
+
}
|
|
1438
|
+
plan.sessions = sessions.size;
|
|
1439
|
+
plan.inventoryReady = true;
|
|
1440
|
+
}
|
|
1441
|
+
async function projectApplyResource(plan, row) {
|
|
1442
|
+
const fail = (code, reason, scope, current, expected) => {
|
|
1443
|
+
throw Object.assign(new Error(reason), { projectConflict: { code, reason, scope, current, expected } });
|
|
1444
|
+
};
|
|
1445
|
+
if (row.issue)
|
|
1446
|
+
fail(row.issue.code, row.issue.reason, row.issue.scope);
|
|
1447
|
+
if (row.kind === 'directory') {
|
|
1448
|
+
projectNoLinks(row.path);
|
|
1449
|
+
const stat = fs.statSync(row.path, { throwIfNoEntry: false });
|
|
1450
|
+
if (stat && !stat.isDirectory())
|
|
1451
|
+
fail('C9', '目标目录被同名文件占用', row.path === plan.target ? 'all' : 'file');
|
|
1452
|
+
if (!stat)
|
|
1453
|
+
fs.mkdirSync(row.path, { recursive: true });
|
|
1454
|
+
}
|
|
1455
|
+
else if (row.kind === 'project') {
|
|
1456
|
+
projectNoLinks(row.from);
|
|
1457
|
+
projectNoLinks(row.path);
|
|
1458
|
+
const source = fs.statSync(row.from, { throwIfNoEntry: false });
|
|
1459
|
+
if (!source) {
|
|
1460
|
+
row.state = 'skipped';
|
|
1461
|
+
plan.warnings.push('源文件已删除,跳过: ' + row.from);
|
|
1462
|
+
return;
|
|
1463
|
+
}
|
|
1464
|
+
if (!source.isFile())
|
|
1465
|
+
fail('C9', '项目清单项已不是普通文件', 'file');
|
|
1466
|
+
const existing = await projectStamp(row.path);
|
|
1467
|
+
if (existing) {
|
|
1468
|
+
const hash = crypto.createHash('sha256');
|
|
1469
|
+
try {
|
|
1470
|
+
for await (const bytes of fs.createReadStream(row.from))
|
|
1471
|
+
hash.update(bytes);
|
|
1472
|
+
}
|
|
1473
|
+
catch (error) {
|
|
1474
|
+
if (error.code === 'ENOENT') {
|
|
1475
|
+
row.state = 'skipped';
|
|
1476
|
+
plan.warnings.push('源文件已删除,跳过: ' + row.from);
|
|
1477
|
+
return;
|
|
1478
|
+
}
|
|
1479
|
+
throw error;
|
|
1480
|
+
}
|
|
1481
|
+
if (hash.digest('hex') !== existing.sha256)
|
|
1482
|
+
fail('C9', '目标已存在不同内容,跳过将保留目标文件', 'file');
|
|
1483
|
+
return;
|
|
1484
|
+
}
|
|
1485
|
+
await projectPublishFile(plan, row, false);
|
|
1486
|
+
}
|
|
1487
|
+
else if (row.kind === 'file' || row.kind === 'check') {
|
|
1488
|
+
if (row.from && !projectEqual(await projectStamp(row.from), row.stamp))
|
|
1489
|
+
fail('C4', '原生会话复制期间变化', 'session');
|
|
1490
|
+
if (row.kind === 'check') {
|
|
1491
|
+
if (!row.stamp || !projectEqual(await projectStamp(row.path), row.stamp))
|
|
1492
|
+
fail('C4', '核心会话仍在变化', 'session');
|
|
1493
|
+
return;
|
|
1494
|
+
}
|
|
1495
|
+
const current = await projectStamp(row.path);
|
|
1496
|
+
const desired = row.content ? crypto.createHash('sha256').update(Buffer.from(row.content, 'base64')).digest('hex') : row.stamp.sha256;
|
|
1497
|
+
if (current) {
|
|
1498
|
+
if (current.sha256 !== desired)
|
|
1499
|
+
fail('C5', '目标存在不同的核心文件,不能覆盖或拼接', 'session');
|
|
1500
|
+
row.reused = true;
|
|
1501
|
+
row.written = current;
|
|
1502
|
+
return;
|
|
1503
|
+
}
|
|
1504
|
+
await projectPublishFile(plan, row, true);
|
|
1505
|
+
}
|
|
1506
|
+
else if (row.kind === 'config') {
|
|
1507
|
+
const { mutateConfig } = await import('./config/config-manager.js');
|
|
1508
|
+
mutateConfig(ConfigTarget.Agent, { self: row.aid }, config => {
|
|
1509
|
+
const current = { present: Object.hasOwn(config.projects ?? {}, 'defaultPath'), value: config.projects?.defaultPath ?? null };
|
|
1510
|
+
if (projectSame(current, row.after))
|
|
1511
|
+
return;
|
|
1512
|
+
if (!current.present) {
|
|
1513
|
+
const effective = resolveProjectDefaultPath(resolveEffective({ self: row.aid }, { cache: false }).projects?.defaultPath);
|
|
1514
|
+
if (!effective || path.resolve(effective) !== plan.source)
|
|
1515
|
+
fail('C1', '继承的项目路径已改变', 'agent', effective, plan.target);
|
|
1516
|
+
}
|
|
1517
|
+
if (!projectSame(current, row.before) || config.projects !== undefined && (!config.projects || typeof config.projects !== 'object' || Array.isArray(config.projects))) {
|
|
1518
|
+
fail('C1', 'Agent 项目字段已被修改,跳过将排除整个 Agent', 'agent', current, row.after);
|
|
1519
|
+
}
|
|
1520
|
+
row.changed = true;
|
|
1521
|
+
row.state = 'intent';
|
|
1522
|
+
saveAgentProjectChange(plan);
|
|
1523
|
+
config.projects = { ...(config.projects ?? {}), defaultPath: plan.target };
|
|
1524
|
+
});
|
|
1525
|
+
}
|
|
1526
|
+
else if (row.kind === 'meta') {
|
|
1527
|
+
const read = () => path.basename(row.path) === 'active.json' ? JSON.parse(fs.readFileSync(row.path, 'utf8')) : projectSessionStore.readLastJsonlLineStrict(row.path);
|
|
1528
|
+
const current = read(), binding = projectBinding(current);
|
|
1529
|
+
if (projectSame(binding, row.after))
|
|
1530
|
+
return;
|
|
1531
|
+
if (current?.activeTask || current?.metadata?.turnState?.active)
|
|
1532
|
+
fail('C4', 'EC 会话出现新的在途任务', 'session');
|
|
1533
|
+
if (!projectSame(binding, row.before))
|
|
1534
|
+
fail('C2', 'EC 会话绑定已改变,不能合并两次切换', 'session', binding, row.after);
|
|
1535
|
+
row.changed = true;
|
|
1536
|
+
row.state = 'intent';
|
|
1537
|
+
saveAgentProjectChange(plan);
|
|
1538
|
+
const next = { ...current, projectPath: plan.target };
|
|
1539
|
+
if (path.basename(row.path) === 'active.json')
|
|
1540
|
+
atomicWriteJson(row.path, next);
|
|
1541
|
+
else
|
|
1542
|
+
projectAppendMetadata(row.path, next);
|
|
1543
|
+
}
|
|
1544
|
+
else if (row.kind === 'sqlite') {
|
|
1545
|
+
const { DatabaseSync } = await import('node:sqlite'), db = new DatabaseSync(row.path);
|
|
1546
|
+
try {
|
|
1547
|
+
db.exec('BEGIN IMMEDIATE');
|
|
1548
|
+
const current = db.prepare('SELECT cwd, rollout_path FROM threads WHERE id = ?').get(row.rowId);
|
|
1549
|
+
if (!projectSame(current, row.after)) {
|
|
1550
|
+
if (!projectSame(current, row.before))
|
|
1551
|
+
fail('C6', '同一 Codex 索引记录被修改', 'session', current, row.after);
|
|
1552
|
+
row.changed = true;
|
|
1553
|
+
row.state = 'intent';
|
|
1554
|
+
saveAgentProjectChange(plan);
|
|
1555
|
+
db.prepare('UPDATE threads SET cwd = ? WHERE id = ? AND cwd = ? AND rollout_path = ?')
|
|
1556
|
+
.run(plan.target, row.rowId, row.before.cwd, row.before.rollout_path);
|
|
1557
|
+
}
|
|
1558
|
+
db.exec('COMMIT');
|
|
1559
|
+
}
|
|
1560
|
+
finally {
|
|
1561
|
+
db.close();
|
|
1562
|
+
}
|
|
1563
|
+
}
|
|
1564
|
+
}
|
|
1565
|
+
/** Publish new files without replacing data created by a concurrent writer. */
|
|
1566
|
+
async function projectPublishFile(plan, row, core) {
|
|
1567
|
+
fs.mkdirSync(path.dirname(row.path), { recursive: true });
|
|
1568
|
+
const temporary = row.path + '.project-' + plan.planId;
|
|
1569
|
+
projectNoLinks(temporary);
|
|
1570
|
+
fs.rmSync(temporary, { force: true });
|
|
1571
|
+
try {
|
|
1572
|
+
if (row.content)
|
|
1573
|
+
fs.writeFileSync(temporary, Buffer.from(row.content, 'base64'), { flag: 'wx', mode: 0o600 });
|
|
1574
|
+
else
|
|
1575
|
+
await fs.promises.copyFile(row.from, temporary, fs.constants.COPYFILE_EXCL);
|
|
1576
|
+
if (row.from) {
|
|
1577
|
+
const stat = fs.statSync(row.from, { throwIfNoEntry: false });
|
|
1578
|
+
if (stat) {
|
|
1579
|
+
fs.chmodSync(temporary, stat.mode & 0o777);
|
|
1580
|
+
fs.utimesSync(temporary, stat.atime, stat.mtime);
|
|
1581
|
+
}
|
|
1582
|
+
}
|
|
1583
|
+
const written = await projectStamp(temporary);
|
|
1584
|
+
if (core && (!written || row.from && !projectEqual(await projectStamp(row.from), row.stamp)
|
|
1585
|
+
|| !row.content && written.sha256 !== row.stamp.sha256))
|
|
1586
|
+
throw projectChangeError('C4', '核心会话复制期间变化');
|
|
1587
|
+
row.written = written;
|
|
1588
|
+
row.created = true;
|
|
1589
|
+
row.state = 'intent';
|
|
1590
|
+
saveAgentProjectChange(plan);
|
|
1591
|
+
const fd = fs.openSync(temporary, 'r');
|
|
1592
|
+
try {
|
|
1593
|
+
fs.fsyncSync(fd);
|
|
1594
|
+
}
|
|
1595
|
+
finally {
|
|
1596
|
+
fs.closeSync(fd);
|
|
1597
|
+
}
|
|
1598
|
+
projectNoLinks(row.path);
|
|
1599
|
+
try {
|
|
1600
|
+
fs.linkSync(temporary, row.path);
|
|
1601
|
+
}
|
|
1602
|
+
catch (error) {
|
|
1603
|
+
row.created = false;
|
|
1604
|
+
row.state = 'pending';
|
|
1605
|
+
throw error;
|
|
1606
|
+
}
|
|
1607
|
+
}
|
|
1608
|
+
catch (error) {
|
|
1609
|
+
if (!core && error.code === 'ENOENT' && !fs.existsSync(row.from)) {
|
|
1610
|
+
row.state = 'skipped';
|
|
1611
|
+
row.created = false;
|
|
1612
|
+
plan.warnings.push('读取期间删除,跳过: ' + row.from);
|
|
1613
|
+
return;
|
|
1614
|
+
}
|
|
1615
|
+
throw error;
|
|
1616
|
+
}
|
|
1617
|
+
finally {
|
|
1618
|
+
fs.rmSync(temporary, { force: true });
|
|
1619
|
+
}
|
|
1620
|
+
}
|
|
1621
|
+
function projectAppendMetadata(file, value) {
|
|
1622
|
+
const size = fs.statSync(file).size, fd = fs.openSync(file, 'r');
|
|
1623
|
+
const last = Buffer.alloc(1);
|
|
1624
|
+
try {
|
|
1625
|
+
if (size)
|
|
1626
|
+
fs.readSync(fd, last, 0, 1, size - 1);
|
|
1627
|
+
}
|
|
1628
|
+
finally {
|
|
1629
|
+
fs.closeSync(fd);
|
|
1630
|
+
}
|
|
1631
|
+
fs.appendFileSync(file, (size && last[0] !== 10 ? '\n' : '') + JSON.stringify(value) + '\n');
|
|
1632
|
+
}
|
|
1633
|
+
async function projectRestoreResource(plan, row) {
|
|
1634
|
+
if (!['done', 'intent'].includes(row.state))
|
|
1635
|
+
return;
|
|
1636
|
+
const conflict = () => projectChangeError('RECOVERY_CONFLICT', '恢复时发现独立修改,保留现场: ' + row.path);
|
|
1637
|
+
if (row.kind === 'file' && row.created) {
|
|
1638
|
+
const current = await projectStamp(row.path);
|
|
1639
|
+
if (current) {
|
|
1640
|
+
if (!projectEqual(current, row.written))
|
|
1641
|
+
throw conflict();
|
|
1642
|
+
fs.unlinkSync(row.path);
|
|
1643
|
+
}
|
|
1644
|
+
}
|
|
1645
|
+
else if (row.kind === 'config' && row.changed) {
|
|
1646
|
+
const { mutateConfig } = await import('./config/config-manager.js');
|
|
1647
|
+
mutateConfig(ConfigTarget.Agent, { self: row.aid }, config => {
|
|
1648
|
+
const current = { present: Object.hasOwn(config.projects ?? {}, 'defaultPath'), value: config.projects?.defaultPath ?? null };
|
|
1649
|
+
if (projectSame(current, row.before))
|
|
1650
|
+
return;
|
|
1651
|
+
if (!projectSame(current, row.after))
|
|
1652
|
+
throw conflict();
|
|
1653
|
+
if (row.before.present)
|
|
1654
|
+
config.projects.defaultPath = row.before.value;
|
|
1655
|
+
else {
|
|
1656
|
+
delete config.projects.defaultPath;
|
|
1657
|
+
if (!Object.keys(config.projects).length)
|
|
1658
|
+
delete config.projects;
|
|
1659
|
+
}
|
|
1660
|
+
});
|
|
1661
|
+
}
|
|
1662
|
+
else if (row.kind === 'meta' && row.changed) {
|
|
1663
|
+
const current = path.basename(row.path) === 'active.json' ? JSON.parse(fs.readFileSync(row.path, 'utf8')) : projectSessionStore.readLastJsonlLineStrict(row.path);
|
|
1664
|
+
if (!projectSame(projectBinding(current), row.before)) {
|
|
1665
|
+
if (!projectSame(projectBinding(current), row.after))
|
|
1666
|
+
throw conflict();
|
|
1667
|
+
const restored = { ...current, projectPath: row.before.projectPath };
|
|
1668
|
+
if (path.basename(row.path) === 'active.json')
|
|
1669
|
+
atomicWriteJson(row.path, restored);
|
|
1670
|
+
else
|
|
1671
|
+
projectAppendMetadata(row.path, restored);
|
|
1672
|
+
}
|
|
1673
|
+
}
|
|
1674
|
+
else if (row.kind === 'sqlite' && row.changed) {
|
|
1675
|
+
const { DatabaseSync } = await import('node:sqlite'), db = new DatabaseSync(row.path);
|
|
1676
|
+
try {
|
|
1677
|
+
db.exec('BEGIN IMMEDIATE');
|
|
1678
|
+
const current = db.prepare('SELECT cwd, rollout_path FROM threads WHERE id = ?').get(row.rowId);
|
|
1679
|
+
if (!projectSame(current, row.before)) {
|
|
1680
|
+
if (!projectSame(current, row.after))
|
|
1681
|
+
throw conflict();
|
|
1682
|
+
db.prepare('UPDATE threads SET cwd = ? WHERE id = ?').run(row.before.cwd, row.rowId);
|
|
1683
|
+
}
|
|
1684
|
+
db.exec('COMMIT');
|
|
1685
|
+
}
|
|
1686
|
+
finally {
|
|
1687
|
+
db.close();
|
|
1688
|
+
}
|
|
1689
|
+
}
|
|
1690
|
+
row.state = 'restored';
|
|
1691
|
+
saveAgentProjectChange(plan);
|
|
1692
|
+
}
|
|
1693
|
+
export async function resolveAgentProjectConflict(plan, conflictId, decision) {
|
|
1694
|
+
const conflict = plan.pendingConflict;
|
|
1695
|
+
if (plan.status !== 'awaiting_decision' || !conflict || conflict.id !== conflictId)
|
|
1696
|
+
throw projectChangeError('STALE_CONFLICT', 'Conflict has expired; query status');
|
|
1697
|
+
if (decision === 'abort') {
|
|
1698
|
+
await applyAgentProjectChange(plan, 'rollback');
|
|
1699
|
+
return;
|
|
1700
|
+
}
|
|
1701
|
+
const row = plan.resources.find(row => row.key === conflict.resourceKey);
|
|
1702
|
+
if (conflict.scope === 'agent' || conflict.scope === 'all') {
|
|
1703
|
+
plan.skippedAgents = [...new Set([...plan.skippedAgents, ...(conflict.scope === 'all' ? plan.affectedAids : conflict.aids)])];
|
|
1704
|
+
}
|
|
1705
|
+
else if (conflict.scope === 'session')
|
|
1706
|
+
plan.skippedGroups = [...new Set([...plan.skippedGroups, ...row.groups])];
|
|
1707
|
+
if (conflict.scope === 'file') {
|
|
1708
|
+
for (const item of plan.resources)
|
|
1709
|
+
if (['project', 'directory', 'issue'].includes(item.kind) && projectInside(row.path, item.path))
|
|
1710
|
+
item.state = 'skipped';
|
|
1711
|
+
}
|
|
1712
|
+
try {
|
|
1713
|
+
for (const item of [...plan.resources].reverse())
|
|
1714
|
+
if (item.groups.length && !projectResourceActive(plan, item))
|
|
1715
|
+
await projectRestoreResource(plan, item);
|
|
1716
|
+
for (const aid of plan.skippedAgents)
|
|
1717
|
+
if (agentProjectChangeGate(aid)?.planId === plan.planId) {
|
|
1718
|
+
fs.rmSync(path.join(projectChangeDirectory(aid), 'gate.json'), { force: true });
|
|
1719
|
+
}
|
|
1720
|
+
row.state = 'skipped';
|
|
1721
|
+
plan.warnings.push(conflict.code + ': ' + conflict.reason + ' — ' + conflict.skipEffect);
|
|
1722
|
+
delete plan.pendingConflict;
|
|
1723
|
+
delete plan.error;
|
|
1724
|
+
plan.status = 'running';
|
|
1725
|
+
saveAgentProjectChange(plan);
|
|
1726
|
+
}
|
|
1727
|
+
catch (error) {
|
|
1728
|
+
plan.status = 'paused';
|
|
1729
|
+
plan.error = String(error);
|
|
1730
|
+
saveAgentProjectChange(plan);
|
|
1731
|
+
throw error;
|
|
1732
|
+
}
|
|
1733
|
+
}
|
|
1734
|
+
export async function applyAgentProjectChange(plan, operation) {
|
|
1735
|
+
if (plan.revision !== 2)
|
|
1736
|
+
return applyLegacyAgentProjectChange(plan, operation);
|
|
1737
|
+
try {
|
|
1738
|
+
if (operation === 'rollback') {
|
|
1739
|
+
plan.status = 'running';
|
|
1740
|
+
plan.currentPhase = 'rolling_back';
|
|
1741
|
+
delete plan.pendingConflict;
|
|
1742
|
+
saveAgentProjectChange(plan);
|
|
1743
|
+
for (const row of [...plan.resources].reverse())
|
|
1744
|
+
await projectRestoreResource(plan, row);
|
|
1745
|
+
plan.status = 'rolled_back';
|
|
1746
|
+
projectFinishGates(plan);
|
|
1747
|
+
saveAgentProjectChange(plan);
|
|
1748
|
+
return;
|
|
1749
|
+
}
|
|
1750
|
+
if (plan.status === 'succeeded' || plan.status === 'rolled_back' || plan.pendingConflict)
|
|
1751
|
+
return;
|
|
1752
|
+
plan.status = 'running';
|
|
1753
|
+
for (const step of [4, 5, 6, 7]) {
|
|
1754
|
+
if ((plan.currentStep ?? 0) > step)
|
|
1755
|
+
continue;
|
|
1756
|
+
advanceAgentProjectChange(plan, step);
|
|
1757
|
+
const rows = plan.resources.filter(row => step === 4 ? ['directory', 'project'].includes(row.kind) || row.kind === 'issue' && !row.groups.length
|
|
1758
|
+
: step === 5 ? !['directory', 'project', 'config'].includes(row.kind) && !(row.kind === 'issue' && !row.groups.length)
|
|
1759
|
+
: step === 6 ? row.kind === 'config' : false);
|
|
1760
|
+
for (const row of rows) {
|
|
1761
|
+
if (['done', 'skipped', 'restored'].includes(row.state))
|
|
1762
|
+
continue;
|
|
1763
|
+
if (!projectResourceActive(plan, row)) {
|
|
1764
|
+
row.state = 'skipped';
|
|
1765
|
+
continue;
|
|
1766
|
+
}
|
|
1767
|
+
try {
|
|
1768
|
+
await projectApplyResource(plan, row);
|
|
1769
|
+
if (row.state !== 'skipped')
|
|
1770
|
+
row.state = 'done';
|
|
1771
|
+
saveAgentProjectChange(plan);
|
|
1772
|
+
}
|
|
1773
|
+
catch (error) {
|
|
1774
|
+
const detail = error.projectConflict;
|
|
1775
|
+
const scope = row.kind === 'config' ? 'agent' : row.groups.length ? 'session' : row.path === plan.target ? 'all' : 'file';
|
|
1776
|
+
projectAsk(plan, row, detail?.code ?? error.code ?? 'IO_ERROR', detail?.reason ?? String(error), detail?.scope ?? scope, detail?.current, detail?.expected);
|
|
1777
|
+
return;
|
|
1778
|
+
}
|
|
1779
|
+
}
|
|
1780
|
+
// Verify only core resources; ordinary project changes never trigger reconciliation.
|
|
1781
|
+
if (step === 7)
|
|
1782
|
+
for (const row of plan.resources.filter(row => row.state === 'done' && projectResourceActive(plan, row))) {
|
|
1783
|
+
try {
|
|
1784
|
+
let valid = true;
|
|
1785
|
+
if (row.kind === 'file')
|
|
1786
|
+
valid = !!row.written && projectEqual(await projectStamp(row.path), row.written)
|
|
1787
|
+
&& (!row.from || projectEqual(await projectStamp(row.from), row.stamp));
|
|
1788
|
+
else if (row.kind === 'check')
|
|
1789
|
+
valid = projectEqual(await projectStamp(row.path), row.stamp);
|
|
1790
|
+
else if (row.kind === 'config') {
|
|
1791
|
+
const config = cfgRead(ConfigTarget.Agent, { self: row.aid }, { cache: false });
|
|
1792
|
+
valid = config?.projects?.defaultPath === plan.target;
|
|
1793
|
+
}
|
|
1794
|
+
else if (row.kind === 'meta') {
|
|
1795
|
+
const meta = path.basename(row.path) === 'active.json' ? JSON.parse(fs.readFileSync(row.path, 'utf8')) : projectSessionStore.readLastJsonlLineStrict(row.path);
|
|
1796
|
+
valid = projectSame(projectBinding(meta), row.after);
|
|
1797
|
+
}
|
|
1798
|
+
else if (row.kind === 'sqlite') {
|
|
1799
|
+
const { DatabaseSync } = await import('node:sqlite'), db = new DatabaseSync(row.path, { readOnly: true });
|
|
1800
|
+
try {
|
|
1801
|
+
valid = projectSame(db.prepare('SELECT cwd, rollout_path FROM threads WHERE id = ?').get(row.rowId), row.after);
|
|
1802
|
+
}
|
|
1803
|
+
finally {
|
|
1804
|
+
db.close();
|
|
1805
|
+
}
|
|
1806
|
+
}
|
|
1807
|
+
if (!valid) {
|
|
1808
|
+
projectAsk(plan, row, row.kind === 'config' ? 'C1' : row.kind === 'meta' ? 'C2' : row.kind === 'sqlite' ? 'C6' : 'C4', '核心资源在提交期间变化,跳过需要恢复对应依赖', row.kind === 'config' ? 'agent' : 'session');
|
|
1809
|
+
return;
|
|
1810
|
+
}
|
|
1811
|
+
}
|
|
1812
|
+
catch (error) {
|
|
1813
|
+
projectAsk(plan, row, 'C3', '核心资源提交校验失败: ' + String(error), row.kind === 'config' ? 'agent' : 'session');
|
|
1814
|
+
return;
|
|
1815
|
+
}
|
|
1816
|
+
}
|
|
1817
|
+
}
|
|
1818
|
+
for (const step of plan.steps)
|
|
1819
|
+
if (step.state === 'in_progress')
|
|
1820
|
+
step.state = plan.warnings.length ? 'warn' : 'done';
|
|
1821
|
+
plan.status = 'succeeded';
|
|
1822
|
+
delete plan.error;
|
|
1823
|
+
projectFinishGates(plan);
|
|
1824
|
+
saveAgentProjectChange(plan);
|
|
1825
|
+
}
|
|
1826
|
+
catch (error) {
|
|
1827
|
+
plan.status = 'paused';
|
|
1828
|
+
plan.error = String(error);
|
|
1829
|
+
saveAgentProjectChange(plan);
|
|
1830
|
+
throw error;
|
|
1831
|
+
}
|
|
1832
|
+
}
|
|
1833
|
+
async function projectDesired(write, current) {
|
|
1834
|
+
if (!current)
|
|
1835
|
+
return false;
|
|
1836
|
+
const { createHash } = await import('node:crypto');
|
|
1837
|
+
const sha = write.content ? createHash('sha256').update(Buffer.from(write.content, 'base64')).digest('hex') : write.source.sha256;
|
|
1838
|
+
if (current.sha256 === sha && (!write.from || current.mode === write.source.mode))
|
|
1839
|
+
return true;
|
|
1840
|
+
if (write.config && write.content) {
|
|
1841
|
+
const original = JSON.parse(fs.readFileSync(write.path, 'utf8'));
|
|
1842
|
+
const expected = JSON.parse(Buffer.from(write.content, 'base64').toString('utf8'));
|
|
1843
|
+
return JSON.stringify(original) === JSON.stringify(expected);
|
|
1844
|
+
}
|
|
1845
|
+
return false;
|
|
1846
|
+
}
|
|
1847
|
+
async function projectCopy(from, to, stamp, token) {
|
|
1848
|
+
projectNoLinks(from);
|
|
1849
|
+
projectNoLinks(to);
|
|
1850
|
+
fs.mkdirSync(path.dirname(to), { recursive: true });
|
|
1851
|
+
const temporary = to + '.project-' + token;
|
|
1852
|
+
projectNoLinks(temporary);
|
|
1853
|
+
fs.rmSync(temporary, { force: true });
|
|
1854
|
+
try {
|
|
1855
|
+
await fs.promises.copyFile(from, temporary, fs.constants.COPYFILE_EXCL);
|
|
1856
|
+
fs.chmodSync(temporary, stamp.mode | 0o600);
|
|
1857
|
+
const fd = fs.openSync(temporary, 'r+');
|
|
1858
|
+
try {
|
|
1859
|
+
fs.fsyncSync(fd);
|
|
1860
|
+
}
|
|
1861
|
+
finally {
|
|
1862
|
+
fs.closeSync(fd);
|
|
1863
|
+
}
|
|
1864
|
+
fs.chmodSync(temporary, stamp.mode);
|
|
1865
|
+
fs.utimesSync(temporary, stamp.mtimeMs / 1000, stamp.mtimeMs / 1000);
|
|
1866
|
+
if (!projectEqual(await projectStamp(temporary), stamp)) {
|
|
1867
|
+
throw projectChangeError('INTEGRITY_FAILED', 'Copied file failed verification: ' + to);
|
|
1868
|
+
}
|
|
1869
|
+
const { atomicReplaceFile } = await import('./utils/atomic-write.js');
|
|
1870
|
+
atomicReplaceFile(temporary, to, { allowInPlaceFallback: false });
|
|
1871
|
+
}
|
|
1872
|
+
finally {
|
|
1873
|
+
fs.rmSync(temporary, { force: true });
|
|
1874
|
+
}
|
|
1875
|
+
}
|
|
1876
|
+
async function applyLegacyAgentProjectChange(plan, operation) {
|
|
1877
|
+
const planFile = projectChangeFile(plan.aid, plan.planId), directory = path.dirname(planFile);
|
|
1878
|
+
const gateFile = path.join(projectChangeDirectory(plan.aid), 'gate.json');
|
|
1879
|
+
const save = () => projectPersist(planFile, plan);
|
|
1880
|
+
const gate = agentProjectChangeGate(plan.aid);
|
|
1881
|
+
if (gate && gate.planId !== plan.planId && (gate.state === 'recovery' || operation !== 'apply')) {
|
|
1882
|
+
throw projectChangeError('PROJECT_RECOVERY_REQUIRED', 'Another project change owns this Agent');
|
|
1883
|
+
}
|
|
1884
|
+
if (operation === 'rollback' && !plan.prepared) {
|
|
1885
|
+
plan.status = 'rolled_back';
|
|
1886
|
+
save();
|
|
1887
|
+
projectPersist(gateFile, { planId: plan.planId, state: 'stopped' });
|
|
1888
|
+
return;
|
|
1889
|
+
}
|
|
1890
|
+
if (plan.status === 'rolled_back' || operation !== 'rollback' && plan.status === 'succeeded')
|
|
1891
|
+
return;
|
|
1892
|
+
if (plan.conflicts.length)
|
|
1893
|
+
throw projectChangeError('CONFLICT', 'Resolve preview conflicts before applying');
|
|
1894
|
+
projectPersist(gateFile, { planId: plan.planId, state: 'recovery' });
|
|
1895
|
+
plan.status = 'running';
|
|
1896
|
+
save();
|
|
1897
|
+
try {
|
|
1898
|
+
if (!plan.prepared) {
|
|
1899
|
+
const directories = [];
|
|
1900
|
+
const filesNow = await projectWalk(plan.source, directories);
|
|
1901
|
+
if (JSON.stringify(filesNow) !== JSON.stringify(plan.projectInventory)
|
|
1902
|
+
|| JSON.stringify(directories.sort()) !== JSON.stringify(plan.projectDirectories)) {
|
|
1903
|
+
throw projectChangeError('SOURCE_CHANGED', 'Project file inventory changed after preview');
|
|
1904
|
+
}
|
|
1905
|
+
for (const [file, stamp] of Object.entries(plan.sources)) {
|
|
1906
|
+
if (!projectEqual(await projectStamp(file), stamp))
|
|
1907
|
+
throw projectChangeError('SOURCE_CHANGED', 'Preview source changed: ' + file);
|
|
1908
|
+
}
|
|
1909
|
+
for (const write of plan.files) {
|
|
1910
|
+
if (!projectEqual(await projectStamp(write.path), write.before))
|
|
1911
|
+
throw projectChangeError('TARGET_CHANGED', 'Preview target changed: ' + write.path);
|
|
1912
|
+
}
|
|
1913
|
+
const files = [...new Set([...plan.files.map(write => write.path), ...plan.cleanup])];
|
|
1914
|
+
for (let index = 0; index < files.length; index++) {
|
|
1915
|
+
const file = files[index], stamp = await projectStamp(file);
|
|
1916
|
+
if (stamp) {
|
|
1917
|
+
const backup = path.join(directory, 'backups', String(index));
|
|
1918
|
+
await projectCopy(file, backup, stamp, plan.planId);
|
|
1919
|
+
plan.backups[file] = { file: backup, stamp };
|
|
1920
|
+
}
|
|
1921
|
+
else
|
|
1922
|
+
plan.backups[file] = null;
|
|
1923
|
+
}
|
|
1924
|
+
// A saved prepared record is the boundary before any live write.
|
|
1925
|
+
plan.prepared = true;
|
|
1926
|
+
save();
|
|
1927
|
+
}
|
|
1928
|
+
plan.status = 'running';
|
|
1929
|
+
delete plan.error;
|
|
1930
|
+
save();
|
|
1931
|
+
if (operation === 'rollback') {
|
|
1932
|
+
// Check every target before restoring anything.
|
|
1933
|
+
const expectedTarget = new Set([...(plan.targetInventory ?? []),
|
|
1934
|
+
...plan.files.flatMap(write => [write.path, write.path + '.project-' + plan.planId]).filter(file => projectInside(plan.target, file))]);
|
|
1935
|
+
if ((await projectWalk(plan.target)).some(file => !expectedTarget.has(file))) {
|
|
1936
|
+
throw projectChangeError('CONFLICT', 'Target contains new project files; preserve and resolve them before recovering the original directory');
|
|
1937
|
+
}
|
|
1938
|
+
for (const write of plan.files) {
|
|
1939
|
+
const current = await projectStamp(write.path);
|
|
1940
|
+
if (Object.hasOwn(plan.restored ?? {}, write.path)) {
|
|
1941
|
+
if (!projectEqual(current, plan.restored[write.path]))
|
|
1942
|
+
throw projectChangeError('CONFLICT', 'Restored target was independently edited: ' + write.path);
|
|
1943
|
+
continue;
|
|
1944
|
+
}
|
|
1945
|
+
const written = plan.written?.[write.path];
|
|
1946
|
+
if (!projectEqual(current, write.before) && (written ? !projectEqual(current, written) : !await projectDesired(write, current))) {
|
|
1947
|
+
throw projectChangeError('CONFLICT', 'Target was independently edited: ' + write.path);
|
|
1948
|
+
}
|
|
1949
|
+
}
|
|
1950
|
+
for (const file of plan.cleanup) {
|
|
1951
|
+
const current = await projectStamp(file), before = plan.sources[file];
|
|
1952
|
+
if (current && !projectEqual(current, before))
|
|
1953
|
+
throw projectChangeError('CONFLICT', 'Source was independently edited: ' + file);
|
|
1954
|
+
}
|
|
1955
|
+
for (const backup of Object.values(plan.backups)) {
|
|
1956
|
+
if (backup && !projectEqual(await projectStamp(backup.file), backup.stamp)) {
|
|
1957
|
+
throw projectChangeError('INTEGRITY_FAILED', 'Project backup changed');
|
|
1958
|
+
}
|
|
1959
|
+
}
|
|
1960
|
+
for (const row of plan.sql) {
|
|
1961
|
+
const { DatabaseSync } = await import('node:sqlite');
|
|
1962
|
+
const db = new DatabaseSync(row.database);
|
|
1963
|
+
try {
|
|
1964
|
+
db.exec('BEGIN IMMEDIATE');
|
|
1965
|
+
const current = db.prepare('SELECT cwd, rollout_path FROM threads WHERE id = ?').get(row.id);
|
|
1966
|
+
if (!current || ![row.before, row.after].includes(current.cwd) || current.rollout_path !== row.rolloutPath) {
|
|
1967
|
+
throw projectChangeError('CONFLICT', 'Codex thread changed');
|
|
1968
|
+
}
|
|
1969
|
+
db.prepare('UPDATE threads SET cwd = ? WHERE id = ? AND cwd = ?').run(row.before, row.id, current.cwd);
|
|
1970
|
+
db.exec('COMMIT');
|
|
1971
|
+
}
|
|
1972
|
+
finally {
|
|
1973
|
+
db.close();
|
|
1974
|
+
}
|
|
1975
|
+
}
|
|
1976
|
+
for (const [file, backup] of Object.entries(plan.backups).reverse()) {
|
|
1977
|
+
if (Object.hasOwn(plan.restored ?? {}, file)) {
|
|
1978
|
+
if (!projectEqual(await projectStamp(file), plan.restored[file]))
|
|
1979
|
+
throw projectChangeError('CONFLICT', 'Restored file changed: ' + file);
|
|
1980
|
+
continue;
|
|
1981
|
+
}
|
|
1982
|
+
if (backup) {
|
|
1983
|
+
if (!projectEqual(await projectStamp(backup.file), backup.stamp))
|
|
1984
|
+
throw projectChangeError('INTEGRITY_FAILED', 'Project backup changed');
|
|
1985
|
+
const write = plan.files.find(item => item.path === file);
|
|
1986
|
+
if (write?.config) {
|
|
1987
|
+
cfgWrite(ConfigTarget.Agent, JSON.parse(fs.readFileSync(backup.file, 'utf8')), { self: plan.aid });
|
|
1988
|
+
fs.chmodSync(file, backup.stamp.mode);
|
|
1989
|
+
}
|
|
1990
|
+
else
|
|
1991
|
+
await projectCopy(backup.file, file, backup.stamp, plan.planId);
|
|
1992
|
+
}
|
|
1993
|
+
else
|
|
1994
|
+
fs.rmSync(file, { force: true });
|
|
1995
|
+
(plan.restored ??= {})[file] = await projectStamp(file);
|
|
1996
|
+
save();
|
|
1997
|
+
}
|
|
1998
|
+
for (const [dir, metadata] of Object.entries(plan.directoryMetadata ?? {})) {
|
|
1999
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
2000
|
+
fs.chmodSync(dir, metadata.mode);
|
|
2001
|
+
fs.utimesSync(dir, metadata.mtimeMs / 1000, metadata.mtimeMs / 1000);
|
|
2002
|
+
}
|
|
2003
|
+
for (const write of plan.files) {
|
|
2004
|
+
const temporary = write.path + '.project-' + plan.planId;
|
|
2005
|
+
projectNoLinks(temporary);
|
|
2006
|
+
fs.rmSync(temporary, { force: true });
|
|
2007
|
+
}
|
|
2008
|
+
plan.status = 'rolled_back';
|
|
2009
|
+
save();
|
|
2010
|
+
for (const dir of [...plan.directories].sort((a, b) => b.length - a.length)) {
|
|
2011
|
+
try {
|
|
2012
|
+
fs.rmdirSync(dir);
|
|
2013
|
+
}
|
|
2014
|
+
catch (error) {
|
|
2015
|
+
if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error.code))
|
|
2016
|
+
throw error;
|
|
2017
|
+
}
|
|
2018
|
+
}
|
|
2019
|
+
projectPersist(gateFile, { planId: plan.planId, state: 'stopped' });
|
|
2020
|
+
return;
|
|
2021
|
+
}
|
|
2022
|
+
const targetDirectories = (plan.projectDirectories ?? [plan.source]).map(dir => path.join(plan.target, path.relative(plan.source, dir)));
|
|
2023
|
+
for (const dir of targetDirectories) {
|
|
2024
|
+
projectNoLinks(dir);
|
|
2025
|
+
if (!fs.existsSync(dir)) {
|
|
2026
|
+
if (!plan.directories.includes(dir)) {
|
|
2027
|
+
plan.directories.push(dir);
|
|
2028
|
+
save();
|
|
2029
|
+
}
|
|
2030
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
2031
|
+
}
|
|
2032
|
+
}
|
|
2033
|
+
const applyWrite = async (write) => {
|
|
2034
|
+
const current = await projectStamp(write.path);
|
|
2035
|
+
const written = plan.written?.[write.path];
|
|
2036
|
+
if (written && !projectEqual(current, written))
|
|
2037
|
+
throw projectChangeError('TARGET_CHANGED', 'Previously written target changed: ' + write.path);
|
|
2038
|
+
if (await projectDesired(write, current)) {
|
|
2039
|
+
const temporary = write.path + '.project-' + plan.planId;
|
|
2040
|
+
projectNoLinks(temporary);
|
|
2041
|
+
fs.rmSync(temporary, { force: true });
|
|
2042
|
+
(plan.written ??= {})[write.path] = current;
|
|
2043
|
+
save();
|
|
2044
|
+
return;
|
|
2045
|
+
}
|
|
2046
|
+
if (!projectEqual(current, write.before))
|
|
2047
|
+
throw projectChangeError('TARGET_CHANGED', 'Target changed: ' + write.path);
|
|
2048
|
+
if (write.from && !projectEqual(await projectStamp(write.from), write.source)) {
|
|
2049
|
+
throw projectChangeError('SOURCE_CHANGED', 'Source changed: ' + write.from);
|
|
2050
|
+
}
|
|
2051
|
+
let parent = path.dirname(write.path);
|
|
2052
|
+
const missing = [];
|
|
2053
|
+
while (!fs.existsSync(parent)) {
|
|
2054
|
+
missing.push(parent);
|
|
2055
|
+
parent = path.dirname(parent);
|
|
2056
|
+
}
|
|
2057
|
+
for (const dir of missing.reverse())
|
|
2058
|
+
if (!plan.directories.includes(dir))
|
|
2059
|
+
plan.directories.push(dir);
|
|
2060
|
+
save();
|
|
2061
|
+
fs.mkdirSync(path.dirname(write.path), { recursive: true });
|
|
2062
|
+
if (write.config) {
|
|
2063
|
+
cfgWrite(ConfigTarget.Agent, JSON.parse(Buffer.from(write.content, 'base64').toString('utf8')), { self: plan.aid });
|
|
2064
|
+
if (write.before)
|
|
2065
|
+
fs.chmodSync(write.path, write.before.mode);
|
|
2066
|
+
}
|
|
2067
|
+
else if (write.from)
|
|
2068
|
+
await projectCopy(write.from, write.path, write.source, plan.planId);
|
|
2069
|
+
else {
|
|
2070
|
+
const { atomicWrite } = await import('./utils/atomic-write.js');
|
|
2071
|
+
atomicWrite(write.path, Buffer.from(write.content, 'base64').toString('utf8'));
|
|
2072
|
+
fs.chmodSync(write.path, write.before?.mode ?? 0o600);
|
|
2073
|
+
}
|
|
2074
|
+
const stamp = await projectStamp(write.path);
|
|
2075
|
+
if (!await projectDesired(write, stamp))
|
|
2076
|
+
throw projectChangeError('INTEGRITY_FAILED', 'Written target failed verification: ' + write.path);
|
|
2077
|
+
(plan.written ??= {})[write.path] = stamp;
|
|
2078
|
+
save();
|
|
2079
|
+
};
|
|
2080
|
+
for (const write of plan.files.filter(write => !write.config))
|
|
2081
|
+
await applyWrite(write);
|
|
2082
|
+
for (const row of plan.sql) {
|
|
2083
|
+
const { DatabaseSync } = await import('node:sqlite');
|
|
2084
|
+
const db = new DatabaseSync(row.database);
|
|
2085
|
+
try {
|
|
2086
|
+
db.exec('BEGIN IMMEDIATE');
|
|
2087
|
+
const current = db.prepare('SELECT cwd, rollout_path FROM threads WHERE id = ?').get(row.id);
|
|
2088
|
+
if (!current || ![row.before, row.after].includes(current.cwd) || current.rollout_path !== row.rolloutPath) {
|
|
2089
|
+
throw projectChangeError('TARGET_CHANGED', 'Codex thread changed');
|
|
2090
|
+
}
|
|
2091
|
+
db.prepare('UPDATE threads SET cwd = ? WHERE id = ? AND cwd = ?').run(row.after, row.id, current.cwd);
|
|
2092
|
+
db.exec('COMMIT');
|
|
2093
|
+
}
|
|
2094
|
+
finally {
|
|
2095
|
+
db.close();
|
|
2096
|
+
}
|
|
2097
|
+
}
|
|
2098
|
+
for (const write of plan.files.filter(write => write.config))
|
|
2099
|
+
await applyWrite(write);
|
|
2100
|
+
for (const [file, stamp] of Object.entries(plan.written ?? {})) {
|
|
2101
|
+
if (!projectEqual(await projectStamp(file), stamp))
|
|
2102
|
+
throw projectChangeError('TARGET_CHANGED', 'Written target changed before commit: ' + file);
|
|
2103
|
+
}
|
|
2104
|
+
for (const [file, stamp] of Object.entries(plan.sources)) {
|
|
2105
|
+
if (projectInside(plan.target, file) && !plan.written?.[file] && !projectEqual(await projectStamp(file), stamp)) {
|
|
2106
|
+
throw projectChangeError('TARGET_CHANGED', 'Reused target changed before commit: ' + file);
|
|
2107
|
+
}
|
|
2108
|
+
}
|
|
2109
|
+
for (const [dir, metadata] of Object.entries(plan.directoryMetadata ?? {})) {
|
|
2110
|
+
const destination = path.join(plan.target, path.relative(plan.source, dir));
|
|
2111
|
+
if (plan.directories.includes(destination)) {
|
|
2112
|
+
fs.chmodSync(destination, metadata.mode);
|
|
2113
|
+
fs.utimesSync(destination, metadata.mtimeMs / 1000, metadata.mtimeMs / 1000);
|
|
2114
|
+
}
|
|
2115
|
+
}
|
|
2116
|
+
plan.applied = true;
|
|
2117
|
+
save();
|
|
2118
|
+
const remainingDirectories = [];
|
|
2119
|
+
if ((await projectWalk(plan.source, remainingDirectories)).some(file => !plan.projectInventory?.includes(file))
|
|
2120
|
+
|| remainingDirectories.some(dir => !plan.projectDirectories?.includes(dir))) {
|
|
2121
|
+
throw projectChangeError('SOURCE_CHANGED', 'New project files appeared during migration');
|
|
2122
|
+
}
|
|
2123
|
+
// Never recursively remove a source directory: an independently created file must survive.
|
|
2124
|
+
for (const file of plan.cleanup) {
|
|
2125
|
+
const current = await projectStamp(file);
|
|
2126
|
+
if (current && (!projectEqual(current, plan.sources[file]) || current.mtimeMs !== plan.sources[file].mtimeMs)) {
|
|
2127
|
+
throw projectChangeError('SOURCE_CHANGED', 'Source changed before cleanup: ' + file);
|
|
2128
|
+
}
|
|
2129
|
+
fs.rmSync(file, { force: true });
|
|
2130
|
+
}
|
|
2131
|
+
const directories = new Set([...plan.cleanup.map(file => path.dirname(file)),
|
|
2132
|
+
...(plan.projectDirectories ?? [])]);
|
|
2133
|
+
for (const dir of [...directories].sort((a, b) => b.length - a.length)) {
|
|
2134
|
+
let current = dir;
|
|
2135
|
+
while (current !== path.dirname(current) && (projectInside(plan.source, current) || plan.cleanup.some(file => path.dirname(file) === current))) {
|
|
2136
|
+
try {
|
|
2137
|
+
fs.rmdirSync(current);
|
|
2138
|
+
}
|
|
2139
|
+
catch (error) {
|
|
2140
|
+
if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error.code))
|
|
2141
|
+
throw error;
|
|
2142
|
+
break;
|
|
2143
|
+
}
|
|
2144
|
+
if (current === plan.source)
|
|
2145
|
+
break;
|
|
2146
|
+
current = path.dirname(current);
|
|
2147
|
+
}
|
|
2148
|
+
}
|
|
2149
|
+
plan.status = 'succeeded';
|
|
2150
|
+
save();
|
|
2151
|
+
projectPersist(gateFile, { planId: plan.planId, state: 'stopped' });
|
|
2152
|
+
}
|
|
2153
|
+
catch (error) {
|
|
2154
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
2155
|
+
plan.status = 'paused';
|
|
2156
|
+
plan.error = reason;
|
|
2157
|
+
save();
|
|
2158
|
+
if (operation === 'apply') {
|
|
2159
|
+
try {
|
|
2160
|
+
await applyLegacyAgentProjectChange(plan, 'rollback');
|
|
2161
|
+
plan.error = reason;
|
|
2162
|
+
save();
|
|
2163
|
+
}
|
|
2164
|
+
catch (rollbackError) {
|
|
2165
|
+
plan.status = 'paused';
|
|
2166
|
+
plan.error = reason + '; recovery required: ' + String(rollbackError);
|
|
2167
|
+
save();
|
|
2168
|
+
}
|
|
2169
|
+
}
|
|
2170
|
+
throw error;
|
|
2171
|
+
}
|
|
2172
|
+
}
|