@joripspace/cli 0.5.0 → 0.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/bin/joripspace.js +1623 -1610
- package/lib/checkpoint-commands.js +210 -210
- package/lib/deploy-files.js +245 -245
- package/lib/deployment-error.js +14 -14
- package/lib/github-commands.js +185 -0
- package/lib/help.js +138 -137
- package/lib/installer-args.js +28 -28
- package/lib/installer-target.js +134 -134
- package/lib/mcp-config.js +981 -981
- package/lib/project-env.js +198 -198
- package/lib/project-paths.js +257 -257
- package/lib/remote-commands.js +392 -392
- package/lib/start-command.js +123 -123
- package/lib/start.js +1467 -1407
- package/lib/template-commands.js +812 -812
- package/package.json +1 -1
- package/vendor/core/github-workflow.cjs +199 -186
- package/vendor/core/onboarding.cjs +2404 -2403
- package/vendor/core/template-publish-workflow.cjs +169 -169
- package/vendor/templates/index.js +104 -104
- package/vendor/templates/templates/basic-worker/files/worker.js +9 -9
- package/vendor/templates/templates/basic-worker/manifest.json +14 -14
- package/vendor/templates/templates/r2-file-api/files/worker.js +42 -42
- package/vendor/templates/templates/r2-file-api/manifest.json +7 -7
package/lib/start.js
CHANGED
|
@@ -1,1411 +1,1471 @@
|
|
|
1
|
-
const fs = require('node:fs');
|
|
1
|
+
const fs = require('node:fs');
|
|
2
2
|
const path = require('node:path');
|
|
3
3
|
const { projectAgentsFile, JORIPSPACE_CLI_GUIDE } = require('../vendor/core/onboarding.cjs');
|
|
4
|
-
const crypto = require('node:crypto');
|
|
5
|
-
const { spawnSync } = require('node:child_process');
|
|
6
|
-
const { ensureProjectEnvIgnored, removeGitignoreEntries } = require('./project-env');
|
|
7
|
-
const {
|
|
8
|
-
createExternalBackupRoot,
|
|
9
|
-
resolveProjectDirectoryTarget,
|
|
10
|
-
resolveProjectFileTarget,
|
|
11
|
-
} = require('./project-paths');
|
|
12
|
-
|
|
13
|
-
const START_AGENTS_START = '<!-- joripspace:start -->';
|
|
14
|
-
const START_AGENTS_END = '<!-- joripspace:end -->';
|
|
15
|
-
const LEGACY_AGENTS_START = '<!-- joripspace:managed:start -->';
|
|
16
|
-
const LEGACY_AGENTS_END = '<!-- joripspace:managed:end -->';
|
|
17
|
-
const PROJECT_SLUG_PATTERN = /^[a-z0-9](?:[a-z0-9-]{1,48}[a-z0-9])?$/;
|
|
18
|
-
const START_MANAGED_PATHS = new Set(['.joripspace/project', 'agents.md', 'claude.md']);
|
|
19
|
-
const LEGACY_HELPER_FILES = Object.freeze([
|
|
20
|
-
['.joripspace/doctor.mjs', 'projectDoctorHelperFile'],
|
|
21
|
-
['.joripspace/deploy.mjs', 'projectDeployHelperFile'],
|
|
22
|
-
['.joripspace/install-template.mjs', 'projectInstallTemplateHelperFile'],
|
|
23
|
-
['.joripspace/pull.mjs', 'projectPullHelperFile'],
|
|
24
|
-
['.joripspace/checkpoint-client.mjs', 'projectCheckpointClientFile'],
|
|
25
|
-
['.joripspace/save.mjs', 'projectSaveHelperFile'],
|
|
26
|
-
['.joripspace/checkpoints.mjs', 'projectCheckpointsHelperFile'],
|
|
27
|
-
['.joripspace/restore.mjs', 'projectRestoreHelperFile'],
|
|
28
|
-
['.joripspace/deploy-checkpoint.mjs', 'projectDeployCheckpointHelperFile'],
|
|
29
|
-
['.joripspace/github-actions-template.yml', 'projectGithubActionsTemplateFile'],
|
|
30
|
-
]);
|
|
31
|
-
const LEGACY_HELPER_SHA256 = Object.freeze({
|
|
32
|
-
'.joripspace/doctor.mjs': '7a2e6332c6112e4645959edf6b62367fbbf447421e9a3c65d1d2990107664ea9',
|
|
33
|
-
'.joripspace/deploy.mjs': '8a7c2afefc851a4a22e6672854c1c2f5e9f27e5c1491e5c66a18e7c395cd46fe',
|
|
34
|
-
'.joripspace/install-template.mjs': 'f6c7b62869a850eef23e19cd051825ba9b07d66dcf3b5cd1284ecd4297e4ac15',
|
|
35
|
-
'.joripspace/pull.mjs': '512bd54ceec30fc74b6cb8841492d67632fbc429dfb1b5f7c81fdad385a63af7',
|
|
36
|
-
'.joripspace/checkpoint-client.mjs': '357cca6eafa8281b1482cb9ea45d0f67a78a908d03a3632bb113ad4dbbc9cd7c',
|
|
37
|
-
'.joripspace/save.mjs': '32b4f360ad0c4fbe692d772c0bf652eb6fa703cd9cf23556e73726c045273559',
|
|
38
|
-
'.joripspace/checkpoints.mjs': '06a56b295bbd6a933af975f8143fc9ec845c94ccfb154163368032267f5f1a41',
|
|
39
|
-
'.joripspace/restore.mjs': 'ee55e7691cb5c1256de21ee67a7b8d07f890b60e79e8c8dd35d35ff182b8df41',
|
|
40
|
-
'.joripspace/deploy-checkpoint.mjs': '8821b49aa61318e6db16159b320e0cb423202c450bdfbdb1be6420ec0b84a7bd',
|
|
41
|
-
});
|
|
42
|
-
const LEGACY_PROJECT_KEYS = new Set([
|
|
43
|
-
'onboarding_schema_version',
|
|
44
|
-
'agent_guide_updated_at',
|
|
45
|
-
'deployment_policy',
|
|
46
|
-
'project_id',
|
|
47
|
-
'project_slug',
|
|
48
|
-
'default_url',
|
|
49
|
-
'api_base_url',
|
|
50
|
-
'mcp_url',
|
|
51
|
-
'deployment',
|
|
52
|
-
]);
|
|
53
|
-
const LEGACY_CREDENTIAL_SESSION_KEYS = new Set([
|
|
54
|
-
'api_base_url',
|
|
55
|
-
'api_token',
|
|
56
|
-
'connect_token',
|
|
57
|
-
'account',
|
|
58
|
-
'source',
|
|
59
|
-
'updated_at',
|
|
60
|
-
'guide_checked_at',
|
|
61
|
-
'global_session_file',
|
|
62
|
-
]);
|
|
63
|
-
const LEGACY_DEPLOYMENT_KEYS = new Set([
|
|
64
|
-
'mode',
|
|
65
|
-
'connection_status',
|
|
66
|
-
'connections',
|
|
67
|
-
'connection_id',
|
|
68
|
-
'repository_id',
|
|
69
|
-
'repository',
|
|
70
|
-
'branch',
|
|
71
|
-
'trigger_type',
|
|
72
|
-
'trigger_ref',
|
|
73
|
-
'workflow_path',
|
|
74
|
-
]);
|
|
75
|
-
const LEGACY_DEPLOYMENT_CONNECTION_KEYS = new Set([
|
|
76
|
-
'connection_id',
|
|
77
|
-
'repository_id',
|
|
78
|
-
'repository_owner',
|
|
79
|
-
'repository_name',
|
|
80
|
-
'branch',
|
|
81
|
-
'workflow_path',
|
|
82
|
-
'status',
|
|
83
|
-
'trigger_type',
|
|
84
|
-
'trigger_ref',
|
|
85
|
-
]);
|
|
86
|
-
|
|
87
|
-
async function startProject(options) {
|
|
88
|
-
const requestedProject = String(options.projectId || '').trim();
|
|
89
|
-
if (!requestedProject) throw new Error('start requires a project name or slug');
|
|
90
|
-
const workspace = resolveProjectRoot(options.cwd || process.cwd(), options.gitCommand || 'git');
|
|
91
|
-
assertSafeProjectGuidance(workspace);
|
|
92
|
-
|
|
93
|
-
const projectsContext = await options.apiRequest('/v1/me/projects', {
|
|
94
|
-
method: 'GET',
|
|
95
|
-
apiToken: options.apiToken,
|
|
96
|
-
});
|
|
97
|
-
const projects = Array.isArray(projectsContext?.projects) ? projectsContext.projects : [];
|
|
98
|
-
const accessible = projects.find((candidate) => projectMatches(candidate, requestedProject));
|
|
99
|
-
if (!accessible) {
|
|
100
|
-
return {
|
|
101
|
-
ok: false,
|
|
102
|
-
status: 'project_not_found',
|
|
103
|
-
project: requestedProject,
|
|
104
|
-
cwd: workspace,
|
|
105
|
-
available_projects: projects.map((candidate) => ({
|
|
106
|
-
project: candidate.project_slug || candidate.slug || candidate.name || null,
|
|
107
|
-
name: candidate.name || null,
|
|
108
|
-
default_url: candidate.default_url || null,
|
|
109
|
-
role: candidate.role || null,
|
|
110
|
-
})),
|
|
111
|
-
next_action: 'confirm-an-existing-project-name-or-slug; start-never-creates-projects',
|
|
112
|
-
};
|
|
113
|
-
}
|
|
114
|
-
const projectSlug = canonicalProjectSlug(accessible);
|
|
115
|
-
if (!PROJECT_SLUG_PATTERN.test(projectSlug)) {
|
|
116
|
-
throw startError('invalid_project_slug', 'accessible project has no canonical project slug');
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
const workspaceState = inspectProjectWorkspace(workspace, projectSlug, {
|
|
120
|
-
allowLegacyCredentialSession: options.allowLegacyCredentialSession === true,
|
|
121
|
-
});
|
|
122
|
-
if (!workspaceState.ok) {
|
|
123
|
-
return {
|
|
124
|
-
ok: false,
|
|
125
|
-
status: workspaceState.status,
|
|
126
|
-
project: projectSlug,
|
|
127
|
-
existing_project: workspaceState.existingProject || null,
|
|
128
|
-
cwd: workspace,
|
|
129
|
-
conflicts: workspaceState.conflicts || [],
|
|
130
|
-
next_action: workspaceState.nextAction,
|
|
131
|
-
};
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
const [details, deployments] = await Promise.all([
|
|
135
|
-
options.apiRequest(`/v1/projects/${encodeURIComponent(projectSlug)}`, {
|
|
136
|
-
method: 'GET',
|
|
137
|
-
apiToken: options.apiToken,
|
|
138
|
-
}),
|
|
139
|
-
options.apiRequest(`/v1/projects/${encodeURIComponent(projectSlug)}/deployments?limit=1`, {
|
|
140
|
-
method: 'GET',
|
|
141
|
-
apiToken: options.apiToken,
|
|
142
|
-
}),
|
|
143
|
-
]);
|
|
144
|
-
|
|
145
|
-
let sourceSync = syncConnectedGithubRepository(
|
|
146
|
-
workspace,
|
|
147
|
-
details?.deployment,
|
|
148
|
-
options.gitCommand || 'git',
|
|
149
|
-
{ allowManagedWorkspace: workspaceState.onlyManagedFiles }
|
|
150
|
-
);
|
|
151
|
-
const sourceSyncBlocking =
|
|
152
|
-
sourceSync &&
|
|
153
|
-
?$/;
|
|
18
|
+
const START_MANAGED_PATHS = new Set(['.joripspace/project', 'agents.md', 'claude.md']);
|
|
19
|
+
const LEGACY_HELPER_FILES = Object.freeze([
|
|
20
|
+
['.joripspace/doctor.mjs', 'projectDoctorHelperFile'],
|
|
21
|
+
['.joripspace/deploy.mjs', 'projectDeployHelperFile'],
|
|
22
|
+
['.joripspace/install-template.mjs', 'projectInstallTemplateHelperFile'],
|
|
23
|
+
['.joripspace/pull.mjs', 'projectPullHelperFile'],
|
|
24
|
+
['.joripspace/checkpoint-client.mjs', 'projectCheckpointClientFile'],
|
|
25
|
+
['.joripspace/save.mjs', 'projectSaveHelperFile'],
|
|
26
|
+
['.joripspace/checkpoints.mjs', 'projectCheckpointsHelperFile'],
|
|
27
|
+
['.joripspace/restore.mjs', 'projectRestoreHelperFile'],
|
|
28
|
+
['.joripspace/deploy-checkpoint.mjs', 'projectDeployCheckpointHelperFile'],
|
|
29
|
+
['.joripspace/github-actions-template.yml', 'projectGithubActionsTemplateFile'],
|
|
30
|
+
]);
|
|
31
|
+
const LEGACY_HELPER_SHA256 = Object.freeze({
|
|
32
|
+
'.joripspace/doctor.mjs': '7a2e6332c6112e4645959edf6b62367fbbf447421e9a3c65d1d2990107664ea9',
|
|
33
|
+
'.joripspace/deploy.mjs': '8a7c2afefc851a4a22e6672854c1c2f5e9f27e5c1491e5c66a18e7c395cd46fe',
|
|
34
|
+
'.joripspace/install-template.mjs': 'f6c7b62869a850eef23e19cd051825ba9b07d66dcf3b5cd1284ecd4297e4ac15',
|
|
35
|
+
'.joripspace/pull.mjs': '512bd54ceec30fc74b6cb8841492d67632fbc429dfb1b5f7c81fdad385a63af7',
|
|
36
|
+
'.joripspace/checkpoint-client.mjs': '357cca6eafa8281b1482cb9ea45d0f67a78a908d03a3632bb113ad4dbbc9cd7c',
|
|
37
|
+
'.joripspace/save.mjs': '32b4f360ad0c4fbe692d772c0bf652eb6fa703cd9cf23556e73726c045273559',
|
|
38
|
+
'.joripspace/checkpoints.mjs': '06a56b295bbd6a933af975f8143fc9ec845c94ccfb154163368032267f5f1a41',
|
|
39
|
+
'.joripspace/restore.mjs': 'ee55e7691cb5c1256de21ee67a7b8d07f890b60e79e8c8dd35d35ff182b8df41',
|
|
40
|
+
'.joripspace/deploy-checkpoint.mjs': '8821b49aa61318e6db16159b320e0cb423202c450bdfbdb1be6420ec0b84a7bd',
|
|
41
|
+
});
|
|
42
|
+
const LEGACY_PROJECT_KEYS = new Set([
|
|
43
|
+
'onboarding_schema_version',
|
|
44
|
+
'agent_guide_updated_at',
|
|
45
|
+
'deployment_policy',
|
|
46
|
+
'project_id',
|
|
47
|
+
'project_slug',
|
|
48
|
+
'default_url',
|
|
49
|
+
'api_base_url',
|
|
50
|
+
'mcp_url',
|
|
51
|
+
'deployment',
|
|
52
|
+
]);
|
|
53
|
+
const LEGACY_CREDENTIAL_SESSION_KEYS = new Set([
|
|
54
|
+
'api_base_url',
|
|
55
|
+
'api_token',
|
|
56
|
+
'connect_token',
|
|
57
|
+
'account',
|
|
58
|
+
'source',
|
|
59
|
+
'updated_at',
|
|
60
|
+
'guide_checked_at',
|
|
61
|
+
'global_session_file',
|
|
62
|
+
]);
|
|
63
|
+
const LEGACY_DEPLOYMENT_KEYS = new Set([
|
|
64
|
+
'mode',
|
|
65
|
+
'connection_status',
|
|
66
|
+
'connections',
|
|
67
|
+
'connection_id',
|
|
68
|
+
'repository_id',
|
|
69
|
+
'repository',
|
|
70
|
+
'branch',
|
|
71
|
+
'trigger_type',
|
|
72
|
+
'trigger_ref',
|
|
73
|
+
'workflow_path',
|
|
74
|
+
]);
|
|
75
|
+
const LEGACY_DEPLOYMENT_CONNECTION_KEYS = new Set([
|
|
76
|
+
'connection_id',
|
|
77
|
+
'repository_id',
|
|
78
|
+
'repository_owner',
|
|
79
|
+
'repository_name',
|
|
80
|
+
'branch',
|
|
81
|
+
'workflow_path',
|
|
82
|
+
'status',
|
|
83
|
+
'trigger_type',
|
|
84
|
+
'trigger_ref',
|
|
85
|
+
]);
|
|
86
|
+
|
|
87
|
+
async function startProject(options) {
|
|
88
|
+
const requestedProject = String(options.projectId || '').trim();
|
|
89
|
+
if (!requestedProject) throw new Error('start requires a project name or slug');
|
|
90
|
+
const workspace = resolveProjectRoot(options.cwd || process.cwd(), options.gitCommand || 'git');
|
|
91
|
+
assertSafeProjectGuidance(workspace);
|
|
92
|
+
|
|
93
|
+
const projectsContext = await options.apiRequest('/v1/me/projects', {
|
|
94
|
+
method: 'GET',
|
|
95
|
+
apiToken: options.apiToken,
|
|
96
|
+
});
|
|
97
|
+
const projects = Array.isArray(projectsContext?.projects) ? projectsContext.projects : [];
|
|
98
|
+
const accessible = projects.find((candidate) => projectMatches(candidate, requestedProject));
|
|
99
|
+
if (!accessible) {
|
|
100
|
+
return {
|
|
101
|
+
ok: false,
|
|
102
|
+
status: 'project_not_found',
|
|
103
|
+
project: requestedProject,
|
|
104
|
+
cwd: workspace,
|
|
105
|
+
available_projects: projects.map((candidate) => ({
|
|
106
|
+
project: candidate.project_slug || candidate.slug || candidate.name || null,
|
|
107
|
+
name: candidate.name || null,
|
|
108
|
+
default_url: candidate.default_url || null,
|
|
109
|
+
role: candidate.role || null,
|
|
110
|
+
})),
|
|
111
|
+
next_action: 'confirm-an-existing-project-name-or-slug; start-never-creates-projects',
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
const projectSlug = canonicalProjectSlug(accessible);
|
|
115
|
+
if (!PROJECT_SLUG_PATTERN.test(projectSlug)) {
|
|
116
|
+
throw startError('invalid_project_slug', 'accessible project has no canonical project slug');
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const workspaceState = inspectProjectWorkspace(workspace, projectSlug, {
|
|
120
|
+
allowLegacyCredentialSession: options.allowLegacyCredentialSession === true,
|
|
121
|
+
});
|
|
122
|
+
if (!workspaceState.ok) {
|
|
123
|
+
return {
|
|
124
|
+
ok: false,
|
|
125
|
+
status: workspaceState.status,
|
|
126
|
+
project: projectSlug,
|
|
127
|
+
existing_project: workspaceState.existingProject || null,
|
|
128
|
+
cwd: workspace,
|
|
129
|
+
conflicts: workspaceState.conflicts || [],
|
|
130
|
+
next_action: workspaceState.nextAction,
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const [details, deployments] = await Promise.all([
|
|
135
|
+
options.apiRequest(`/v1/projects/${encodeURIComponent(projectSlug)}`, {
|
|
136
|
+
method: 'GET',
|
|
137
|
+
apiToken: options.apiToken,
|
|
138
|
+
}),
|
|
139
|
+
options.apiRequest(`/v1/projects/${encodeURIComponent(projectSlug)}/deployments?limit=1`, {
|
|
140
|
+
method: 'GET',
|
|
141
|
+
apiToken: options.apiToken,
|
|
142
|
+
}),
|
|
143
|
+
]);
|
|
144
|
+
|
|
145
|
+
let sourceSync = syncConnectedGithubRepository(
|
|
146
|
+
workspace,
|
|
147
|
+
details?.deployment,
|
|
148
|
+
options.gitCommand || 'git',
|
|
149
|
+
{ allowManagedWorkspace: workspaceState.onlyManagedFiles }
|
|
150
|
+
);
|
|
151
|
+
const sourceSyncBlocking =
|
|
152
|
+
sourceSync &&
|
|
153
|
+
![
|
|
154
|
+
'synchronized',
|
|
155
|
+
'dirty_worktree',
|
|
156
|
+
'managed_worktree_preserved',
|
|
157
|
+
'empty_remote_ready',
|
|
158
|
+
'initialized_empty_remote',
|
|
159
|
+
].includes(sourceSync.status);
|
|
160
|
+
if (sourceSyncBlocking) {
|
|
161
|
+
return {
|
|
162
|
+
ok: false,
|
|
163
|
+
status: 'github_repository_sync_conflict',
|
|
164
|
+
project: projectSlug,
|
|
165
|
+
cwd: workspace,
|
|
166
|
+
source_sync: sourceSync,
|
|
167
|
+
next_action: 'resolve-the-reported-git-conflict-without-overwriting-local-work',
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const existingWorkBeforeGuidance = workspaceHasApplicationFiles(workspace);
|
|
172
|
+
if (options.beforeWorkspaceMigration) {
|
|
173
|
+
await Promise.resolve(options.beforeWorkspaceMigration({ project: projectSlug, workspace }));
|
|
174
|
+
}
|
|
175
|
+
const migrationState = inspectProjectWorkspace(workspace, projectSlug, {
|
|
176
|
+
allowLegacyCredentialSession: options.allowLegacyCredentialSession === true,
|
|
177
|
+
});
|
|
178
|
+
if (!migrationState.ok) {
|
|
179
|
+
return {
|
|
180
|
+
ok: false,
|
|
181
|
+
status: migrationState.status,
|
|
182
|
+
project: projectSlug,
|
|
183
|
+
existing_project: migrationState.existingProject || null,
|
|
184
|
+
cwd: workspace,
|
|
185
|
+
conflicts: migrationState.conflicts || [],
|
|
186
|
+
next_action: migrationState.nextAction,
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
if (options.beforeMigrationCommit) {
|
|
190
|
+
await Promise.resolve(options.beforeMigrationCommit({ project: projectSlug, workspace }));
|
|
191
|
+
}
|
|
192
|
+
const migration = migrateProjectWorkspace(workspace, projectSlug, migrationState, options);
|
|
193
|
+
const executable = path.resolve(options.executable || process.argv[1] || process.execPath);
|
|
194
|
+
const latestDeployment = Array.isArray(deployments?.deployments)
|
|
195
|
+
? deployments.deployments[0] || null
|
|
196
|
+
: null;
|
|
197
|
+
const deploymentMode = details?.deployment?.mode || 'direct';
|
|
198
|
+
const restorable =
|
|
199
|
+
latestDeployment?.status === 'success' &&
|
|
200
|
+
(latestDeployment.download_available || latestDeployment.rollback_available);
|
|
201
|
+
if (
|
|
202
|
+
deploymentMode === 'github_actions' &&
|
|
203
|
+
details?.deployment?.source_status === 'empty' &&
|
|
204
|
+
restorable &&
|
|
205
|
+
!existingWorkBeforeGuidance
|
|
206
|
+
) {
|
|
207
|
+
sourceSync = {
|
|
208
|
+
status: 'latest_deployment_restore_required',
|
|
209
|
+
deployment_id: latestDeployment.deployment_id,
|
|
210
|
+
repository_setup: sourceSync,
|
|
211
|
+
};
|
|
212
|
+
} else if (!sourceSync && deploymentMode !== 'github_actions') {
|
|
213
|
+
sourceSync =
|
|
214
|
+
restorable && !existingWorkBeforeGuidance
|
|
215
|
+
? {
|
|
216
|
+
status: 'latest_deployment_restore_required',
|
|
217
|
+
deployment_id: latestDeployment.deployment_id,
|
|
218
|
+
}
|
|
219
|
+
: latestDeployment
|
|
220
|
+
? {
|
|
221
|
+
status: 'existing_workspace_preserved',
|
|
222
|
+
reason: existingWorkBeforeGuidance ? 'local_work_exists' : 'deployment_source_unavailable',
|
|
223
|
+
}
|
|
224
|
+
: null;
|
|
225
|
+
}
|
|
226
|
+
const description = normalizedDescription(details?.description ?? accessible?.description);
|
|
227
|
+
const hasExistingWork = Boolean(
|
|
228
|
+
existingWorkBeforeGuidance ||
|
|
229
|
+
latestDeployment ||
|
|
230
|
+
(details?.deployment?.mode === 'github_actions' && details?.deployment?.source_status !== 'empty')
|
|
231
|
+
);
|
|
232
|
+
const warnings = [];
|
|
233
|
+
if (migration.backupRoot) {
|
|
234
|
+
warnings.push({
|
|
235
|
+
code: 'legacy_workspace_backup_created',
|
|
236
|
+
message: 'Verified legacy onboarding files were moved outside the project before cleanup.',
|
|
237
|
+
backup_root: migration.backupRoot,
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
if (sourceSync?.status === 'dirty_worktree' || sourceSync?.status === 'managed_worktree_preserved') {
|
|
241
|
+
warnings.push({
|
|
242
|
+
code: 'local_work_preserved',
|
|
243
|
+
message: 'Local Git changes were preserved and no source files were overwritten.',
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
const templateChoice =
|
|
247
|
+
!description && !hasExistingWork
|
|
248
|
+
? await loadTemplateChoice(options.apiRequest, options.apiToken, executable, projectSlug, workspace)
|
|
249
|
+
: null;
|
|
250
|
+
|
|
251
|
+
return {
|
|
252
|
+
ok: true,
|
|
253
|
+
project: projectSlug,
|
|
254
|
+
executable,
|
|
236
255
|
continue_with: 'cli',
|
|
237
256
|
onboarding: createStartOnboarding(executable, workspace, projectSlug, true),
|
|
238
257
|
next_action: templateChoice
|
|
239
|
-
? templateChoice.status === 'ready'
|
|
240
|
-
? 'present-template-choice'
|
|
241
|
-
: 'retry-start-once-before-project-questions'
|
|
242
|
-
: 'continue-development',
|
|
243
|
-
template_choice: templateChoice,
|
|
244
|
-
context: {
|
|
245
|
-
description,
|
|
246
|
-
project_status: details?.status || accessible?.status || null,
|
|
247
|
-
latest_deployment: latestDeployment,
|
|
248
|
-
source_sync: sourceSync,
|
|
249
|
-
warnings,
|
|
250
|
-
},
|
|
251
|
-
};
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
async function loadTemplateChoice(apiRequest, apiToken, executable, projectSlug, workspace) {
|
|
255
|
-
for (let attempt = 1; attempt <= 2; attempt += 1) {
|
|
256
|
-
try {
|
|
257
|
-
const result = await apiRequest('/v1/templates', { method: 'GET', apiToken });
|
|
258
|
-
const templates = Array.isArray(result?.templates) ? result.templates : [];
|
|
259
|
-
return {
|
|
260
|
-
status: 'ready',
|
|
261
|
-
optional: true,
|
|
262
|
-
no_template_option: { number: 0, name: '템플릿 없이 시작' },
|
|
263
|
-
templates: templates.map((template, index) => ({ ...template, number: index + 1 })),
|
|
264
|
-
next_cursor: typeof result?.next_cursor === 'string' ? result.next_cursor : null,
|
|
265
|
-
presentation:
|
|
266
|
-
'프로젝트 질문 전에 0번과 templates를 번호, 템플릿 이름, 적합한 용도, 포함 기능이 있는 Markdown 표로 보여주고 사용자의 선택을 기다리세요.',
|
|
258
|
+
? templateChoice.status === 'ready'
|
|
259
|
+
? 'present-template-choice'
|
|
260
|
+
: 'retry-start-once-before-project-questions'
|
|
261
|
+
: 'continue-development',
|
|
262
|
+
template_choice: templateChoice,
|
|
263
|
+
context: {
|
|
264
|
+
description,
|
|
265
|
+
project_status: details?.status || accessible?.status || null,
|
|
266
|
+
latest_deployment: latestDeployment,
|
|
267
|
+
source_sync: sourceSync,
|
|
268
|
+
warnings,
|
|
269
|
+
},
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
async function loadTemplateChoice(apiRequest, apiToken, executable, projectSlug, workspace) {
|
|
274
|
+
for (let attempt = 1; attempt <= 2; attempt += 1) {
|
|
275
|
+
try {
|
|
276
|
+
const result = await apiRequest('/v1/templates', { method: 'GET', apiToken });
|
|
277
|
+
const templates = Array.isArray(result?.templates) ? result.templates : [];
|
|
278
|
+
return {
|
|
279
|
+
status: 'ready',
|
|
280
|
+
optional: true,
|
|
281
|
+
no_template_option: { number: 0, name: '템플릿 없이 시작' },
|
|
282
|
+
templates: templates.map((template, index) => ({ ...template, number: index + 1 })),
|
|
283
|
+
next_cursor: typeof result?.next_cursor === 'string' ? result.next_cursor : null,
|
|
284
|
+
presentation:
|
|
285
|
+
'프로젝트 질문 전에 0번과 templates를 번호, 템플릿 이름, 적합한 용도, 포함 기능이 있는 Markdown 표로 보여주고 사용자의 선택을 기다리세요.',
|
|
267
286
|
install_command: `${!process.pkg && executable === path.resolve(process.argv[1] || '') ? quoteCommandArgument(process.execPath) + ' ' : ''}${quoteCommandArgument(executable)} install-template --template "TEMPLATE_SLUG" --project ${quoteCommandArgument(projectSlug)} --dir ${quoteCommandArgument(workspace)}`,
|
|
268
|
-
};
|
|
269
|
-
} catch {
|
|
270
|
-
if (attempt === 2) break;
|
|
271
|
-
}
|
|
272
|
-
}
|
|
273
|
-
return {
|
|
274
|
-
status: 'temporarily_unavailable',
|
|
275
|
-
optional: true,
|
|
276
|
-
no_template_option: { number: 0, name: '템플릿 없이 시작' },
|
|
277
|
-
templates: [],
|
|
278
|
-
retryable: true,
|
|
279
|
-
next_action:
|
|
280
|
-
'같은 절대경로 CLI와 프로젝트로 start를 한 번 다시 실행한 뒤 템플릿 선택 전에는 서비스 질문으로 넘어가지 마세요.',
|
|
281
|
-
};
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
function quoteCommandArgument(value) {
|
|
285
|
-
return `"${String(value).replace(/"/g, '\\"')}"`;
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
function syncConnectedGithubRepository(workspace, deployment, gitCommand, options = {}) {
|
|
289
|
-
if (!deployment || deployment.mode !== 'github_actions') return null;
|
|
290
|
-
const repository = String(deployment.repository || '').trim();
|
|
291
|
-
const branch = String(deployment.branch || '').trim();
|
|
292
|
-
if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repository) || !validGitBranch(branch)) {
|
|
293
|
-
return { status: 'invalid_configuration', repository, branch };
|
|
294
|
-
}
|
|
295
|
-
const expectedUrl = `https://github.com/${repository}.git`;
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
const
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
'
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
const
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
const
|
|
382
|
-
?
|
|
383
|
-
: '';
|
|
384
|
-
const
|
|
385
|
-
? fs.readFileSync(
|
|
386
|
-
: '';
|
|
387
|
-
const
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
}
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
}
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
}
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
const
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
const
|
|
517
|
-
if (
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
}
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
}
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
287
|
+
};
|
|
288
|
+
} catch {
|
|
289
|
+
if (attempt === 2) break;
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
return {
|
|
293
|
+
status: 'temporarily_unavailable',
|
|
294
|
+
optional: true,
|
|
295
|
+
no_template_option: { number: 0, name: '템플릿 없이 시작' },
|
|
296
|
+
templates: [],
|
|
297
|
+
retryable: true,
|
|
298
|
+
next_action:
|
|
299
|
+
'같은 절대경로 CLI와 프로젝트로 start를 한 번 다시 실행한 뒤 템플릿 선택 전에는 서비스 질문으로 넘어가지 마세요.',
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function quoteCommandArgument(value) {
|
|
304
|
+
return `"${String(value).replace(/"/g, '\\"')}"`;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
function syncConnectedGithubRepository(workspace, deployment, gitCommand, options = {}) {
|
|
308
|
+
if (!deployment || deployment.mode !== 'github_actions') return null;
|
|
309
|
+
const repository = String(deployment.repository || '').trim();
|
|
310
|
+
const branch = String(deployment.branch || '').trim();
|
|
311
|
+
if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repository) || !validGitBranch(branch)) {
|
|
312
|
+
return { status: 'invalid_configuration', repository, branch };
|
|
313
|
+
}
|
|
314
|
+
const expectedUrl = `https://github.com/${repository}.git`;
|
|
315
|
+
if (deployment.source_status === 'empty') {
|
|
316
|
+
return prepareEmptyGithubRepository(workspace, gitCommand, repository, branch, expectedUrl);
|
|
317
|
+
}
|
|
318
|
+
const inside = git(workspace, gitCommand, ['rev-parse', '--is-inside-work-tree']);
|
|
319
|
+
if (inside.status === 0 && inside.stdout.trim() === 'true') {
|
|
320
|
+
const remote = git(workspace, gitCommand, ['remote', 'get-url', 'origin']);
|
|
321
|
+
if (remote.status !== 0) return gitFailure('origin_missing', remote);
|
|
322
|
+
if (githubRepository(remote.stdout.trim()) !== repository.toLowerCase()) {
|
|
323
|
+
return {
|
|
324
|
+
status: 'wrong_repository',
|
|
325
|
+
expected_repository: repository,
|
|
326
|
+
actual_remote: redactGitDiagnostic(remote.stdout.trim()),
|
|
327
|
+
};
|
|
328
|
+
}
|
|
329
|
+
const currentBranch = git(workspace, gitCommand, ['branch', '--show-current']);
|
|
330
|
+
if (currentBranch.status !== 0) return gitFailure('branch_check_failed', currentBranch);
|
|
331
|
+
if (currentBranch.stdout.trim() !== branch) {
|
|
332
|
+
return { status: 'wrong_branch', expected_branch: branch, actual_branch: currentBranch.stdout.trim() };
|
|
333
|
+
}
|
|
334
|
+
const status = git(workspace, gitCommand, ['status', '--porcelain', '--untracked-files=all']);
|
|
335
|
+
if (status.status !== 0) return gitFailure('status_failed', status);
|
|
336
|
+
if (status.stdout.trim()) {
|
|
337
|
+
const changedFiles = status.stdout.trim().split(/\r?\n/);
|
|
338
|
+
const onlyManaged = changedFiles.every((line) => isManagedGitStatusLine(line));
|
|
339
|
+
return {
|
|
340
|
+
status: onlyManaged ? 'managed_worktree_preserved' : 'dirty_worktree',
|
|
341
|
+
changed_files: changedFiles,
|
|
342
|
+
repository,
|
|
343
|
+
branch,
|
|
344
|
+
};
|
|
345
|
+
}
|
|
346
|
+
const fetch = git(workspace, gitCommand, ['fetch', '--no-tags', 'origin', branch]);
|
|
347
|
+
if (fetch.status !== 0) return gitFailure('fetch_failed', fetch);
|
|
348
|
+
const canFastForward = git(workspace, gitCommand, ['merge-base', '--is-ancestor', 'HEAD', 'FETCH_HEAD']);
|
|
349
|
+
if (canFastForward.status === 0) {
|
|
350
|
+
const merge = git(workspace, gitCommand, ['merge', '--ff-only', 'FETCH_HEAD']);
|
|
351
|
+
if (merge.status !== 0) return gitFailure('fast_forward_failed', merge);
|
|
352
|
+
return { status: 'synchronized', operation: 'fast_forward', repository, branch };
|
|
353
|
+
}
|
|
354
|
+
const localAhead = git(workspace, gitCommand, ['merge-base', '--is-ancestor', 'FETCH_HEAD', 'HEAD']);
|
|
355
|
+
if (localAhead.status === 0) {
|
|
356
|
+
return { status: 'synchronized', operation: 'local_ahead', repository, branch };
|
|
357
|
+
}
|
|
358
|
+
return { status: 'divergent_history', repository, branch };
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
const allowed = new Set(['.env.joripspace', '.gitignore']);
|
|
362
|
+
if (options.allowManagedWorkspace) {
|
|
363
|
+
allowed.add('.joripspace');
|
|
364
|
+
allowed.add('agents.md');
|
|
365
|
+
allowed.add('claude.md');
|
|
366
|
+
}
|
|
367
|
+
const unexpected = fs.readdirSync(workspace).filter((name) => !allowed.has(name.toLowerCase()));
|
|
368
|
+
if (unexpected.length) return { status: 'non_empty_directory', unexpected_entries: unexpected };
|
|
369
|
+
const temporary = `${workspace}.joripspace-clone-${process.pid}-${Date.now()}`;
|
|
370
|
+
const clone = spawnSync(
|
|
371
|
+
gitCommand,
|
|
372
|
+
['clone', '--branch', branch, '--single-branch', expectedUrl, temporary],
|
|
373
|
+
{
|
|
374
|
+
encoding: 'utf8',
|
|
375
|
+
windowsHide: true,
|
|
376
|
+
}
|
|
377
|
+
);
|
|
378
|
+
if (clone.status !== 0) {
|
|
379
|
+
fs.rmSync(temporary, { recursive: true, force: true });
|
|
380
|
+
return gitFailure('clone_failed', clone);
|
|
381
|
+
}
|
|
382
|
+
try {
|
|
383
|
+
const trackedEnv = git(temporary, gitCommand, [
|
|
384
|
+
'ls-files',
|
|
385
|
+
'--error-unmatch',
|
|
386
|
+
'--',
|
|
387
|
+
':(icase).env.joripspace',
|
|
388
|
+
]);
|
|
389
|
+
if (trackedEnv.status === 0) {
|
|
390
|
+
return {
|
|
391
|
+
status: 'protected_auth_file_tracked',
|
|
392
|
+
repository,
|
|
393
|
+
branch,
|
|
394
|
+
protected_file: '.env.joripspace',
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
const localGitignorePath = managedProjectFilePath(workspace, '.gitignore');
|
|
398
|
+
const temporaryEntries = fs.readdirSync(temporary);
|
|
399
|
+
const remoteGitignoreEntry = temporaryEntries.find((entry) => entry.toLowerCase() === '.gitignore');
|
|
400
|
+
const remoteGitignorePath = remoteGitignoreEntry
|
|
401
|
+
? path.join(temporary, remoteGitignoreEntry)
|
|
402
|
+
: path.join(temporary, '.gitignore');
|
|
403
|
+
const localGitignore = fs.existsSync(localGitignorePath)
|
|
404
|
+
? fs.readFileSync(localGitignorePath, 'utf8')
|
|
405
|
+
: '';
|
|
406
|
+
const remoteGitignore = fs.existsSync(remoteGitignorePath)
|
|
407
|
+
? fs.readFileSync(remoteGitignorePath, 'utf8')
|
|
408
|
+
: '';
|
|
409
|
+
const localEntries = new Set(fs.readdirSync(workspace).map((entry) => entry.toLowerCase()));
|
|
410
|
+
for (const entry of temporaryEntries) {
|
|
411
|
+
const normalizedEntry = entry.toLowerCase();
|
|
412
|
+
if (
|
|
413
|
+
normalizedEntry === '.env.joripspace' ||
|
|
414
|
+
normalizedEntry === '.gitignore' ||
|
|
415
|
+
normalizedEntry === '.joripspace' ||
|
|
416
|
+
((normalizedEntry === 'agents.md' || normalizedEntry === 'claude.md') &&
|
|
417
|
+
localEntries.has(normalizedEntry))
|
|
418
|
+
) {
|
|
419
|
+
continue;
|
|
420
|
+
}
|
|
421
|
+
fs.cpSync(path.join(temporary, entry), path.join(workspace, entry), { recursive: true, force: true });
|
|
422
|
+
}
|
|
423
|
+
writeTextAtomically(localGitignorePath, mergeGitignoreSources(remoteGitignore, localGitignore));
|
|
424
|
+
ensureProjectEnvIgnored(workspace);
|
|
425
|
+
} finally {
|
|
426
|
+
fs.rmSync(temporary, { recursive: true, force: true });
|
|
427
|
+
}
|
|
428
|
+
return { status: 'synchronized', operation: 'clone', repository, branch };
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
function prepareEmptyGithubRepository(workspace, gitCommand, repository, branch, expectedUrl) {
|
|
432
|
+
const inside = git(workspace, gitCommand, ['rev-parse', '--is-inside-work-tree']);
|
|
433
|
+
if (inside.status === 0 && inside.stdout.trim() === 'true') {
|
|
434
|
+
const remote = git(workspace, gitCommand, ['remote', 'get-url', 'origin']);
|
|
435
|
+
if (remote.status !== 0) {
|
|
436
|
+
const addRemote = git(workspace, gitCommand, ['remote', 'add', 'origin', expectedUrl]);
|
|
437
|
+
if (addRemote.status !== 0) return gitFailure('origin_add_failed', addRemote);
|
|
438
|
+
} else if (githubRepository(remote.stdout.trim()) !== repository.toLowerCase()) {
|
|
439
|
+
return {
|
|
440
|
+
status: 'wrong_repository',
|
|
441
|
+
expected_repository: repository,
|
|
442
|
+
actual_remote: redactGitDiagnostic(remote.stdout.trim()),
|
|
443
|
+
};
|
|
444
|
+
}
|
|
445
|
+
const currentBranch = git(workspace, gitCommand, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
|
|
446
|
+
if (currentBranch.status !== 0) return gitFailure('branch_check_failed', currentBranch);
|
|
447
|
+
if (currentBranch.stdout.trim() !== branch) {
|
|
448
|
+
const head = git(workspace, gitCommand, ['rev-parse', '--verify', 'HEAD']);
|
|
449
|
+
if (head.status === 0) {
|
|
450
|
+
return {
|
|
451
|
+
status: 'wrong_branch',
|
|
452
|
+
expected_branch: branch,
|
|
453
|
+
actual_branch: currentBranch.stdout.trim(),
|
|
454
|
+
};
|
|
455
|
+
}
|
|
456
|
+
const setBranch = git(workspace, gitCommand, ['symbolic-ref', 'HEAD', `refs/heads/${branch}`]);
|
|
457
|
+
if (setBranch.status !== 0) return gitFailure('branch_setup_failed', setBranch);
|
|
458
|
+
}
|
|
459
|
+
return { status: 'empty_remote_ready', operation: 'existing_repository', repository, branch };
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
const initialize = git(workspace, gitCommand, ['init', '--initial-branch', branch]);
|
|
463
|
+
if (initialize.status !== 0) return gitFailure('init_failed', initialize);
|
|
464
|
+
const addRemote = git(workspace, gitCommand, ['remote', 'add', 'origin', expectedUrl]);
|
|
465
|
+
if (addRemote.status !== 0) return gitFailure('origin_add_failed', addRemote);
|
|
466
|
+
return { status: 'initialized_empty_remote', operation: 'git_init', repository, branch };
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
function validGitBranch(value) {
|
|
470
|
+
if (
|
|
471
|
+
!value ||
|
|
472
|
+
value === '@' ||
|
|
473
|
+
value.startsWith('-') ||
|
|
474
|
+
value.startsWith('/') ||
|
|
475
|
+
value.endsWith('/') ||
|
|
476
|
+
value.endsWith('.') ||
|
|
477
|
+
value.includes('..') ||
|
|
478
|
+
value.includes('@{') ||
|
|
479
|
+
value.includes('//') ||
|
|
480
|
+
value.includes('[') ||
|
|
481
|
+
/[\x00-\x20\x7f~^:?*\\]/.test(value)
|
|
482
|
+
) {
|
|
483
|
+
return false;
|
|
484
|
+
}
|
|
485
|
+
return !value.split('/').some((part) => part.startsWith('.') || part.toLowerCase().endsWith('.lock'));
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
function git(workspace, gitCommand, args) {
|
|
489
|
+
return spawnSync(gitCommand, ['-C', workspace, ...args], {
|
|
490
|
+
encoding: 'utf8',
|
|
491
|
+
windowsHide: true,
|
|
492
|
+
});
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
function gitFailure(status, result) {
|
|
496
|
+
return {
|
|
497
|
+
status,
|
|
498
|
+
error:
|
|
499
|
+
redactGitDiagnostic(result.error?.message || String(result.stderr || result.stdout || '').trim()) ||
|
|
500
|
+
'git command failed',
|
|
501
|
+
};
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
function redactGitDiagnostic(value) {
|
|
505
|
+
return String(value || '')
|
|
506
|
+
.replace(/\b(https?|git|ssh):\/\/[^\s/@]+@/gi, '$1://')
|
|
507
|
+
.replace(
|
|
508
|
+
/([?&](?:access[_-]?token|api[_-]?key|auth(?:orization)?|credential|password|token)=)[^&#\s]+/gi,
|
|
509
|
+
'$1[redacted]'
|
|
510
|
+
)
|
|
511
|
+
.replace(/\b(?:github_pat_[A-Za-z0-9_]+|gh[pousr]_[A-Za-z0-9_]+|glpat-[A-Za-z0-9_-]+)\b/g, '[redacted]');
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
function mergeGitignoreSources(remoteSource, localSource) {
|
|
515
|
+
const lines = [];
|
|
516
|
+
const seen = new Set();
|
|
517
|
+
for (const line of `${remoteSource || ''}\n${localSource || ''}`.split(/\r?\n/)) {
|
|
518
|
+
if (!line || seen.has(line)) continue;
|
|
519
|
+
seen.add(line);
|
|
520
|
+
lines.push(line);
|
|
521
|
+
}
|
|
522
|
+
return lines.length ? `${lines.join('\n')}\n` : '';
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
function githubRepository(remote) {
|
|
526
|
+
const value = String(remote || '')
|
|
527
|
+
.trim()
|
|
528
|
+
.replace(/\.git$/i, '');
|
|
529
|
+
const match =
|
|
530
|
+
/^(?:https:\/\/github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([^/]+\/[^/]+)$/i.exec(value);
|
|
531
|
+
return match ? match[1].toLowerCase() : '';
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
function resolveProjectRoot(cwd, gitCommand) {
|
|
535
|
+
const directory = path.resolve(cwd);
|
|
536
|
+
if (!fs.existsSync(directory) || !fs.statSync(directory).isDirectory()) {
|
|
537
|
+
throw new Error(`start cwd does not exist or is not a directory: ${directory}`);
|
|
538
|
+
}
|
|
539
|
+
const discovered = git(directory, gitCommand, ['rev-parse', '--show-toplevel']);
|
|
540
|
+
const candidate = String(discovered.stdout || '').trim();
|
|
541
|
+
if (discovered.status === 0 && candidate && !/[\r\n\0]/.test(candidate) && path.isAbsolute(candidate)) {
|
|
542
|
+
try {
|
|
543
|
+
const root = fs.realpathSync.native(path.resolve(candidate));
|
|
544
|
+
const current = fs.realpathSync.native(directory);
|
|
545
|
+
const relative = path.relative(root, current);
|
|
546
|
+
if (!relative.startsWith('..') && !path.isAbsolute(relative) && fs.statSync(root).isDirectory()) {
|
|
547
|
+
return root;
|
|
548
|
+
}
|
|
549
|
+
} catch {}
|
|
550
|
+
}
|
|
551
|
+
return directory;
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
function readProjectMarker(workspace) {
|
|
555
|
+
const markerPath = managedProjectFilePath(workspace, '.joripspace/project');
|
|
556
|
+
if (!fs.existsSync(markerPath)) return '';
|
|
557
|
+
return parseProjectMarker(fs.readFileSync(markerPath, 'utf8'));
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
function ensureProjectGuidance(workspace, projectSlug) {
|
|
561
|
+
assertSafeProjectGuidance(workspace);
|
|
562
|
+
const joripspaceDirectory = resolveProjectDirectoryTarget(workspace, '.joripspace').target;
|
|
563
|
+
fs.mkdirSync(joripspaceDirectory, { recursive: true });
|
|
564
|
+
const projectPath = managedProjectFilePath(workspace, '.joripspace/project');
|
|
565
|
+
const currentProject = fs.existsSync(projectPath) ? fs.readFileSync(projectPath, 'utf8') : '';
|
|
566
|
+
const nextProject = `${projectSlug}\n`;
|
|
567
|
+
if (currentProject !== nextProject) writeTextAtomically(projectPath, nextProject);
|
|
568
|
+
|
|
569
|
+
const agentsPath = managedProjectFilePath(workspace, 'AGENTS.md');
|
|
570
|
+
const currentAgents = fs.existsSync(agentsPath) ? fs.readFileSync(agentsPath, 'utf8') : '';
|
|
571
|
+
const nextAgents = upsertStartAgentsBlock(currentAgents);
|
|
572
|
+
if (nextAgents !== currentAgents) writeTextAtomically(agentsPath, nextAgents);
|
|
573
|
+
|
|
574
|
+
const claudePath = managedProjectFilePath(workspace, 'CLAUDE.md');
|
|
575
|
+
const currentClaude = fs.existsSync(claudePath) ? fs.readFileSync(claudePath, 'utf8') : '';
|
|
576
|
+
const nextClaude = upsertClaudeAgentsReference(currentClaude);
|
|
577
|
+
if (nextClaude !== currentClaude) writeTextAtomically(claudePath, nextClaude);
|
|
578
|
+
|
|
579
|
+
return {
|
|
580
|
+
project: projectPath,
|
|
581
|
+
agents: agentsPath,
|
|
582
|
+
claude: claudePath,
|
|
583
|
+
created: {
|
|
584
|
+
project: currentProject !== nextProject,
|
|
585
|
+
agents: nextAgents !== currentAgents,
|
|
586
|
+
claude: nextClaude !== currentClaude,
|
|
587
|
+
},
|
|
588
|
+
};
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
function assertSafeProjectGuidance(workspace) {
|
|
592
|
+
resolveProjectDirectoryTarget(workspace, '.joripspace');
|
|
593
|
+
for (const relative of [
|
|
594
|
+
'.env.joripspace',
|
|
595
|
+
'.gitignore',
|
|
596
|
+
'AGENTS.md',
|
|
597
|
+
'CLAUDE.md',
|
|
598
|
+
'.joripspace/project',
|
|
599
|
+
'.joripspace/project.json',
|
|
600
|
+
'.joripspace/agent-session.json',
|
|
601
|
+
...LEGACY_HELPER_FILES.map(([relative]) => relative),
|
|
602
|
+
]) {
|
|
603
|
+
managedProjectFilePath(workspace, relative);
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
function managedProjectFilePath(workspace, relative) {
|
|
608
|
+
const location = resolveProjectFileTarget(workspace, relative);
|
|
609
|
+
if (location.blockers.length) {
|
|
610
|
+
throw new Error(`managed project file path is blocked: ${location.blockers.join(', ')}`);
|
|
611
|
+
}
|
|
612
|
+
return location.target;
|
|
613
|
+
}
|
|
614
|
+
|
|
555
615
|
function upsertStartAgentsBlock(source) {
|
|
556
616
|
const block = projectAgentsFile();
|
|
557
|
-
let current = String(source || '').replace(/\r\n/g, '\n');
|
|
558
|
-
const ranges = [
|
|
559
|
-
[START_AGENTS_START, START_AGENTS_END],
|
|
560
|
-
[LEGACY_AGENTS_START, LEGACY_AGENTS_END],
|
|
561
|
-
];
|
|
562
|
-
for (const [startMarker, endMarker] of ranges) {
|
|
563
|
-
while (current.includes(startMarker) || current.includes(endMarker)) {
|
|
564
|
-
const start = current.indexOf(startMarker);
|
|
565
|
-
const end = current.indexOf(endMarker, Math.max(0, start + startMarker.length));
|
|
566
|
-
if (start < 0 || end < 0 || end < start) {
|
|
567
|
-
throw startError(
|
|
568
|
-
'invalid_agents_managed_block',
|
|
569
|
-
'AGENTS.md contains an incomplete JoripSpace managed block'
|
|
570
|
-
);
|
|
571
|
-
}
|
|
572
|
-
current = `${current.slice(0, start)}${current.slice(end + endMarker.length)}`;
|
|
573
|
-
}
|
|
574
|
-
}
|
|
575
|
-
const unmanaged = current.replace(/^\n+/, '').replace(/\n+$/, '');
|
|
576
|
-
return unmanaged ? `${block}\n\n${unmanaged}\n` : `${block}\n`;
|
|
577
|
-
}
|
|
578
|
-
|
|
579
|
-
function upsertClaudeAgentsReference(source) {
|
|
580
|
-
const original = String(source || '');
|
|
581
|
-
const bom = original.startsWith('\uFEFF') ? '\uFEFF' : '';
|
|
582
|
-
const body = bom ? original.slice(1) : original;
|
|
583
|
-
const newline = body.match(/\r\n|\n|\r/)?.[0] || '\n';
|
|
584
|
-
const topReference = /^[ \t]*@AGENTS\.md[ \t]*(?:\r\n|\n|\r|$)/.test(body);
|
|
585
|
-
let remainder = body.replace(/^[ \t]*@AGENTS\.md[ \t]*(?:\r\n|\n|\r|$)/gm, '');
|
|
586
|
-
if (topReference) remainder = remainder.replace(/^(?:\r\n|\n|\r)/, '');
|
|
587
|
-
return remainder ? `${bom}@AGENTS.md${newline}${newline}${remainder}` : `${bom}@AGENTS.md${newline}`;
|
|
588
|
-
}
|
|
589
|
-
|
|
590
|
-
function projectMatches(candidate, projectId) {
|
|
591
|
-
const requested = String(projectId).toLowerCase();
|
|
592
|
-
return [candidate?.name, candidate?.project_slug, candidate?.slug]
|
|
593
|
-
.filter(Boolean)
|
|
594
|
-
.some((value) => String(value).toLowerCase() === requested);
|
|
595
|
-
}
|
|
596
|
-
|
|
597
|
-
function canonicalProjectSlug(candidate) {
|
|
598
|
-
return String(candidate?.project_slug || candidate?.slug || '').trim();
|
|
599
|
-
}
|
|
600
|
-
|
|
601
|
-
function parseProjectMarker(source) {
|
|
602
|
-
const value = String(source || '');
|
|
603
|
-
if (!/^[^\r\n]+(?:\r?\n)?$/.test(value)) {
|
|
604
|
-
throw startError(
|
|
605
|
-
'invalid_project_marker',
|
|
606
|
-
'.joripspace/project must contain exactly one project slug line'
|
|
607
|
-
);
|
|
608
|
-
}
|
|
609
|
-
const slug = value.replace(/\r?\n$/, '');
|
|
610
|
-
if (!PROJECT_SLUG_PATTERN.test(slug)) {
|
|
611
|
-
throw startError('invalid_project_marker', '.joripspace/project must contain a canonical project slug');
|
|
612
|
-
}
|
|
613
|
-
return slug;
|
|
614
|
-
}
|
|
615
|
-
|
|
616
|
-
function inspectProjectWorkspace(workspace, projectSlug, options = {}) {
|
|
617
|
-
const portablePaths = [
|
|
618
|
-
'AGENTS.md',
|
|
619
|
-
'CLAUDE.md',
|
|
620
|
-
'.joripspace/project',
|
|
621
|
-
'.joripspace/project.json',
|
|
622
|
-
'.joripspace/agent-session.json',
|
|
623
|
-
...LEGACY_HELPER_FILES.map(([relative]) => relative),
|
|
624
|
-
];
|
|
625
|
-
const casingConflicts = portablePaths.flatMap((relative) => portablePathConflicts(workspace, relative));
|
|
626
|
-
if (casingConflicts.length) {
|
|
627
|
-
return {
|
|
628
|
-
ok: false,
|
|
629
|
-
status: 'non_canonical_workspace_path',
|
|
630
|
-
conflicts: casingConflicts,
|
|
631
|
-
nextAction: 'rename-the-reported-paths-to-their-canonical-lowercase-or-uppercase-spelling',
|
|
632
|
-
};
|
|
633
|
-
}
|
|
634
|
-
|
|
635
|
-
const marker = readProjectMarker(workspace);
|
|
636
|
-
if (marker && marker !== projectSlug) {
|
|
637
|
-
return {
|
|
638
|
-
ok: false,
|
|
639
|
-
status: 'project_conflict',
|
|
640
|
-
existingProject: marker,
|
|
641
|
-
nextAction: 'choose-a-folder-without-a-different-joripspace-project',
|
|
642
|
-
};
|
|
643
|
-
}
|
|
644
|
-
|
|
645
|
-
const legacyProjectPath = managedProjectFilePath(workspace, '.joripspace/project.json');
|
|
646
|
-
let legacyProject = null;
|
|
647
|
-
let legacyProjectSnapshot = null;
|
|
648
|
-
if (fs.existsSync(legacyProjectPath)) {
|
|
649
|
-
legacyProjectSnapshot = readMigrationSnapshot(legacyProjectPath);
|
|
650
|
-
legacyProject = parseJsonForMigration(
|
|
651
|
-
legacyProjectSnapshot.source.toString('utf8'),
|
|
652
|
-
legacyProjectPath,
|
|
653
|
-
'legacy project configuration'
|
|
654
|
-
);
|
|
655
|
-
const legacySlug = String(legacyProject.project_slug || legacyProject.project_id || '').trim();
|
|
656
|
-
if (!PROJECT_SLUG_PATTERN.test(legacySlug)) {
|
|
657
|
-
return {
|
|
658
|
-
ok: false,
|
|
659
|
-
status: 'legacy_workspace_migration_blocked',
|
|
660
|
-
conflicts: ['.joripspace/project.json has no canonical project slug'],
|
|
661
|
-
nextAction: 'repair-or-remove-the-invalid-legacy-project-file',
|
|
662
|
-
};
|
|
663
|
-
}
|
|
664
|
-
if (legacySlug !== projectSlug) {
|
|
665
|
-
return {
|
|
666
|
-
ok: false,
|
|
667
|
-
status: 'project_conflict',
|
|
668
|
-
existingProject: legacySlug,
|
|
669
|
-
nextAction: 'choose-a-folder-without-a-different-joripspace-project',
|
|
670
|
-
};
|
|
671
|
-
}
|
|
672
|
-
const legacyProjectConflicts = validateGeneratedLegacyProject(legacyProject);
|
|
673
|
-
if (legacyProjectConflicts.length) {
|
|
674
|
-
return {
|
|
675
|
-
ok: false,
|
|
676
|
-
status: 'legacy_workspace_migration_blocked',
|
|
677
|
-
conflicts: legacyProjectConflicts,
|
|
678
|
-
nextAction: 'preserve-and-review-the-nonstandard-legacy-project-file',
|
|
679
|
-
};
|
|
680
|
-
}
|
|
681
|
-
}
|
|
682
|
-
|
|
683
|
-
const sessionPath = managedProjectFilePath(workspace, '.joripspace/agent-session.json');
|
|
684
|
-
let legacySession = null;
|
|
685
|
-
let legacySessionSnapshot = null;
|
|
686
|
-
if (fs.existsSync(sessionPath)) {
|
|
687
|
-
legacySessionSnapshot = readMigrationSnapshot(sessionPath);
|
|
688
|
-
legacySession = parseJsonForMigration(
|
|
689
|
-
legacySessionSnapshot.source.toString('utf8'),
|
|
690
|
-
sessionPath,
|
|
691
|
-
'legacy agent session'
|
|
692
|
-
);
|
|
693
|
-
const sessionValidation = validateGeneratedLegacySession(legacySession);
|
|
694
|
-
if (!sessionValidation.ok) {
|
|
695
|
-
return {
|
|
696
|
-
ok: false,
|
|
697
|
-
status: 'legacy_workspace_migration_blocked',
|
|
698
|
-
conflicts: sessionValidation.conflicts,
|
|
699
|
-
nextAction: 'preserve-and-review-the-nonstandard-legacy-agent-session',
|
|
700
|
-
};
|
|
701
|
-
}
|
|
702
|
-
if (sessionValidation.connection && !options.allowLegacyCredentialSession) {
|
|
703
|
-
return {
|
|
704
|
-
ok: false,
|
|
705
|
-
status: 'legacy_workspace_migration_blocked',
|
|
706
|
-
conflicts: ['.joripspace/agent-session.json still contains credential values'],
|
|
707
|
-
nextAction: 'run-login-to-migrate-the-legacy-token-before-starting-again',
|
|
708
|
-
};
|
|
709
|
-
}
|
|
710
|
-
const sessionProject = legacySession.project || {};
|
|
711
|
-
const sessionSlug = String(
|
|
712
|
-
sessionProject.slug || legacySession.project_slug || legacySession.project_id || sessionProject.id || ''
|
|
713
|
-
).trim();
|
|
714
|
-
if (sessionSlug && sessionSlug !== projectSlug) {
|
|
715
|
-
return {
|
|
716
|
-
ok: false,
|
|
717
|
-
status: 'project_conflict',
|
|
718
|
-
existingProject: sessionSlug,
|
|
719
|
-
nextAction: 'choose-a-folder-without-a-different-joripspace-project',
|
|
720
|
-
};
|
|
721
|
-
}
|
|
722
|
-
}
|
|
723
|
-
|
|
724
|
-
const legacyConfig = legacyProject || { project_id: projectSlug, project_slug: projectSlug };
|
|
725
|
-
const helperCleanup = inspectLegacyHelpers(workspace, legacyConfig);
|
|
726
|
-
if (helperCleanup.conflicts.length) {
|
|
727
|
-
return {
|
|
728
|
-
ok: false,
|
|
729
|
-
status: 'legacy_workspace_migration_blocked',
|
|
730
|
-
conflicts: helperCleanup.conflicts,
|
|
731
|
-
nextAction: 'review-modified-legacy-helper-files-before-running-start-again',
|
|
732
|
-
};
|
|
733
|
-
}
|
|
734
|
-
const hasLegacyArtifacts = Boolean(legacyProject || legacySession || helperCleanup.snapshots.length);
|
|
735
|
-
const packageCleanup = hasLegacyArtifacts ? inspectLegacyPackageScripts(workspace) : null;
|
|
736
|
-
if (packageCleanup?.conflicts.length) {
|
|
737
|
-
return {
|
|
738
|
-
ok: false,
|
|
739
|
-
status: 'legacy_workspace_migration_blocked',
|
|
740
|
-
conflicts: packageCleanup.conflicts,
|
|
741
|
-
nextAction: 'review-modified-legacy-package-scripts-before-running-start-again',
|
|
742
|
-
};
|
|
743
|
-
}
|
|
744
|
-
return {
|
|
745
|
-
ok: true,
|
|
746
|
-
marker,
|
|
747
|
-
legacyProjectPath: legacyProject ? legacyProjectPath : null,
|
|
748
|
-
legacySessionPath: legacySession ? sessionPath : null,
|
|
749
|
-
helperPaths: helperCleanup.snapshots.map((snapshot) => snapshot.path),
|
|
750
|
-
packageCleanup,
|
|
751
|
-
cleanupSnapshots: [
|
|
752
|
-
legacyProject ? legacyProjectSnapshot : null,
|
|
753
|
-
legacySession ? legacySessionSnapshot : null,
|
|
754
|
-
...helperCleanup.snapshots,
|
|
755
|
-
].filter(Boolean),
|
|
756
|
-
onlyManagedFiles: workspaceContainsOnlyManagedFiles(workspace),
|
|
757
|
-
};
|
|
758
|
-
}
|
|
759
|
-
|
|
760
|
-
function validateGeneratedLegacyProject(project) {
|
|
761
|
-
const unknownKeys = Object.keys(project).filter((key) => !LEGACY_PROJECT_KEYS.has(key));
|
|
762
|
-
if (unknownKeys.length) {
|
|
763
|
-
return unknownKeys.map((key) => `.joripspace/project.json contains an unknown field: ${key}`);
|
|
764
|
-
}
|
|
765
|
-
const conflicts = [];
|
|
766
|
-
if (project.onboarding_schema_version !== 9) {
|
|
767
|
-
conflicts.push('.joripspace/project.json is not a generated schema version 9 file');
|
|
768
|
-
}
|
|
769
|
-
for (const key of ['agent_guide_updated_at', 'project_id', 'project_slug', 'api_base_url']) {
|
|
770
|
-
if (typeof project[key] !== 'string' || !project[key].trim()) {
|
|
771
|
-
conflicts.push(`.joripspace/project.json field ${key} is invalid`);
|
|
772
|
-
}
|
|
773
|
-
}
|
|
774
|
-
if (project.project_id !== project.project_slug) {
|
|
775
|
-
conflicts.push('.joripspace/project.json project_id and project_slug do not match');
|
|
776
|
-
}
|
|
777
|
-
for (const key of ['deployment_policy', 'deployment']) {
|
|
778
|
-
if (!project[key] || typeof project[key] !== 'object' || Array.isArray(project[key])) {
|
|
779
|
-
conflicts.push(`.joripspace/project.json field ${key} is invalid`);
|
|
780
|
-
}
|
|
781
|
-
}
|
|
782
|
-
if (project.deployment_policy && typeof project.deployment_policy === 'object') {
|
|
783
|
-
const expectedPolicy = loadCoreOnboardingPackage().JORIPSPACE_WORKFLOW_POLICY;
|
|
784
|
-
if (!deepEqualJson(project.deployment_policy, expectedPolicy)) {
|
|
785
|
-
conflicts.push('.joripspace/project.json deployment_policy differs from the generated policy');
|
|
786
|
-
}
|
|
787
|
-
}
|
|
788
|
-
if (project.deployment && typeof project.deployment === 'object') {
|
|
789
|
-
const deploymentUnknown = Object.keys(project.deployment).filter(
|
|
790
|
-
(key) => !LEGACY_DEPLOYMENT_KEYS.has(key)
|
|
791
|
-
);
|
|
792
|
-
conflicts.push(
|
|
793
|
-
...deploymentUnknown.map(
|
|
794
|
-
(key) => `.joripspace/project.json deployment contains an unknown field: ${key}`
|
|
795
|
-
)
|
|
796
|
-
);
|
|
797
|
-
if (!['direct', 'github_actions'].includes(project.deployment.mode)) {
|
|
798
|
-
conflicts.push('.joripspace/project.json deployment mode is invalid');
|
|
799
|
-
}
|
|
800
|
-
if (
|
|
801
|
-
project.deployment.connection_status !== undefined &&
|
|
802
|
-
typeof project.deployment.connection_status !== 'string'
|
|
803
|
-
) {
|
|
804
|
-
conflicts.push('.joripspace/project.json deployment connection_status is invalid');
|
|
805
|
-
}
|
|
806
|
-
if (project.deployment.connections !== undefined) {
|
|
807
|
-
if (!Array.isArray(project.deployment.connections)) {
|
|
808
|
-
conflicts.push('.joripspace/project.json deployment connections is invalid');
|
|
809
|
-
} else {
|
|
810
|
-
for (const [index, connection] of project.deployment.connections.entries()) {
|
|
811
|
-
if (!connection || typeof connection !== 'object' || Array.isArray(connection)) {
|
|
812
|
-
conflicts.push(`.joripspace/project.json deployment connection ${index} is invalid`);
|
|
813
|
-
continue;
|
|
814
|
-
}
|
|
815
|
-
const unknown = Object.keys(connection).filter(
|
|
816
|
-
(key) => !LEGACY_DEPLOYMENT_CONNECTION_KEYS.has(key)
|
|
817
|
-
);
|
|
818
|
-
conflicts.push(
|
|
819
|
-
...unknown.map(
|
|
820
|
-
(key) =>
|
|
821
|
-
`.joripspace/project.json deployment connection ${index} contains an unknown field: ${key}`
|
|
822
|
-
)
|
|
823
|
-
);
|
|
824
|
-
}
|
|
825
|
-
}
|
|
826
|
-
}
|
|
827
|
-
}
|
|
828
|
-
for (const key of ['default_url', 'mcp_url']) {
|
|
829
|
-
if (project[key] !== undefined && project[key] !== null && typeof project[key] !== 'string') {
|
|
830
|
-
conflicts.push(`.joripspace/project.json field ${key} is invalid`);
|
|
831
|
-
}
|
|
832
|
-
}
|
|
833
|
-
try {
|
|
834
|
-
const apiUrl = new URL(project.api_base_url);
|
|
835
|
-
if (!['http:', 'https:'].includes(apiUrl.protocol) || apiUrl.username || apiUrl.password) {
|
|
836
|
-
conflicts.push('.joripspace/project.json api_base_url is invalid');
|
|
837
|
-
}
|
|
838
|
-
} catch {
|
|
839
|
-
conflicts.push('.joripspace/project.json api_base_url is invalid');
|
|
840
|
-
}
|
|
841
|
-
return [...new Set(conflicts)];
|
|
842
|
-
}
|
|
843
|
-
|
|
844
|
-
function validateGeneratedLegacySession(session) {
|
|
845
|
-
if (containsCredentialValue(session)) {
|
|
846
|
-
try {
|
|
847
|
-
const connection = legacyCredentialSessionConnection(session);
|
|
848
|
-
return connection
|
|
849
|
-
? { ok: true, connection, conflicts: [] }
|
|
850
|
-
: {
|
|
851
|
-
ok: false,
|
|
852
|
-
connection: null,
|
|
853
|
-
conflicts: ['.joripspace/agent-session.json has an unsupported credential schema'],
|
|
854
|
-
};
|
|
855
|
-
} catch (error) {
|
|
856
|
-
return { ok: false, connection: null, conflicts: [error.message] };
|
|
857
|
-
}
|
|
858
|
-
}
|
|
859
|
-
const topKeys = ['schema_version', 'scope', 'project', 'agent_guide', 'collaboration', 'local_auth'];
|
|
860
|
-
if (!hasExactObjectKeys(session, topKeys)) {
|
|
861
|
-
return {
|
|
862
|
-
ok: false,
|
|
863
|
-
connection: null,
|
|
864
|
-
conflicts: ['.joripspace/agent-session.json is not a generated shared-workspace session'],
|
|
865
|
-
};
|
|
866
|
-
}
|
|
867
|
-
const valid =
|
|
868
|
-
session.schema_version === 2 &&
|
|
869
|
-
session.scope === 'shared_workspace' &&
|
|
870
|
-
hasExactObjectKeys(session.project, ['id', 'slug', 'config_file']) &&
|
|
871
|
-
typeof session.project.id === 'string' &&
|
|
872
|
-
typeof session.project.slug === 'string' &&
|
|
873
|
-
['.joripspace/project', '.joripspace/project.json'].includes(session.project.config_file) &&
|
|
874
|
-
hasExactObjectKeys(session.agent_guide, ['updated_at']) &&
|
|
875
|
-
typeof session.agent_guide.updated_at === 'string' &&
|
|
876
|
-
hasExactObjectKeys(session.collaboration, ['git_tracked']) &&
|
|
877
|
-
session.collaboration.git_tracked === true &&
|
|
878
|
-
hasExactObjectKeys(session.local_auth, [
|
|
879
|
-
'env_file',
|
|
880
|
-
'required_environment',
|
|
881
|
-
'credential_values_in_session',
|
|
882
|
-
]) &&
|
|
883
|
-
session.local_auth.env_file === '.env.joripspace' &&
|
|
884
|
-
Array.isArray(session.local_auth.required_environment) &&
|
|
885
|
-
session.local_auth.required_environment.length === 1 &&
|
|
886
|
-
session.local_auth.required_environment[0] === 'JORIPSPACE_API_TOKEN' &&
|
|
887
|
-
session.local_auth.credential_values_in_session === false;
|
|
888
|
-
return valid
|
|
889
|
-
? { ok: true, connection: null, conflicts: [] }
|
|
890
|
-
: {
|
|
891
|
-
ok: false,
|
|
892
|
-
connection: null,
|
|
893
|
-
conflicts: ['.joripspace/agent-session.json has an unsupported generated shape'],
|
|
894
|
-
};
|
|
895
|
-
}
|
|
896
|
-
|
|
897
|
-
function legacyCredentialSessionConnection(session) {
|
|
898
|
-
if (!session || typeof session !== 'object' || Array.isArray(session)) return null;
|
|
899
|
-
const apiToken = typeof session.api_token === 'string' ? session.api_token.trim() : '';
|
|
900
|
-
const connectToken = typeof session.connect_token === 'string' ? session.connect_token.trim() : '';
|
|
901
|
-
if (!apiToken && !connectToken) return null;
|
|
902
|
-
const unknown = Object.keys(session).filter((key) => !LEGACY_CREDENTIAL_SESSION_KEYS.has(key));
|
|
903
|
-
if (unknown.length) {
|
|
904
|
-
throw startError(
|
|
905
|
-
'legacy_workspace_migration_blocked',
|
|
906
|
-
`.joripspace/agent-session.json contains an unknown field: ${unknown[0]}`
|
|
907
|
-
);
|
|
908
|
-
}
|
|
909
|
-
if (apiToken && connectToken && apiToken !== connectToken) {
|
|
910
|
-
throw startError(
|
|
911
|
-
'legacy_workspace_migration_blocked',
|
|
912
|
-
'.joripspace/agent-session.json contains conflicting connection tokens'
|
|
913
|
-
);
|
|
914
|
-
}
|
|
915
|
-
if (
|
|
916
|
-
typeof session.api_base_url !== 'string' ||
|
|
917
|
-
!session.api_base_url.trim() ||
|
|
918
|
-
(session.source !== undefined && session.source !== 'cli-login') ||
|
|
919
|
-
(session.updated_at !== undefined && typeof session.updated_at !== 'string') ||
|
|
920
|
-
typeof session.guide_checked_at !== 'string' ||
|
|
921
|
-
!hasExactObjectKeys(session.account, ['account_id']) ||
|
|
922
|
-
typeof session.account.account_id !== 'string' ||
|
|
923
|
-
(session.global_session_file !== undefined &&
|
|
924
|
-
session.global_session_file !== null &&
|
|
925
|
-
typeof session.global_session_file !== 'string')
|
|
926
|
-
) {
|
|
927
|
-
throw startError(
|
|
928
|
-
'legacy_workspace_migration_blocked',
|
|
929
|
-
'.joripspace/agent-session.json has an unsupported credential schema'
|
|
930
|
-
);
|
|
931
|
-
}
|
|
932
|
-
let apiUrl;
|
|
933
|
-
try {
|
|
934
|
-
apiUrl = new URL(session.api_base_url);
|
|
935
|
-
} catch {
|
|
936
|
-
apiUrl = null;
|
|
937
|
-
}
|
|
938
|
-
if (!apiUrl || !['http:', 'https:'].includes(apiUrl.protocol) || apiUrl.username || apiUrl.password) {
|
|
939
|
-
throw startError(
|
|
940
|
-
'legacy_workspace_migration_blocked',
|
|
941
|
-
'.joripspace/agent-session.json api_base_url is invalid'
|
|
942
|
-
);
|
|
943
|
-
}
|
|
944
|
-
return {
|
|
945
|
-
apiToken: apiToken || connectToken,
|
|
946
|
-
apiBaseUrl: apiUrl.href.replace(/\/+$/, ''),
|
|
947
|
-
accountId: session.account.account_id.trim(),
|
|
948
|
-
};
|
|
949
|
-
}
|
|
950
|
-
|
|
951
|
-
function hasExactObjectKeys(value, keys) {
|
|
952
|
-
if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
|
|
953
|
-
const actual = Object.keys(value).sort();
|
|
954
|
-
const expected = [...keys].sort();
|
|
955
|
-
return actual.length === expected.length && actual.every((key, index) => key === expected[index]);
|
|
956
|
-
}
|
|
957
|
-
|
|
958
|
-
function deepEqualJson(left, right) {
|
|
959
|
-
if (left === right) return true;
|
|
960
|
-
if (!left || !right || typeof left !== 'object' || typeof right !== 'object') return false;
|
|
961
|
-
if (Array.isArray(left) || Array.isArray(right)) {
|
|
962
|
-
return (
|
|
963
|
-
Array.isArray(left) &&
|
|
964
|
-
Array.isArray(right) &&
|
|
965
|
-
left.length === right.length &&
|
|
966
|
-
left.every((value, index) => deepEqualJson(value, right[index]))
|
|
967
|
-
);
|
|
968
|
-
}
|
|
969
|
-
const leftKeys = Object.keys(left).sort();
|
|
970
|
-
const rightKeys = Object.keys(right).sort();
|
|
971
|
-
return (
|
|
972
|
-
leftKeys.length === rightKeys.length &&
|
|
973
|
-
leftKeys.every((key, index) => key === rightKeys[index] && deepEqualJson(left[key], right[key]))
|
|
974
|
-
);
|
|
975
|
-
}
|
|
976
|
-
|
|
977
|
-
function migrateProjectWorkspace(workspace, projectSlug, state, options = {}) {
|
|
978
|
-
for (const snapshot of state.cleanupSnapshots || []) assertMigrationSnapshotUnchanged(snapshot);
|
|
979
|
-
const persistentSnapshots = [
|
|
980
|
-
...(state.packageCleanup?.changed ? [state.packageCleanup.snapshot] : []),
|
|
981
|
-
...(state.cleanupSnapshots || []).filter(
|
|
982
|
-
(snapshot) => path.basename(snapshot.path).toLowerCase() !== 'agent-session.json'
|
|
983
|
-
),
|
|
984
|
-
];
|
|
985
|
-
const backupRoot = persistentSnapshots.length
|
|
986
|
-
? createExternalBackupRoot(workspace, 'legacy-migration', options.dataDir)
|
|
987
|
-
: null;
|
|
988
|
-
if (backupRoot) {
|
|
989
|
-
const backupDevice = fs.statSync(backupRoot).dev;
|
|
990
|
-
for (const snapshot of persistentSnapshots) {
|
|
991
|
-
if (fs.lstatSync(snapshot.path).dev !== backupDevice) {
|
|
992
|
-
throw startError(
|
|
993
|
-
'legacy_workspace_migration_blocked',
|
|
994
|
-
'legacy migration backup must be on the same filesystem as the project'
|
|
995
|
-
);
|
|
996
|
-
}
|
|
997
|
-
}
|
|
998
|
-
}
|
|
999
|
-
if (state.packageCleanup?.changed) {
|
|
1000
|
-
replaceMigrationSnapshotAtomically(
|
|
1001
|
-
workspace,
|
|
1002
|
-
state.packageCleanup.snapshot,
|
|
1003
|
-
`${JSON.stringify(state.packageCleanup.value, null, 2)}\n`,
|
|
1004
|
-
backupRoot,
|
|
1005
|
-
options.afterLegacyPathQuarantined
|
|
1006
|
-
);
|
|
1007
|
-
}
|
|
1008
|
-
for (const snapshot of state.cleanupSnapshots || []) {
|
|
1009
|
-
if (path.basename(snapshot.path).toLowerCase() === 'agent-session.json') {
|
|
1010
|
-
removeMigrationSnapshotAtomically(snapshot, options.afterLegacyPathQuarantined);
|
|
1011
|
-
} else {
|
|
1012
|
-
backupMigrationSnapshotAtomically(
|
|
1013
|
-
workspace,
|
|
1014
|
-
snapshot,
|
|
1015
|
-
backupRoot,
|
|
1016
|
-
options.afterLegacyPathQuarantined,
|
|
1017
|
-
'remove'
|
|
1018
|
-
);
|
|
1019
|
-
}
|
|
1020
|
-
}
|
|
1021
|
-
if (state.legacySessionPath) {
|
|
1022
|
-
removeGitignoreEntries(workspace, ['.joripspace/agent-session.json']);
|
|
1023
|
-
}
|
|
1024
|
-
ensureProjectGuidance(workspace, projectSlug);
|
|
1025
|
-
return { backupRoot };
|
|
1026
|
-
}
|
|
1027
|
-
|
|
1028
|
-
function inspectLegacyHelpers(workspace, projectConfig) {
|
|
1029
|
-
const core = loadCoreOnboardingPackage();
|
|
1030
|
-
const snapshots = [];
|
|
1031
|
-
const conflicts = [];
|
|
1032
|
-
for (const [relative, generatorName] of LEGACY_HELPER_FILES) {
|
|
1033
|
-
const filePath = managedProjectFilePath(workspace, relative);
|
|
1034
|
-
if (!fs.existsSync(filePath)) continue;
|
|
1035
|
-
const generator = core[generatorName];
|
|
1036
|
-
const expected =
|
|
1037
|
-
typeof generator === 'function'
|
|
1038
|
-
? generatorName === 'projectGithubActionsTemplateFile'
|
|
1039
|
-
? generator(projectConfig)
|
|
1040
|
-
: generator()
|
|
1041
|
-
: null;
|
|
1042
|
-
const snapshot = readMigrationSnapshot(filePath);
|
|
1043
|
-
const current = snapshot.source.toString('utf8');
|
|
1044
|
-
if (
|
|
1045
|
-
(typeof expected !== 'string' || current !== expected) &&
|
|
1046
|
-
!looksLikeGeneratedLegacyHelper(relative, current, expected)
|
|
1047
|
-
) {
|
|
1048
|
-
conflicts.push(`${relative} differs from the generated JoripSpace helper`);
|
|
1049
|
-
continue;
|
|
1050
|
-
}
|
|
1051
|
-
snapshots.push(snapshot);
|
|
1052
|
-
}
|
|
1053
|
-
return { conflicts, snapshots };
|
|
1054
|
-
}
|
|
1055
|
-
|
|
1056
|
-
function looksLikeGeneratedLegacyHelper(relative, source, expected) {
|
|
1057
|
-
const value = String(source || '');
|
|
1058
|
-
const legacyHash = LEGACY_HELPER_SHA256[relative];
|
|
1059
|
-
if (legacyHash && crypto.createHash('sha256').update(value).digest('hex') === legacyHash) return true;
|
|
1060
|
-
if (relative !== '.joripspace/github-actions-template.yml' || typeof expected !== 'string') return false;
|
|
1061
|
-
return value === expected.replaceAll('.joripspace/deploy.json', '.joripspace/project.json');
|
|
1062
|
-
}
|
|
1063
|
-
|
|
1064
|
-
function inspectLegacyPackageScripts(workspace) {
|
|
1065
|
-
const packagePath = managedProjectFilePath(workspace, 'package.json');
|
|
1066
|
-
if (!fs.existsSync(packagePath)) {
|
|
1067
|
-
return { changed: false, conflicts: [], path: packagePath, snapshot: null, value: null };
|
|
1068
|
-
}
|
|
1069
|
-
const snapshot = readMigrationSnapshot(packagePath);
|
|
1070
|
-
const value = parseJsonForMigration(snapshot.source.toString('utf8'), packagePath, 'package.json');
|
|
1071
|
-
const expectedScripts = loadCoreOnboardingPackage().projectPackageHelperScripts();
|
|
1072
|
-
const scripts =
|
|
1073
|
-
value.scripts && typeof value.scripts === 'object' && !Array.isArray(value.scripts)
|
|
1074
|
-
? { ...value.scripts }
|
|
1075
|
-
: {};
|
|
1076
|
-
const conflicts = [];
|
|
1077
|
-
let changed = false;
|
|
1078
|
-
for (const [name, expected] of Object.entries(expectedScripts)) {
|
|
1079
|
-
if (scripts[name] === undefined) continue;
|
|
1080
|
-
if (scripts[name] !== expected) {
|
|
1081
|
-
if (String(scripts[name]).includes('.joripspace/')) {
|
|
1082
|
-
conflicts.push(`package.json script ${name} differs from the generated JoripSpace command`);
|
|
1083
|
-
}
|
|
1084
|
-
continue;
|
|
1085
|
-
}
|
|
1086
|
-
delete scripts[name];
|
|
1087
|
-
changed = true;
|
|
1088
|
-
}
|
|
1089
|
-
return {
|
|
1090
|
-
changed,
|
|
1091
|
-
conflicts,
|
|
1092
|
-
path: packagePath,
|
|
1093
|
-
snapshot,
|
|
1094
|
-
value: changed ? { ...value, scripts } : value,
|
|
1095
|
-
};
|
|
1096
|
-
}
|
|
1097
|
-
|
|
1098
|
-
function parseJsonForMigration(source, filePath, label) {
|
|
1099
|
-
try {
|
|
1100
|
-
const value = JSON.parse(source);
|
|
1101
|
-
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('not an object');
|
|
1102
|
-
return value;
|
|
1103
|
-
} catch {
|
|
1104
|
-
throw startError('legacy_workspace_migration_blocked', `${label} is not valid JSON: ${filePath}`);
|
|
1105
|
-
}
|
|
1106
|
-
}
|
|
1107
|
-
|
|
1108
|
-
function readMigrationSnapshot(filePath) {
|
|
1109
|
-
const before = fs.lstatSync(filePath);
|
|
1110
|
-
if (!before.isFile() || before.isSymbolicLink()) {
|
|
1111
|
-
throw startError(
|
|
1112
|
-
'legacy_workspace_changed_during_migration',
|
|
1113
|
-
`legacy migration target is not a regular file: ${filePath}`
|
|
1114
|
-
);
|
|
1115
|
-
}
|
|
1116
|
-
const source = fs.readFileSync(filePath);
|
|
1117
|
-
const after = fs.lstatSync(filePath);
|
|
1118
|
-
if (
|
|
1119
|
-
!after.isFile() ||
|
|
1120
|
-
after.isSymbolicLink() ||
|
|
1121
|
-
before.dev !== after.dev ||
|
|
1122
|
-
before.ino !== after.ino ||
|
|
1123
|
-
before.size !== after.size ||
|
|
1124
|
-
before.mtimeMs !== after.mtimeMs ||
|
|
1125
|
-
before.ctimeMs !== after.ctimeMs
|
|
1126
|
-
) {
|
|
1127
|
-
throw startError(
|
|
1128
|
-
'legacy_workspace_changed_during_migration',
|
|
1129
|
-
`legacy migration target changed while it was being validated: ${filePath}`
|
|
1130
|
-
);
|
|
1131
|
-
}
|
|
1132
|
-
return { path: filePath, source, mode: before.mode };
|
|
1133
|
-
}
|
|
1134
|
-
|
|
1135
|
-
function assertMigrationSnapshotUnchanged(snapshot) {
|
|
1136
|
-
if (!snapshot) return;
|
|
1137
|
-
let current;
|
|
1138
|
-
try {
|
|
1139
|
-
current = readMigrationSnapshot(snapshot.path);
|
|
1140
|
-
} catch {
|
|
1141
|
-
throw startError(
|
|
1142
|
-
'legacy_workspace_changed_during_migration',
|
|
1143
|
-
`legacy migration target changed after validation: ${snapshot.path}`
|
|
1144
|
-
);
|
|
1145
|
-
}
|
|
1146
|
-
if (!current.source.equals(snapshot.source)) {
|
|
1147
|
-
throw startError(
|
|
1148
|
-
'legacy_workspace_changed_during_migration',
|
|
1149
|
-
`legacy migration target changed after validation: ${snapshot.path}`
|
|
1150
|
-
);
|
|
1151
|
-
}
|
|
1152
|
-
}
|
|
1153
|
-
|
|
1154
|
-
function quarantineMigrationSnapshot(snapshot, callback, operation) {
|
|
1155
|
-
assertMigrationSnapshotUnchanged(snapshot);
|
|
1156
|
-
const quarantinePath = `${snapshot.path}.joripspace-migrate-${process.pid}-${crypto.randomUUID()}`;
|
|
1157
|
-
fs.renameSync(snapshot.path, quarantinePath);
|
|
1158
|
-
try {
|
|
1159
|
-
callback?.({ path: snapshot.path, quarantinePath, operation });
|
|
1160
|
-
const quarantined = readMigrationSnapshot(quarantinePath);
|
|
1161
|
-
if (!quarantined.source.equals(snapshot.source)) {
|
|
1162
|
-
throw startError(
|
|
1163
|
-
'legacy_workspace_changed_during_migration',
|
|
1164
|
-
`legacy migration target changed after it was quarantined: ${snapshot.path}`
|
|
1165
|
-
);
|
|
1166
|
-
}
|
|
1167
|
-
if (fs.existsSync(snapshot.path)) {
|
|
1168
|
-
fs.rmSync(quarantinePath, { force: true });
|
|
1169
|
-
throw startError(
|
|
1170
|
-
'legacy_workspace_changed_during_migration',
|
|
1171
|
-
`legacy migration target was recreated during migration: ${snapshot.path}`
|
|
1172
|
-
);
|
|
1173
|
-
}
|
|
1174
|
-
return quarantinePath;
|
|
1175
|
-
} catch (error) {
|
|
1176
|
-
restoreMigrationSnapshotWithoutOverwrite(quarantinePath, snapshot.path, true);
|
|
1177
|
-
throw error;
|
|
1178
|
-
}
|
|
1179
|
-
}
|
|
1180
|
-
|
|
1181
|
-
function backupMigrationSnapshotAtomically(workspace, snapshot, backupRoot, callback, operation) {
|
|
1182
|
-
if (!backupRoot) {
|
|
1183
|
-
throw startError('legacy_workspace_migration_blocked', 'legacy migration backup is unavailable');
|
|
1184
|
-
}
|
|
1185
|
-
assertMigrationSnapshotUnchanged(snapshot);
|
|
617
|
+
let current = String(source || '').replace(/\r\n/g, '\n');
|
|
618
|
+
const ranges = [
|
|
619
|
+
[START_AGENTS_START, START_AGENTS_END],
|
|
620
|
+
[LEGACY_AGENTS_START, LEGACY_AGENTS_END],
|
|
621
|
+
];
|
|
622
|
+
for (const [startMarker, endMarker] of ranges) {
|
|
623
|
+
while (current.includes(startMarker) || current.includes(endMarker)) {
|
|
624
|
+
const start = current.indexOf(startMarker);
|
|
625
|
+
const end = current.indexOf(endMarker, Math.max(0, start + startMarker.length));
|
|
626
|
+
if (start < 0 || end < 0 || end < start) {
|
|
627
|
+
throw startError(
|
|
628
|
+
'invalid_agents_managed_block',
|
|
629
|
+
'AGENTS.md contains an incomplete JoripSpace managed block'
|
|
630
|
+
);
|
|
631
|
+
}
|
|
632
|
+
current = `${current.slice(0, start)}${current.slice(end + endMarker.length)}`;
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
const unmanaged = current.replace(/^\n+/, '').replace(/\n+$/, '');
|
|
636
|
+
return unmanaged ? `${block}\n\n${unmanaged}\n` : `${block}\n`;
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
function upsertClaudeAgentsReference(source) {
|
|
640
|
+
const original = String(source || '');
|
|
641
|
+
const bom = original.startsWith('\uFEFF') ? '\uFEFF' : '';
|
|
642
|
+
const body = bom ? original.slice(1) : original;
|
|
643
|
+
const newline = body.match(/\r\n|\n|\r/)?.[0] || '\n';
|
|
644
|
+
const topReference = /^[ \t]*@AGENTS\.md[ \t]*(?:\r\n|\n|\r|$)/.test(body);
|
|
645
|
+
let remainder = body.replace(/^[ \t]*@AGENTS\.md[ \t]*(?:\r\n|\n|\r|$)/gm, '');
|
|
646
|
+
if (topReference) remainder = remainder.replace(/^(?:\r\n|\n|\r)/, '');
|
|
647
|
+
return remainder ? `${bom}@AGENTS.md${newline}${newline}${remainder}` : `${bom}@AGENTS.md${newline}`;
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
function projectMatches(candidate, projectId) {
|
|
651
|
+
const requested = String(projectId).toLowerCase();
|
|
652
|
+
return [candidate?.name, candidate?.project_slug, candidate?.slug]
|
|
653
|
+
.filter(Boolean)
|
|
654
|
+
.some((value) => String(value).toLowerCase() === requested);
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
function canonicalProjectSlug(candidate) {
|
|
658
|
+
return String(candidate?.project_slug || candidate?.slug || '').trim();
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
function parseProjectMarker(source) {
|
|
662
|
+
const value = String(source || '');
|
|
663
|
+
if (!/^[^\r\n]+(?:\r?\n)?$/.test(value)) {
|
|
664
|
+
throw startError(
|
|
665
|
+
'invalid_project_marker',
|
|
666
|
+
'.joripspace/project must contain exactly one project slug line'
|
|
667
|
+
);
|
|
668
|
+
}
|
|
669
|
+
const slug = value.replace(/\r?\n$/, '');
|
|
670
|
+
if (!PROJECT_SLUG_PATTERN.test(slug)) {
|
|
671
|
+
throw startError('invalid_project_marker', '.joripspace/project must contain a canonical project slug');
|
|
672
|
+
}
|
|
673
|
+
return slug;
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
function inspectProjectWorkspace(workspace, projectSlug, options = {}) {
|
|
677
|
+
const portablePaths = [
|
|
678
|
+
'AGENTS.md',
|
|
679
|
+
'CLAUDE.md',
|
|
680
|
+
'.joripspace/project',
|
|
681
|
+
'.joripspace/project.json',
|
|
682
|
+
'.joripspace/agent-session.json',
|
|
683
|
+
...LEGACY_HELPER_FILES.map(([relative]) => relative),
|
|
684
|
+
];
|
|
685
|
+
const casingConflicts = portablePaths.flatMap((relative) => portablePathConflicts(workspace, relative));
|
|
686
|
+
if (casingConflicts.length) {
|
|
687
|
+
return {
|
|
688
|
+
ok: false,
|
|
689
|
+
status: 'non_canonical_workspace_path',
|
|
690
|
+
conflicts: casingConflicts,
|
|
691
|
+
nextAction: 'rename-the-reported-paths-to-their-canonical-lowercase-or-uppercase-spelling',
|
|
692
|
+
};
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
const marker = readProjectMarker(workspace);
|
|
696
|
+
if (marker && marker !== projectSlug) {
|
|
697
|
+
return {
|
|
698
|
+
ok: false,
|
|
699
|
+
status: 'project_conflict',
|
|
700
|
+
existingProject: marker,
|
|
701
|
+
nextAction: 'choose-a-folder-without-a-different-joripspace-project',
|
|
702
|
+
};
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
const legacyProjectPath = managedProjectFilePath(workspace, '.joripspace/project.json');
|
|
706
|
+
let legacyProject = null;
|
|
707
|
+
let legacyProjectSnapshot = null;
|
|
708
|
+
if (fs.existsSync(legacyProjectPath)) {
|
|
709
|
+
legacyProjectSnapshot = readMigrationSnapshot(legacyProjectPath);
|
|
710
|
+
legacyProject = parseJsonForMigration(
|
|
711
|
+
legacyProjectSnapshot.source.toString('utf8'),
|
|
712
|
+
legacyProjectPath,
|
|
713
|
+
'legacy project configuration'
|
|
714
|
+
);
|
|
715
|
+
const legacySlug = String(legacyProject.project_slug || legacyProject.project_id || '').trim();
|
|
716
|
+
if (!PROJECT_SLUG_PATTERN.test(legacySlug)) {
|
|
717
|
+
return {
|
|
718
|
+
ok: false,
|
|
719
|
+
status: 'legacy_workspace_migration_blocked',
|
|
720
|
+
conflicts: ['.joripspace/project.json has no canonical project slug'],
|
|
721
|
+
nextAction: 'repair-or-remove-the-invalid-legacy-project-file',
|
|
722
|
+
};
|
|
723
|
+
}
|
|
724
|
+
if (legacySlug !== projectSlug) {
|
|
725
|
+
return {
|
|
726
|
+
ok: false,
|
|
727
|
+
status: 'project_conflict',
|
|
728
|
+
existingProject: legacySlug,
|
|
729
|
+
nextAction: 'choose-a-folder-without-a-different-joripspace-project',
|
|
730
|
+
};
|
|
731
|
+
}
|
|
732
|
+
const legacyProjectConflicts = validateGeneratedLegacyProject(legacyProject);
|
|
733
|
+
if (legacyProjectConflicts.length) {
|
|
734
|
+
return {
|
|
735
|
+
ok: false,
|
|
736
|
+
status: 'legacy_workspace_migration_blocked',
|
|
737
|
+
conflicts: legacyProjectConflicts,
|
|
738
|
+
nextAction: 'preserve-and-review-the-nonstandard-legacy-project-file',
|
|
739
|
+
};
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
const sessionPath = managedProjectFilePath(workspace, '.joripspace/agent-session.json');
|
|
744
|
+
let legacySession = null;
|
|
745
|
+
let legacySessionSnapshot = null;
|
|
746
|
+
if (fs.existsSync(sessionPath)) {
|
|
747
|
+
legacySessionSnapshot = readMigrationSnapshot(sessionPath);
|
|
748
|
+
legacySession = parseJsonForMigration(
|
|
749
|
+
legacySessionSnapshot.source.toString('utf8'),
|
|
750
|
+
sessionPath,
|
|
751
|
+
'legacy agent session'
|
|
752
|
+
);
|
|
753
|
+
const sessionValidation = validateGeneratedLegacySession(legacySession);
|
|
754
|
+
if (!sessionValidation.ok) {
|
|
755
|
+
return {
|
|
756
|
+
ok: false,
|
|
757
|
+
status: 'legacy_workspace_migration_blocked',
|
|
758
|
+
conflicts: sessionValidation.conflicts,
|
|
759
|
+
nextAction: 'preserve-and-review-the-nonstandard-legacy-agent-session',
|
|
760
|
+
};
|
|
761
|
+
}
|
|
762
|
+
if (sessionValidation.connection && !options.allowLegacyCredentialSession) {
|
|
763
|
+
return {
|
|
764
|
+
ok: false,
|
|
765
|
+
status: 'legacy_workspace_migration_blocked',
|
|
766
|
+
conflicts: ['.joripspace/agent-session.json still contains credential values'],
|
|
767
|
+
nextAction: 'run-login-to-migrate-the-legacy-token-before-starting-again',
|
|
768
|
+
};
|
|
769
|
+
}
|
|
770
|
+
const sessionProject = legacySession.project || {};
|
|
771
|
+
const sessionSlug = String(
|
|
772
|
+
sessionProject.slug || legacySession.project_slug || legacySession.project_id || sessionProject.id || ''
|
|
773
|
+
).trim();
|
|
774
|
+
if (sessionSlug && sessionSlug !== projectSlug) {
|
|
775
|
+
return {
|
|
776
|
+
ok: false,
|
|
777
|
+
status: 'project_conflict',
|
|
778
|
+
existingProject: sessionSlug,
|
|
779
|
+
nextAction: 'choose-a-folder-without-a-different-joripspace-project',
|
|
780
|
+
};
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
const legacyConfig = legacyProject || { project_id: projectSlug, project_slug: projectSlug };
|
|
785
|
+
const helperCleanup = inspectLegacyHelpers(workspace, legacyConfig);
|
|
786
|
+
if (helperCleanup.conflicts.length) {
|
|
787
|
+
return {
|
|
788
|
+
ok: false,
|
|
789
|
+
status: 'legacy_workspace_migration_blocked',
|
|
790
|
+
conflicts: helperCleanup.conflicts,
|
|
791
|
+
nextAction: 'review-modified-legacy-helper-files-before-running-start-again',
|
|
792
|
+
};
|
|
793
|
+
}
|
|
794
|
+
const hasLegacyArtifacts = Boolean(legacyProject || legacySession || helperCleanup.snapshots.length);
|
|
795
|
+
const packageCleanup = hasLegacyArtifacts ? inspectLegacyPackageScripts(workspace) : null;
|
|
796
|
+
if (packageCleanup?.conflicts.length) {
|
|
797
|
+
return {
|
|
798
|
+
ok: false,
|
|
799
|
+
status: 'legacy_workspace_migration_blocked',
|
|
800
|
+
conflicts: packageCleanup.conflicts,
|
|
801
|
+
nextAction: 'review-modified-legacy-package-scripts-before-running-start-again',
|
|
802
|
+
};
|
|
803
|
+
}
|
|
804
|
+
return {
|
|
805
|
+
ok: true,
|
|
806
|
+
marker,
|
|
807
|
+
legacyProjectPath: legacyProject ? legacyProjectPath : null,
|
|
808
|
+
legacySessionPath: legacySession ? sessionPath : null,
|
|
809
|
+
helperPaths: helperCleanup.snapshots.map((snapshot) => snapshot.path),
|
|
810
|
+
packageCleanup,
|
|
811
|
+
cleanupSnapshots: [
|
|
812
|
+
legacyProject ? legacyProjectSnapshot : null,
|
|
813
|
+
legacySession ? legacySessionSnapshot : null,
|
|
814
|
+
...helperCleanup.snapshots,
|
|
815
|
+
].filter(Boolean),
|
|
816
|
+
onlyManagedFiles: workspaceContainsOnlyManagedFiles(workspace),
|
|
817
|
+
};
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
function validateGeneratedLegacyProject(project) {
|
|
821
|
+
const unknownKeys = Object.keys(project).filter((key) => !LEGACY_PROJECT_KEYS.has(key));
|
|
822
|
+
if (unknownKeys.length) {
|
|
823
|
+
return unknownKeys.map((key) => `.joripspace/project.json contains an unknown field: ${key}`);
|
|
824
|
+
}
|
|
825
|
+
const conflicts = [];
|
|
826
|
+
if (project.onboarding_schema_version !== 9) {
|
|
827
|
+
conflicts.push('.joripspace/project.json is not a generated schema version 9 file');
|
|
828
|
+
}
|
|
829
|
+
for (const key of ['agent_guide_updated_at', 'project_id', 'project_slug', 'api_base_url']) {
|
|
830
|
+
if (typeof project[key] !== 'string' || !project[key].trim()) {
|
|
831
|
+
conflicts.push(`.joripspace/project.json field ${key} is invalid`);
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
if (project.project_id !== project.project_slug) {
|
|
835
|
+
conflicts.push('.joripspace/project.json project_id and project_slug do not match');
|
|
836
|
+
}
|
|
837
|
+
for (const key of ['deployment_policy', 'deployment']) {
|
|
838
|
+
if (!project[key] || typeof project[key] !== 'object' || Array.isArray(project[key])) {
|
|
839
|
+
conflicts.push(`.joripspace/project.json field ${key} is invalid`);
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
if (project.deployment_policy && typeof project.deployment_policy === 'object') {
|
|
843
|
+
const expectedPolicy = loadCoreOnboardingPackage().JORIPSPACE_WORKFLOW_POLICY;
|
|
844
|
+
if (!deepEqualJson(project.deployment_policy, expectedPolicy)) {
|
|
845
|
+
conflicts.push('.joripspace/project.json deployment_policy differs from the generated policy');
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
if (project.deployment && typeof project.deployment === 'object') {
|
|
849
|
+
const deploymentUnknown = Object.keys(project.deployment).filter(
|
|
850
|
+
(key) => !LEGACY_DEPLOYMENT_KEYS.has(key)
|
|
851
|
+
);
|
|
852
|
+
conflicts.push(
|
|
853
|
+
...deploymentUnknown.map(
|
|
854
|
+
(key) => `.joripspace/project.json deployment contains an unknown field: ${key}`
|
|
855
|
+
)
|
|
856
|
+
);
|
|
857
|
+
if (!['direct', 'github_actions'].includes(project.deployment.mode)) {
|
|
858
|
+
conflicts.push('.joripspace/project.json deployment mode is invalid');
|
|
859
|
+
}
|
|
860
|
+
if (
|
|
861
|
+
project.deployment.connection_status !== undefined &&
|
|
862
|
+
typeof project.deployment.connection_status !== 'string'
|
|
863
|
+
) {
|
|
864
|
+
conflicts.push('.joripspace/project.json deployment connection_status is invalid');
|
|
865
|
+
}
|
|
866
|
+
if (project.deployment.connections !== undefined) {
|
|
867
|
+
if (!Array.isArray(project.deployment.connections)) {
|
|
868
|
+
conflicts.push('.joripspace/project.json deployment connections is invalid');
|
|
869
|
+
} else {
|
|
870
|
+
for (const [index, connection] of project.deployment.connections.entries()) {
|
|
871
|
+
if (!connection || typeof connection !== 'object' || Array.isArray(connection)) {
|
|
872
|
+
conflicts.push(`.joripspace/project.json deployment connection ${index} is invalid`);
|
|
873
|
+
continue;
|
|
874
|
+
}
|
|
875
|
+
const unknown = Object.keys(connection).filter(
|
|
876
|
+
(key) => !LEGACY_DEPLOYMENT_CONNECTION_KEYS.has(key)
|
|
877
|
+
);
|
|
878
|
+
conflicts.push(
|
|
879
|
+
...unknown.map(
|
|
880
|
+
(key) =>
|
|
881
|
+
`.joripspace/project.json deployment connection ${index} contains an unknown field: ${key}`
|
|
882
|
+
)
|
|
883
|
+
);
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
for (const key of ['default_url', 'mcp_url']) {
|
|
889
|
+
if (project[key] !== undefined && project[key] !== null && typeof project[key] !== 'string') {
|
|
890
|
+
conflicts.push(`.joripspace/project.json field ${key} is invalid`);
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
try {
|
|
894
|
+
const apiUrl = new URL(project.api_base_url);
|
|
895
|
+
if (!['http:', 'https:'].includes(apiUrl.protocol) || apiUrl.username || apiUrl.password) {
|
|
896
|
+
conflicts.push('.joripspace/project.json api_base_url is invalid');
|
|
897
|
+
}
|
|
898
|
+
} catch {
|
|
899
|
+
conflicts.push('.joripspace/project.json api_base_url is invalid');
|
|
900
|
+
}
|
|
901
|
+
return [...new Set(conflicts)];
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
function validateGeneratedLegacySession(session) {
|
|
905
|
+
if (containsCredentialValue(session)) {
|
|
906
|
+
try {
|
|
907
|
+
const connection = legacyCredentialSessionConnection(session);
|
|
908
|
+
return connection
|
|
909
|
+
? { ok: true, connection, conflicts: [] }
|
|
910
|
+
: {
|
|
911
|
+
ok: false,
|
|
912
|
+
connection: null,
|
|
913
|
+
conflicts: ['.joripspace/agent-session.json has an unsupported credential schema'],
|
|
914
|
+
};
|
|
915
|
+
} catch (error) {
|
|
916
|
+
return { ok: false, connection: null, conflicts: [error.message] };
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
const topKeys = ['schema_version', 'scope', 'project', 'agent_guide', 'collaboration', 'local_auth'];
|
|
920
|
+
if (!hasExactObjectKeys(session, topKeys)) {
|
|
921
|
+
return {
|
|
922
|
+
ok: false,
|
|
923
|
+
connection: null,
|
|
924
|
+
conflicts: ['.joripspace/agent-session.json is not a generated shared-workspace session'],
|
|
925
|
+
};
|
|
926
|
+
}
|
|
927
|
+
const valid =
|
|
928
|
+
session.schema_version === 2 &&
|
|
929
|
+
session.scope === 'shared_workspace' &&
|
|
930
|
+
hasExactObjectKeys(session.project, ['id', 'slug', 'config_file']) &&
|
|
931
|
+
typeof session.project.id === 'string' &&
|
|
932
|
+
typeof session.project.slug === 'string' &&
|
|
933
|
+
['.joripspace/project', '.joripspace/project.json'].includes(session.project.config_file) &&
|
|
934
|
+
hasExactObjectKeys(session.agent_guide, ['updated_at']) &&
|
|
935
|
+
typeof session.agent_guide.updated_at === 'string' &&
|
|
936
|
+
hasExactObjectKeys(session.collaboration, ['git_tracked']) &&
|
|
937
|
+
session.collaboration.git_tracked === true &&
|
|
938
|
+
hasExactObjectKeys(session.local_auth, [
|
|
939
|
+
'env_file',
|
|
940
|
+
'required_environment',
|
|
941
|
+
'credential_values_in_session',
|
|
942
|
+
]) &&
|
|
943
|
+
session.local_auth.env_file === '.env.joripspace' &&
|
|
944
|
+
Array.isArray(session.local_auth.required_environment) &&
|
|
945
|
+
session.local_auth.required_environment.length === 1 &&
|
|
946
|
+
session.local_auth.required_environment[0] === 'JORIPSPACE_API_TOKEN' &&
|
|
947
|
+
session.local_auth.credential_values_in_session === false;
|
|
948
|
+
return valid
|
|
949
|
+
? { ok: true, connection: null, conflicts: [] }
|
|
950
|
+
: {
|
|
951
|
+
ok: false,
|
|
952
|
+
connection: null,
|
|
953
|
+
conflicts: ['.joripspace/agent-session.json has an unsupported generated shape'],
|
|
954
|
+
};
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
function legacyCredentialSessionConnection(session) {
|
|
958
|
+
if (!session || typeof session !== 'object' || Array.isArray(session)) return null;
|
|
959
|
+
const apiToken = typeof session.api_token === 'string' ? session.api_token.trim() : '';
|
|
960
|
+
const connectToken = typeof session.connect_token === 'string' ? session.connect_token.trim() : '';
|
|
961
|
+
if (!apiToken && !connectToken) return null;
|
|
962
|
+
const unknown = Object.keys(session).filter((key) => !LEGACY_CREDENTIAL_SESSION_KEYS.has(key));
|
|
963
|
+
if (unknown.length) {
|
|
964
|
+
throw startError(
|
|
965
|
+
'legacy_workspace_migration_blocked',
|
|
966
|
+
`.joripspace/agent-session.json contains an unknown field: ${unknown[0]}`
|
|
967
|
+
);
|
|
968
|
+
}
|
|
969
|
+
if (apiToken && connectToken && apiToken !== connectToken) {
|
|
970
|
+
throw startError(
|
|
971
|
+
'legacy_workspace_migration_blocked',
|
|
972
|
+
'.joripspace/agent-session.json contains conflicting connection tokens'
|
|
973
|
+
);
|
|
974
|
+
}
|
|
975
|
+
if (
|
|
976
|
+
typeof session.api_base_url !== 'string' ||
|
|
977
|
+
!session.api_base_url.trim() ||
|
|
978
|
+
(session.source !== undefined && session.source !== 'cli-login') ||
|
|
979
|
+
(session.updated_at !== undefined && typeof session.updated_at !== 'string') ||
|
|
980
|
+
typeof session.guide_checked_at !== 'string' ||
|
|
981
|
+
!hasExactObjectKeys(session.account, ['account_id']) ||
|
|
982
|
+
typeof session.account.account_id !== 'string' ||
|
|
983
|
+
(session.global_session_file !== undefined &&
|
|
984
|
+
session.global_session_file !== null &&
|
|
985
|
+
typeof session.global_session_file !== 'string')
|
|
986
|
+
) {
|
|
987
|
+
throw startError(
|
|
988
|
+
'legacy_workspace_migration_blocked',
|
|
989
|
+
'.joripspace/agent-session.json has an unsupported credential schema'
|
|
990
|
+
);
|
|
991
|
+
}
|
|
992
|
+
let apiUrl;
|
|
993
|
+
try {
|
|
994
|
+
apiUrl = new URL(session.api_base_url);
|
|
995
|
+
} catch {
|
|
996
|
+
apiUrl = null;
|
|
997
|
+
}
|
|
998
|
+
if (!apiUrl || !['http:', 'https:'].includes(apiUrl.protocol) || apiUrl.username || apiUrl.password) {
|
|
999
|
+
throw startError(
|
|
1000
|
+
'legacy_workspace_migration_blocked',
|
|
1001
|
+
'.joripspace/agent-session.json api_base_url is invalid'
|
|
1002
|
+
);
|
|
1003
|
+
}
|
|
1004
|
+
return {
|
|
1005
|
+
apiToken: apiToken || connectToken,
|
|
1006
|
+
apiBaseUrl: apiUrl.href.replace(/\/+$/, ''),
|
|
1007
|
+
accountId: session.account.account_id.trim(),
|
|
1008
|
+
};
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
function hasExactObjectKeys(value, keys) {
|
|
1012
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
|
|
1013
|
+
const actual = Object.keys(value).sort();
|
|
1014
|
+
const expected = [...keys].sort();
|
|
1015
|
+
return actual.length === expected.length && actual.every((key, index) => key === expected[index]);
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
function deepEqualJson(left, right) {
|
|
1019
|
+
if (left === right) return true;
|
|
1020
|
+
if (!left || !right || typeof left !== 'object' || typeof right !== 'object') return false;
|
|
1021
|
+
if (Array.isArray(left) || Array.isArray(right)) {
|
|
1022
|
+
return (
|
|
1023
|
+
Array.isArray(left) &&
|
|
1024
|
+
Array.isArray(right) &&
|
|
1025
|
+
left.length === right.length &&
|
|
1026
|
+
left.every((value, index) => deepEqualJson(value, right[index]))
|
|
1027
|
+
);
|
|
1028
|
+
}
|
|
1029
|
+
const leftKeys = Object.keys(left).sort();
|
|
1030
|
+
const rightKeys = Object.keys(right).sort();
|
|
1031
|
+
return (
|
|
1032
|
+
leftKeys.length === rightKeys.length &&
|
|
1033
|
+
leftKeys.every((key, index) => key === rightKeys[index] && deepEqualJson(left[key], right[key]))
|
|
1034
|
+
);
|
|
1035
|
+
}
|
|
1036
|
+
|
|
1037
|
+
function migrateProjectWorkspace(workspace, projectSlug, state, options = {}) {
|
|
1038
|
+
for (const snapshot of state.cleanupSnapshots || []) assertMigrationSnapshotUnchanged(snapshot);
|
|
1039
|
+
const persistentSnapshots = [
|
|
1040
|
+
...(state.packageCleanup?.changed ? [state.packageCleanup.snapshot] : []),
|
|
1041
|
+
...(state.cleanupSnapshots || []).filter(
|
|
1042
|
+
(snapshot) => path.basename(snapshot.path).toLowerCase() !== 'agent-session.json'
|
|
1043
|
+
),
|
|
1044
|
+
];
|
|
1045
|
+
const backupRoot = persistentSnapshots.length
|
|
1046
|
+
? createExternalBackupRoot(workspace, 'legacy-migration', options.dataDir)
|
|
1047
|
+
: null;
|
|
1048
|
+
if (backupRoot) {
|
|
1049
|
+
const backupDevice = fs.statSync(backupRoot).dev;
|
|
1050
|
+
for (const snapshot of persistentSnapshots) {
|
|
1051
|
+
if (fs.lstatSync(snapshot.path).dev !== backupDevice) {
|
|
1052
|
+
throw startError(
|
|
1053
|
+
'legacy_workspace_migration_blocked',
|
|
1054
|
+
'legacy migration backup must be on the same filesystem as the project'
|
|
1055
|
+
);
|
|
1056
|
+
}
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
if (state.packageCleanup?.changed) {
|
|
1060
|
+
replaceMigrationSnapshotAtomically(
|
|
1061
|
+
workspace,
|
|
1062
|
+
state.packageCleanup.snapshot,
|
|
1063
|
+
`${JSON.stringify(state.packageCleanup.value, null, 2)}\n`,
|
|
1064
|
+
backupRoot,
|
|
1065
|
+
options.afterLegacyPathQuarantined
|
|
1066
|
+
);
|
|
1067
|
+
}
|
|
1068
|
+
for (const snapshot of state.cleanupSnapshots || []) {
|
|
1069
|
+
if (path.basename(snapshot.path).toLowerCase() === 'agent-session.json') {
|
|
1070
|
+
removeMigrationSnapshotAtomically(snapshot, options.afterLegacyPathQuarantined);
|
|
1071
|
+
} else {
|
|
1072
|
+
backupMigrationSnapshotAtomically(
|
|
1073
|
+
workspace,
|
|
1074
|
+
snapshot,
|
|
1075
|
+
backupRoot,
|
|
1076
|
+
options.afterLegacyPathQuarantined,
|
|
1077
|
+
'remove'
|
|
1078
|
+
);
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
if (state.legacySessionPath) {
|
|
1082
|
+
removeGitignoreEntries(workspace, ['.joripspace/agent-session.json']);
|
|
1083
|
+
}
|
|
1084
|
+
ensureProjectGuidance(workspace, projectSlug);
|
|
1085
|
+
return { backupRoot };
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
function inspectLegacyHelpers(workspace, projectConfig) {
|
|
1089
|
+
const core = loadCoreOnboardingPackage();
|
|
1090
|
+
const snapshots = [];
|
|
1091
|
+
const conflicts = [];
|
|
1092
|
+
for (const [relative, generatorName] of LEGACY_HELPER_FILES) {
|
|
1093
|
+
const filePath = managedProjectFilePath(workspace, relative);
|
|
1094
|
+
if (!fs.existsSync(filePath)) continue;
|
|
1095
|
+
const generator = core[generatorName];
|
|
1096
|
+
const expected =
|
|
1097
|
+
typeof generator === 'function'
|
|
1098
|
+
? generatorName === 'projectGithubActionsTemplateFile'
|
|
1099
|
+
? generator(projectConfig)
|
|
1100
|
+
: generator()
|
|
1101
|
+
: null;
|
|
1102
|
+
const snapshot = readMigrationSnapshot(filePath);
|
|
1103
|
+
const current = snapshot.source.toString('utf8');
|
|
1104
|
+
if (
|
|
1105
|
+
(typeof expected !== 'string' || current !== expected) &&
|
|
1106
|
+
!looksLikeGeneratedLegacyHelper(relative, current, expected)
|
|
1107
|
+
) {
|
|
1108
|
+
conflicts.push(`${relative} differs from the generated JoripSpace helper`);
|
|
1109
|
+
continue;
|
|
1110
|
+
}
|
|
1111
|
+
snapshots.push(snapshot);
|
|
1112
|
+
}
|
|
1113
|
+
return { conflicts, snapshots };
|
|
1114
|
+
}
|
|
1115
|
+
|
|
1116
|
+
function looksLikeGeneratedLegacyHelper(relative, source, expected) {
|
|
1117
|
+
const value = String(source || '');
|
|
1118
|
+
const legacyHash = LEGACY_HELPER_SHA256[relative];
|
|
1119
|
+
if (legacyHash && crypto.createHash('sha256').update(value).digest('hex') === legacyHash) return true;
|
|
1120
|
+
if (relative !== '.joripspace/github-actions-template.yml' || typeof expected !== 'string') return false;
|
|
1121
|
+
return value === expected.replaceAll('.joripspace/deploy.json', '.joripspace/project.json');
|
|
1122
|
+
}
|
|
1123
|
+
|
|
1124
|
+
function inspectLegacyPackageScripts(workspace) {
|
|
1125
|
+
const packagePath = managedProjectFilePath(workspace, 'package.json');
|
|
1126
|
+
if (!fs.existsSync(packagePath)) {
|
|
1127
|
+
return { changed: false, conflicts: [], path: packagePath, snapshot: null, value: null };
|
|
1128
|
+
}
|
|
1129
|
+
const snapshot = readMigrationSnapshot(packagePath);
|
|
1130
|
+
const value = parseJsonForMigration(snapshot.source.toString('utf8'), packagePath, 'package.json');
|
|
1131
|
+
const expectedScripts = loadCoreOnboardingPackage().projectPackageHelperScripts();
|
|
1132
|
+
const scripts =
|
|
1133
|
+
value.scripts && typeof value.scripts === 'object' && !Array.isArray(value.scripts)
|
|
1134
|
+
? { ...value.scripts }
|
|
1135
|
+
: {};
|
|
1136
|
+
const conflicts = [];
|
|
1137
|
+
let changed = false;
|
|
1138
|
+
for (const [name, expected] of Object.entries(expectedScripts)) {
|
|
1139
|
+
if (scripts[name] === undefined) continue;
|
|
1140
|
+
if (scripts[name] !== expected) {
|
|
1141
|
+
if (String(scripts[name]).includes('.joripspace/')) {
|
|
1142
|
+
conflicts.push(`package.json script ${name} differs from the generated JoripSpace command`);
|
|
1143
|
+
}
|
|
1144
|
+
continue;
|
|
1145
|
+
}
|
|
1146
|
+
delete scripts[name];
|
|
1147
|
+
changed = true;
|
|
1148
|
+
}
|
|
1149
|
+
return {
|
|
1150
|
+
changed,
|
|
1151
|
+
conflicts,
|
|
1152
|
+
path: packagePath,
|
|
1153
|
+
snapshot,
|
|
1154
|
+
value: changed ? { ...value, scripts } : value,
|
|
1155
|
+
};
|
|
1156
|
+
}
|
|
1157
|
+
|
|
1158
|
+
function parseJsonForMigration(source, filePath, label) {
|
|
1159
|
+
try {
|
|
1160
|
+
const value = JSON.parse(source);
|
|
1161
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('not an object');
|
|
1162
|
+
return value;
|
|
1163
|
+
} catch {
|
|
1164
|
+
throw startError('legacy_workspace_migration_blocked', `${label} is not valid JSON: ${filePath}`);
|
|
1165
|
+
}
|
|
1166
|
+
}
|
|
1167
|
+
|
|
1168
|
+
function readMigrationSnapshot(filePath) {
|
|
1169
|
+
const before = fs.lstatSync(filePath);
|
|
1170
|
+
if (!before.isFile() || before.isSymbolicLink()) {
|
|
1171
|
+
throw startError(
|
|
1172
|
+
'legacy_workspace_changed_during_migration',
|
|
1173
|
+
`legacy migration target is not a regular file: ${filePath}`
|
|
1174
|
+
);
|
|
1175
|
+
}
|
|
1176
|
+
const source = fs.readFileSync(filePath);
|
|
1177
|
+
const after = fs.lstatSync(filePath);
|
|
1178
|
+
if (
|
|
1179
|
+
!after.isFile() ||
|
|
1180
|
+
after.isSymbolicLink() ||
|
|
1181
|
+
before.dev !== after.dev ||
|
|
1182
|
+
before.ino !== after.ino ||
|
|
1183
|
+
before.size !== after.size ||
|
|
1184
|
+
before.mtimeMs !== after.mtimeMs ||
|
|
1185
|
+
before.ctimeMs !== after.ctimeMs
|
|
1186
|
+
) {
|
|
1187
|
+
throw startError(
|
|
1188
|
+
'legacy_workspace_changed_during_migration',
|
|
1189
|
+
`legacy migration target changed while it was being validated: ${filePath}`
|
|
1190
|
+
);
|
|
1191
|
+
}
|
|
1192
|
+
return { path: filePath, source, mode: before.mode };
|
|
1193
|
+
}
|
|
1194
|
+
|
|
1195
|
+
function assertMigrationSnapshotUnchanged(snapshot) {
|
|
1196
|
+
if (!snapshot) return;
|
|
1197
|
+
let current;
|
|
1198
|
+
try {
|
|
1199
|
+
current = readMigrationSnapshot(snapshot.path);
|
|
1200
|
+
} catch {
|
|
1201
|
+
throw startError(
|
|
1202
|
+
'legacy_workspace_changed_during_migration',
|
|
1203
|
+
`legacy migration target changed after validation: ${snapshot.path}`
|
|
1204
|
+
);
|
|
1205
|
+
}
|
|
1206
|
+
if (!current.source.equals(snapshot.source)) {
|
|
1207
|
+
throw startError(
|
|
1208
|
+
'legacy_workspace_changed_during_migration',
|
|
1209
|
+
`legacy migration target changed after validation: ${snapshot.path}`
|
|
1210
|
+
);
|
|
1211
|
+
}
|
|
1212
|
+
}
|
|
1213
|
+
|
|
1214
|
+
function quarantineMigrationSnapshot(snapshot, callback, operation) {
|
|
1215
|
+
assertMigrationSnapshotUnchanged(snapshot);
|
|
1216
|
+
const quarantinePath = `${snapshot.path}.joripspace-migrate-${process.pid}-${crypto.randomUUID()}`;
|
|
1217
|
+
fs.renameSync(snapshot.path, quarantinePath);
|
|
1218
|
+
try {
|
|
1219
|
+
callback?.({ path: snapshot.path, quarantinePath, operation });
|
|
1220
|
+
const quarantined = readMigrationSnapshot(quarantinePath);
|
|
1221
|
+
if (!quarantined.source.equals(snapshot.source)) {
|
|
1222
|
+
throw startError(
|
|
1223
|
+
'legacy_workspace_changed_during_migration',
|
|
1224
|
+
`legacy migration target changed after it was quarantined: ${snapshot.path}`
|
|
1225
|
+
);
|
|
1226
|
+
}
|
|
1227
|
+
if (fs.existsSync(snapshot.path)) {
|
|
1228
|
+
fs.rmSync(quarantinePath, { force: true });
|
|
1229
|
+
throw startError(
|
|
1230
|
+
'legacy_workspace_changed_during_migration',
|
|
1231
|
+
`legacy migration target was recreated during migration: ${snapshot.path}`
|
|
1232
|
+
);
|
|
1233
|
+
}
|
|
1234
|
+
return quarantinePath;
|
|
1235
|
+
} catch (error) {
|
|
1236
|
+
restoreMigrationSnapshotWithoutOverwrite(quarantinePath, snapshot.path, true);
|
|
1237
|
+
throw error;
|
|
1238
|
+
}
|
|
1239
|
+
}
|
|
1240
|
+
|
|
1241
|
+
function backupMigrationSnapshotAtomically(workspace, snapshot, backupRoot, callback, operation) {
|
|
1242
|
+
if (!backupRoot) {
|
|
1243
|
+
throw startError('legacy_workspace_migration_blocked', 'legacy migration backup is unavailable');
|
|
1244
|
+
}
|
|
1245
|
+
assertMigrationSnapshotUnchanged(snapshot);
|
|
1186
1246
|
// Managed file snapshots already use real paths. Resolve the workspace too so
|
|
1187
1247
|
// macOS /var aliases and Windows short paths refer to the same project root.
|
|
1188
1248
|
const relative = path.relative(fs.realpathSync.native(workspace), snapshot.path);
|
|
1189
|
-
if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) {
|
|
1190
|
-
throw startError('legacy_workspace_migration_blocked', 'legacy migration target is outside the project');
|
|
1191
|
-
}
|
|
1192
|
-
const backupPath = path.join(backupRoot, 'live', relative);
|
|
1193
|
-
const frozenPath = path.join(backupRoot, 'frozen', relative);
|
|
1194
|
-
fs.mkdirSync(path.dirname(backupPath), { recursive: true, mode: 0o700 });
|
|
1195
|
-
fs.mkdirSync(path.dirname(frozenPath), { recursive: true, mode: 0o700 });
|
|
1196
|
-
writeBufferExclusively(frozenPath, snapshot.source, snapshot.mode);
|
|
1197
|
-
fs.renameSync(snapshot.path, backupPath);
|
|
1198
|
-
try {
|
|
1199
|
-
callback?.({ path: snapshot.path, quarantinePath: backupPath, operation });
|
|
1200
|
-
const backedUp = readMigrationSnapshot(backupPath);
|
|
1201
|
-
if (!backedUp.source.equals(snapshot.source)) {
|
|
1202
|
-
throw startError(
|
|
1203
|
-
'legacy_workspace_changed_during_migration',
|
|
1204
|
-
`legacy migration target changed after it was backed up: ${snapshot.path}`
|
|
1205
|
-
);
|
|
1206
|
-
}
|
|
1207
|
-
if (fs.existsSync(snapshot.path)) {
|
|
1208
|
-
throw startError(
|
|
1209
|
-
'legacy_workspace_changed_during_migration',
|
|
1210
|
-
`legacy migration target was recreated during migration: ${snapshot.path}`
|
|
1211
|
-
);
|
|
1212
|
-
}
|
|
1213
|
-
return backupPath;
|
|
1214
|
-
} catch (error) {
|
|
1215
|
-
restoreMigrationSnapshotWithoutOverwrite(backupPath, snapshot.path);
|
|
1216
|
-
throw error;
|
|
1217
|
-
}
|
|
1218
|
-
}
|
|
1219
|
-
|
|
1220
|
-
function writeBufferExclusively(filePath, source, mode) {
|
|
1221
|
-
const descriptor = fs.openSync(filePath, 'wx', mode & 0o777);
|
|
1222
|
-
try {
|
|
1223
|
-
fs.writeFileSync(descriptor, source);
|
|
1224
|
-
fs.fsyncSync(descriptor);
|
|
1225
|
-
} finally {
|
|
1226
|
-
fs.closeSync(descriptor);
|
|
1227
|
-
}
|
|
1228
|
-
}
|
|
1229
|
-
|
|
1230
|
-
function restoreMigrationSnapshotWithoutOverwrite(backupPath, originalPath, removeBackup = false) {
|
|
1231
|
-
if (!fs.existsSync(backupPath)) return false;
|
|
1232
|
-
try {
|
|
1233
|
-
fs.linkSync(backupPath, originalPath);
|
|
1234
|
-
if (removeBackup) fs.rmSync(backupPath, { force: true });
|
|
1235
|
-
return true;
|
|
1236
|
-
} catch {
|
|
1237
|
-
return false;
|
|
1238
|
-
}
|
|
1239
|
-
}
|
|
1240
|
-
|
|
1241
|
-
function removeMigrationSnapshotAtomically(snapshot, callback) {
|
|
1242
|
-
const quarantinePath = quarantineMigrationSnapshot(snapshot, callback, 'remove');
|
|
1243
|
-
fs.rmSync(quarantinePath, { force: true });
|
|
1244
|
-
}
|
|
1245
|
-
|
|
1246
|
-
function replaceMigrationSnapshotAtomically(workspace, snapshot, source, backupRoot, callback) {
|
|
1247
|
-
const quarantinePath = backupMigrationSnapshotAtomically(
|
|
1248
|
-
workspace,
|
|
1249
|
-
snapshot,
|
|
1250
|
-
backupRoot,
|
|
1251
|
-
callback,
|
|
1252
|
-
'replace'
|
|
1253
|
-
);
|
|
1254
|
-
const temporaryPath = `${snapshot.path}.tmp-${process.pid}-${crypto.randomUUID()}`;
|
|
1255
|
-
let linked = false;
|
|
1256
|
-
try {
|
|
1257
|
-
const descriptor = fs.openSync(temporaryPath, 'wx', snapshot.mode & 0o777);
|
|
1258
|
-
try {
|
|
1259
|
-
fs.writeFileSync(descriptor, source, 'utf8');
|
|
1260
|
-
fs.fsyncSync(descriptor);
|
|
1261
|
-
} finally {
|
|
1262
|
-
fs.closeSync(descriptor);
|
|
1263
|
-
}
|
|
1264
|
-
fs.linkSync(temporaryPath, snapshot.path);
|
|
1265
|
-
linked = true;
|
|
1266
|
-
fs.rmSync(temporaryPath, { force: true });
|
|
1267
|
-
} catch (error) {
|
|
1268
|
-
fs.rmSync(temporaryPath, { force: true });
|
|
1269
|
-
if (!linked) restoreMigrationSnapshotWithoutOverwrite(quarantinePath, snapshot.path);
|
|
1270
|
-
throw startError(
|
|
1271
|
-
'legacy_workspace_changed_during_migration',
|
|
1272
|
-
`legacy migration target could not be replaced without overwriting a concurrent edit: ${snapshot.path}`
|
|
1273
|
-
);
|
|
1274
|
-
}
|
|
1275
|
-
}
|
|
1276
|
-
|
|
1277
|
-
function containsCredentialValue(value, key = '') {
|
|
1278
|
-
if (Array.isArray(value)) return value.some((entry) => containsCredentialValue(entry, key));
|
|
1279
|
-
if (!value || typeof value !== 'object') {
|
|
1280
|
-
return (
|
|
1281
|
-
/^(?:api_token|connect_token|access_token|refresh_token|password|secret)$/i.test(key) &&
|
|
1282
|
-
value !== undefined &&
|
|
1283
|
-
value !== null &&
|
|
1284
|
-
value !== '' &&
|
|
1285
|
-
value !== false
|
|
1286
|
-
);
|
|
1287
|
-
}
|
|
1288
|
-
return Object.entries(value).some(([nestedKey, nested]) => containsCredentialValue(nested, nestedKey));
|
|
1289
|
-
}
|
|
1290
|
-
|
|
1291
|
-
function portablePathConflicts(workspace, relative) {
|
|
1292
|
-
const canonical = relative.replace(/\\/g, '/');
|
|
1293
|
-
const matches = findPortablePathMatches(workspace, canonical);
|
|
1294
|
-
if (matches.length === 0) return [];
|
|
1295
|
-
if (matches.length > 1) return matches.map((match) => `${canonical} conflicts with ${match.relative}`);
|
|
1296
|
-
return matches[0].relative === canonical
|
|
1297
|
-
? []
|
|
1298
|
-
: [`${canonical} uses non-canonical casing ${matches[0].relative}`];
|
|
1299
|
-
}
|
|
1300
|
-
|
|
1301
|
-
function findPortablePathMatches(workspace, relative) {
|
|
1302
|
-
let candidates = [{ fullPath: path.resolve(workspace), parts: [] }];
|
|
1303
|
-
for (const expectedPart of relative.split('/')) {
|
|
1304
|
-
const next = [];
|
|
1305
|
-
for (const candidate of candidates) {
|
|
1306
|
-
let entries = [];
|
|
1307
|
-
try {
|
|
1308
|
-
entries = fs.readdirSync(candidate.fullPath, { withFileTypes: true });
|
|
1309
|
-
} catch (error) {
|
|
1310
|
-
if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') continue;
|
|
1311
|
-
throw error;
|
|
1312
|
-
}
|
|
1313
|
-
for (const entry of entries) {
|
|
1314
|
-
if (entry.name.toLowerCase() !== expectedPart.toLowerCase()) continue;
|
|
1315
|
-
const fullPath = path.join(candidate.fullPath, entry.name);
|
|
1316
|
-
if (fs.lstatSync(fullPath).isSymbolicLink()) {
|
|
1317
|
-
throw new Error(
|
|
1318
|
-
`project path contains a symbolic link or junction: ${[...candidate.parts, entry.name].join('/')}`
|
|
1319
|
-
);
|
|
1320
|
-
}
|
|
1321
|
-
next.push({ fullPath, parts: [...candidate.parts, entry.name] });
|
|
1322
|
-
}
|
|
1323
|
-
}
|
|
1324
|
-
candidates = next;
|
|
1325
|
-
}
|
|
1326
|
-
return candidates.map((candidate) => ({
|
|
1327
|
-
fullPath: candidate.fullPath,
|
|
1328
|
-
relative: candidate.parts.join('/'),
|
|
1329
|
-
}));
|
|
1330
|
-
}
|
|
1331
|
-
|
|
1332
|
-
function workspaceContainsOnlyManagedFiles(workspace) {
|
|
1333
|
-
const allowedTopLevel = new Set(['.env.joripspace', '.gitignore', 'agents.md', 'claude.md']);
|
|
1334
|
-
const allowedJoripspace = new Set([
|
|
1335
|
-
'project',
|
|
1336
|
-
'project.json',
|
|
1337
|
-
'agent-session.json',
|
|
1338
|
-
...LEGACY_HELPER_FILES.map(([relative]) => relative.split('/').at(-1).toLowerCase()),
|
|
1339
|
-
]);
|
|
1340
|
-
for (const entry of fs.readdirSync(workspace, { withFileTypes: true })) {
|
|
1341
|
-
const normalized = entry.name.toLowerCase();
|
|
1342
|
-
if (allowedTopLevel.has(normalized)) continue;
|
|
1343
|
-
if (normalized !== '.joripspace' || !entry.isDirectory()) return false;
|
|
1344
|
-
for (const nested of fs.readdirSync(path.join(workspace, entry.name), { withFileTypes: true })) {
|
|
1345
|
-
if (!nested.isFile() || !allowedJoripspace.has(nested.name.toLowerCase())) return false;
|
|
1346
|
-
}
|
|
1347
|
-
}
|
|
1348
|
-
return true;
|
|
1349
|
-
}
|
|
1350
|
-
|
|
1351
|
-
function workspaceHasApplicationFiles(workspace) {
|
|
1352
|
-
const ignored = new Set(['.git', '.gitignore', '.env.joripspace', '.joripspace', 'agents.md', 'claude.md']);
|
|
1353
|
-
return fs.readdirSync(workspace).some((entry) => !ignored.has(entry.toLowerCase()));
|
|
1354
|
-
}
|
|
1355
|
-
|
|
1356
|
-
function isManagedGitStatusLine(line) {
|
|
1357
|
-
const source = String(line || '');
|
|
1358
|
-
if (source.length < 4 || source[2] !== ' ') return false;
|
|
1359
|
-
const paths = source
|
|
1360
|
-
.slice(3)
|
|
1361
|
-
.split(' -> ')
|
|
1362
|
-
.map((value) => value.replace(/^"|"$/g, '').replace(/\\/g, '/').toLowerCase());
|
|
1363
|
-
const managed = new Set([
|
|
1364
|
-
...START_MANAGED_PATHS,
|
|
1365
|
-
'.joripspace/project.json',
|
|
1366
|
-
'.joripspace/agent-session.json',
|
|
1367
|
-
...LEGACY_HELPER_FILES.map(([relative]) => relative.toLowerCase()),
|
|
1368
|
-
]);
|
|
1369
|
-
return paths.every((relative) => managed.has(relative));
|
|
1370
|
-
}
|
|
1371
|
-
|
|
1372
|
-
function normalizedDescription(value) {
|
|
1373
|
-
const description = typeof value === 'string' ? value.trim() : '';
|
|
1374
|
-
return description || null;
|
|
1375
|
-
}
|
|
1376
|
-
|
|
1249
|
+
if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) {
|
|
1250
|
+
throw startError('legacy_workspace_migration_blocked', 'legacy migration target is outside the project');
|
|
1251
|
+
}
|
|
1252
|
+
const backupPath = path.join(backupRoot, 'live', relative);
|
|
1253
|
+
const frozenPath = path.join(backupRoot, 'frozen', relative);
|
|
1254
|
+
fs.mkdirSync(path.dirname(backupPath), { recursive: true, mode: 0o700 });
|
|
1255
|
+
fs.mkdirSync(path.dirname(frozenPath), { recursive: true, mode: 0o700 });
|
|
1256
|
+
writeBufferExclusively(frozenPath, snapshot.source, snapshot.mode);
|
|
1257
|
+
fs.renameSync(snapshot.path, backupPath);
|
|
1258
|
+
try {
|
|
1259
|
+
callback?.({ path: snapshot.path, quarantinePath: backupPath, operation });
|
|
1260
|
+
const backedUp = readMigrationSnapshot(backupPath);
|
|
1261
|
+
if (!backedUp.source.equals(snapshot.source)) {
|
|
1262
|
+
throw startError(
|
|
1263
|
+
'legacy_workspace_changed_during_migration',
|
|
1264
|
+
`legacy migration target changed after it was backed up: ${snapshot.path}`
|
|
1265
|
+
);
|
|
1266
|
+
}
|
|
1267
|
+
if (fs.existsSync(snapshot.path)) {
|
|
1268
|
+
throw startError(
|
|
1269
|
+
'legacy_workspace_changed_during_migration',
|
|
1270
|
+
`legacy migration target was recreated during migration: ${snapshot.path}`
|
|
1271
|
+
);
|
|
1272
|
+
}
|
|
1273
|
+
return backupPath;
|
|
1274
|
+
} catch (error) {
|
|
1275
|
+
restoreMigrationSnapshotWithoutOverwrite(backupPath, snapshot.path);
|
|
1276
|
+
throw error;
|
|
1277
|
+
}
|
|
1278
|
+
}
|
|
1279
|
+
|
|
1280
|
+
function writeBufferExclusively(filePath, source, mode) {
|
|
1281
|
+
const descriptor = fs.openSync(filePath, 'wx', mode & 0o777);
|
|
1282
|
+
try {
|
|
1283
|
+
fs.writeFileSync(descriptor, source);
|
|
1284
|
+
fs.fsyncSync(descriptor);
|
|
1285
|
+
} finally {
|
|
1286
|
+
fs.closeSync(descriptor);
|
|
1287
|
+
}
|
|
1288
|
+
}
|
|
1289
|
+
|
|
1290
|
+
function restoreMigrationSnapshotWithoutOverwrite(backupPath, originalPath, removeBackup = false) {
|
|
1291
|
+
if (!fs.existsSync(backupPath)) return false;
|
|
1292
|
+
try {
|
|
1293
|
+
fs.linkSync(backupPath, originalPath);
|
|
1294
|
+
if (removeBackup) fs.rmSync(backupPath, { force: true });
|
|
1295
|
+
return true;
|
|
1296
|
+
} catch {
|
|
1297
|
+
return false;
|
|
1298
|
+
}
|
|
1299
|
+
}
|
|
1300
|
+
|
|
1301
|
+
function removeMigrationSnapshotAtomically(snapshot, callback) {
|
|
1302
|
+
const quarantinePath = quarantineMigrationSnapshot(snapshot, callback, 'remove');
|
|
1303
|
+
fs.rmSync(quarantinePath, { force: true });
|
|
1304
|
+
}
|
|
1305
|
+
|
|
1306
|
+
function replaceMigrationSnapshotAtomically(workspace, snapshot, source, backupRoot, callback) {
|
|
1307
|
+
const quarantinePath = backupMigrationSnapshotAtomically(
|
|
1308
|
+
workspace,
|
|
1309
|
+
snapshot,
|
|
1310
|
+
backupRoot,
|
|
1311
|
+
callback,
|
|
1312
|
+
'replace'
|
|
1313
|
+
);
|
|
1314
|
+
const temporaryPath = `${snapshot.path}.tmp-${process.pid}-${crypto.randomUUID()}`;
|
|
1315
|
+
let linked = false;
|
|
1316
|
+
try {
|
|
1317
|
+
const descriptor = fs.openSync(temporaryPath, 'wx', snapshot.mode & 0o777);
|
|
1318
|
+
try {
|
|
1319
|
+
fs.writeFileSync(descriptor, source, 'utf8');
|
|
1320
|
+
fs.fsyncSync(descriptor);
|
|
1321
|
+
} finally {
|
|
1322
|
+
fs.closeSync(descriptor);
|
|
1323
|
+
}
|
|
1324
|
+
fs.linkSync(temporaryPath, snapshot.path);
|
|
1325
|
+
linked = true;
|
|
1326
|
+
fs.rmSync(temporaryPath, { force: true });
|
|
1327
|
+
} catch (error) {
|
|
1328
|
+
fs.rmSync(temporaryPath, { force: true });
|
|
1329
|
+
if (!linked) restoreMigrationSnapshotWithoutOverwrite(quarantinePath, snapshot.path);
|
|
1330
|
+
throw startError(
|
|
1331
|
+
'legacy_workspace_changed_during_migration',
|
|
1332
|
+
`legacy migration target could not be replaced without overwriting a concurrent edit: ${snapshot.path}`
|
|
1333
|
+
);
|
|
1334
|
+
}
|
|
1335
|
+
}
|
|
1336
|
+
|
|
1337
|
+
function containsCredentialValue(value, key = '') {
|
|
1338
|
+
if (Array.isArray(value)) return value.some((entry) => containsCredentialValue(entry, key));
|
|
1339
|
+
if (!value || typeof value !== 'object') {
|
|
1340
|
+
return (
|
|
1341
|
+
/^(?:api_token|connect_token|access_token|refresh_token|password|secret)$/i.test(key) &&
|
|
1342
|
+
value !== undefined &&
|
|
1343
|
+
value !== null &&
|
|
1344
|
+
value !== '' &&
|
|
1345
|
+
value !== false
|
|
1346
|
+
);
|
|
1347
|
+
}
|
|
1348
|
+
return Object.entries(value).some(([nestedKey, nested]) => containsCredentialValue(nested, nestedKey));
|
|
1349
|
+
}
|
|
1350
|
+
|
|
1351
|
+
function portablePathConflicts(workspace, relative) {
|
|
1352
|
+
const canonical = relative.replace(/\\/g, '/');
|
|
1353
|
+
const matches = findPortablePathMatches(workspace, canonical);
|
|
1354
|
+
if (matches.length === 0) return [];
|
|
1355
|
+
if (matches.length > 1) return matches.map((match) => `${canonical} conflicts with ${match.relative}`);
|
|
1356
|
+
return matches[0].relative === canonical
|
|
1357
|
+
? []
|
|
1358
|
+
: [`${canonical} uses non-canonical casing ${matches[0].relative}`];
|
|
1359
|
+
}
|
|
1360
|
+
|
|
1361
|
+
function findPortablePathMatches(workspace, relative) {
|
|
1362
|
+
let candidates = [{ fullPath: path.resolve(workspace), parts: [] }];
|
|
1363
|
+
for (const expectedPart of relative.split('/')) {
|
|
1364
|
+
const next = [];
|
|
1365
|
+
for (const candidate of candidates) {
|
|
1366
|
+
let entries = [];
|
|
1367
|
+
try {
|
|
1368
|
+
entries = fs.readdirSync(candidate.fullPath, { withFileTypes: true });
|
|
1369
|
+
} catch (error) {
|
|
1370
|
+
if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') continue;
|
|
1371
|
+
throw error;
|
|
1372
|
+
}
|
|
1373
|
+
for (const entry of entries) {
|
|
1374
|
+
if (entry.name.toLowerCase() !== expectedPart.toLowerCase()) continue;
|
|
1375
|
+
const fullPath = path.join(candidate.fullPath, entry.name);
|
|
1376
|
+
if (fs.lstatSync(fullPath).isSymbolicLink()) {
|
|
1377
|
+
throw new Error(
|
|
1378
|
+
`project path contains a symbolic link or junction: ${[...candidate.parts, entry.name].join('/')}`
|
|
1379
|
+
);
|
|
1380
|
+
}
|
|
1381
|
+
next.push({ fullPath, parts: [...candidate.parts, entry.name] });
|
|
1382
|
+
}
|
|
1383
|
+
}
|
|
1384
|
+
candidates = next;
|
|
1385
|
+
}
|
|
1386
|
+
return candidates.map((candidate) => ({
|
|
1387
|
+
fullPath: candidate.fullPath,
|
|
1388
|
+
relative: candidate.parts.join('/'),
|
|
1389
|
+
}));
|
|
1390
|
+
}
|
|
1391
|
+
|
|
1392
|
+
function workspaceContainsOnlyManagedFiles(workspace) {
|
|
1393
|
+
const allowedTopLevel = new Set(['.env.joripspace', '.gitignore', 'agents.md', 'claude.md']);
|
|
1394
|
+
const allowedJoripspace = new Set([
|
|
1395
|
+
'project',
|
|
1396
|
+
'project.json',
|
|
1397
|
+
'agent-session.json',
|
|
1398
|
+
...LEGACY_HELPER_FILES.map(([relative]) => relative.split('/').at(-1).toLowerCase()),
|
|
1399
|
+
]);
|
|
1400
|
+
for (const entry of fs.readdirSync(workspace, { withFileTypes: true })) {
|
|
1401
|
+
const normalized = entry.name.toLowerCase();
|
|
1402
|
+
if (allowedTopLevel.has(normalized)) continue;
|
|
1403
|
+
if (normalized !== '.joripspace' || !entry.isDirectory()) return false;
|
|
1404
|
+
for (const nested of fs.readdirSync(path.join(workspace, entry.name), { withFileTypes: true })) {
|
|
1405
|
+
if (!nested.isFile() || !allowedJoripspace.has(nested.name.toLowerCase())) return false;
|
|
1406
|
+
}
|
|
1407
|
+
}
|
|
1408
|
+
return true;
|
|
1409
|
+
}
|
|
1410
|
+
|
|
1411
|
+
function workspaceHasApplicationFiles(workspace) {
|
|
1412
|
+
const ignored = new Set(['.git', '.gitignore', '.env.joripspace', '.joripspace', 'agents.md', 'claude.md']);
|
|
1413
|
+
return fs.readdirSync(workspace).some((entry) => !ignored.has(entry.toLowerCase()));
|
|
1414
|
+
}
|
|
1415
|
+
|
|
1416
|
+
function isManagedGitStatusLine(line) {
|
|
1417
|
+
const source = String(line || '');
|
|
1418
|
+
if (source.length < 4 || source[2] !== ' ') return false;
|
|
1419
|
+
const paths = source
|
|
1420
|
+
.slice(3)
|
|
1421
|
+
.split(' -> ')
|
|
1422
|
+
.map((value) => value.replace(/^"|"$/g, '').replace(/\\/g, '/').toLowerCase());
|
|
1423
|
+
const managed = new Set([
|
|
1424
|
+
...START_MANAGED_PATHS,
|
|
1425
|
+
'.joripspace/project.json',
|
|
1426
|
+
'.joripspace/agent-session.json',
|
|
1427
|
+
...LEGACY_HELPER_FILES.map(([relative]) => relative.toLowerCase()),
|
|
1428
|
+
]);
|
|
1429
|
+
return paths.every((relative) => managed.has(relative));
|
|
1430
|
+
}
|
|
1431
|
+
|
|
1432
|
+
function normalizedDescription(value) {
|
|
1433
|
+
const description = typeof value === 'string' ? value.trim() : '';
|
|
1434
|
+
return description || null;
|
|
1435
|
+
}
|
|
1436
|
+
|
|
1377
1437
|
function loadCoreOnboardingPackage() {
|
|
1378
1438
|
return require('../vendor/core/onboarding.cjs');
|
|
1379
1439
|
}
|
|
1380
|
-
|
|
1381
|
-
function startError(code, message) {
|
|
1382
|
-
const error = new Error(message);
|
|
1383
|
-
error.code = code;
|
|
1384
|
-
return error;
|
|
1385
|
-
}
|
|
1386
|
-
|
|
1387
|
-
function writeTextAtomically(filePath, source) {
|
|
1388
|
-
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
1389
|
-
const temporaryPath = `${filePath}.tmp-${process.pid}-${Date.now()}`;
|
|
1390
|
-
const backupPath = `${filePath}.bak-${process.pid}-${Date.now()}`;
|
|
1391
|
-
fs.writeFileSync(temporaryPath, source, 'utf8');
|
|
1392
|
-
try {
|
|
1393
|
-
fs.renameSync(temporaryPath, filePath);
|
|
1394
|
-
} catch (error) {
|
|
1395
|
-
try {
|
|
1396
|
-
if (fs.existsSync(filePath)) fs.renameSync(filePath, backupPath);
|
|
1397
|
-
fs.renameSync(temporaryPath, filePath);
|
|
1398
|
-
fs.rmSync(backupPath, { force: true });
|
|
1399
|
-
} catch {
|
|
1400
|
-
try {
|
|
1401
|
-
if (fs.existsSync(backupPath) && !fs.existsSync(filePath)) fs.renameSync(backupPath, filePath);
|
|
1402
|
-
} catch {}
|
|
1403
|
-
fs.rmSync(temporaryPath, { force: true });
|
|
1404
|
-
throw error;
|
|
1405
|
-
}
|
|
1406
|
-
}
|
|
1407
|
-
}
|
|
1408
|
-
|
|
1440
|
+
|
|
1441
|
+
function startError(code, message) {
|
|
1442
|
+
const error = new Error(message);
|
|
1443
|
+
error.code = code;
|
|
1444
|
+
return error;
|
|
1445
|
+
}
|
|
1446
|
+
|
|
1447
|
+
function writeTextAtomically(filePath, source) {
|
|
1448
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
1449
|
+
const temporaryPath = `${filePath}.tmp-${process.pid}-${Date.now()}`;
|
|
1450
|
+
const backupPath = `${filePath}.bak-${process.pid}-${Date.now()}`;
|
|
1451
|
+
fs.writeFileSync(temporaryPath, source, 'utf8');
|
|
1452
|
+
try {
|
|
1453
|
+
fs.renameSync(temporaryPath, filePath);
|
|
1454
|
+
} catch (error) {
|
|
1455
|
+
try {
|
|
1456
|
+
if (fs.existsSync(filePath)) fs.renameSync(filePath, backupPath);
|
|
1457
|
+
fs.renameSync(temporaryPath, filePath);
|
|
1458
|
+
fs.rmSync(backupPath, { force: true });
|
|
1459
|
+
} catch {
|
|
1460
|
+
try {
|
|
1461
|
+
if (fs.existsSync(backupPath) && !fs.existsSync(filePath)) fs.renameSync(backupPath, filePath);
|
|
1462
|
+
} catch {}
|
|
1463
|
+
fs.rmSync(temporaryPath, { force: true });
|
|
1464
|
+
throw error;
|
|
1465
|
+
}
|
|
1466
|
+
}
|
|
1467
|
+
}
|
|
1468
|
+
|
|
1409
1469
|
function createStartOnboarding(executable, cwd, project, connected = false, apiBaseUrl = '') {
|
|
1410
1470
|
const invocation = {
|
|
1411
1471
|
command: process.pkg ? executable : process.execPath,
|
|
@@ -1432,16 +1492,16 @@ function createStartOnboarding(executable, cwd, project, connected = false, apiB
|
|
|
1432
1492
|
|
|
1433
1493
|
module.exports = {
|
|
1434
1494
|
createStartOnboarding,
|
|
1435
|
-
START_AGENTS_END,
|
|
1436
|
-
START_AGENTS_START,
|
|
1437
|
-
ensureProjectGuidance,
|
|
1438
|
-
legacyCredentialSessionConnection,
|
|
1439
|
-
readProjectMarker,
|
|
1440
|
-
redactGitDiagnostic,
|
|
1441
|
-
resolveProjectRoot,
|
|
1442
|
-
syncConnectedGithubRepository,
|
|
1443
|
-
startProject,
|
|
1444
|
-
upsertClaudeAgentsReference,
|
|
1445
|
-
upsertStartAgentsBlock,
|
|
1446
|
-
validGitBranch,
|
|
1447
|
-
};
|
|
1495
|
+
START_AGENTS_END,
|
|
1496
|
+
START_AGENTS_START,
|
|
1497
|
+
ensureProjectGuidance,
|
|
1498
|
+
legacyCredentialSessionConnection,
|
|
1499
|
+
readProjectMarker,
|
|
1500
|
+
redactGitDiagnostic,
|
|
1501
|
+
resolveProjectRoot,
|
|
1502
|
+
syncConnectedGithubRepository,
|
|
1503
|
+
startProject,
|
|
1504
|
+
upsertClaudeAgentsReference,
|
|
1505
|
+
upsertStartAgentsBlock,
|
|
1506
|
+
validGitBranch,
|
|
1507
|
+
};
|