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