@notchlet/cli 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auth.js +380 -0
- package/dist/cli-format.js +46 -0
- package/dist/cli-prompt.js +73 -0
- package/dist/cli.js +1040 -0
- package/dist/guidance-install.js +111 -0
- package/dist/integration.js +806 -0
- package/dist/setup.js +92 -0
- package/guidance/aliases.json +27 -0
- package/guidance/generated/claude-code/notchlet-deliver/SKILL.md +94 -0
- package/guidance/generated/claude-code/notchlet-implement/SKILL.md +94 -0
- package/guidance/generated/claude-code/notchlet-init/SKILL.md +30 -0
- package/guidance/generated/claude-code/notchlet-mcp/SKILL.md +60 -0
- package/guidance/generated/claude-code/notchlet-plan/SKILL.md +100 -0
- package/guidance/generated/claude-code/notchlet-platform/SKILL.md +85 -0
- package/guidance/generated/claude-code/notchlet-review/SKILL.md +68 -0
- package/guidance/generated/claude-code/notchlet-super/SKILL.md +47 -0
- package/guidance/generated/compatibility.json +94 -0
- package/guidance/generated/manifest.json +140 -0
- package/guidance/generated/opencode/notchlet-deliver/SKILL.md +94 -0
- package/guidance/generated/opencode/notchlet-implement/SKILL.md +94 -0
- package/guidance/generated/opencode/notchlet-init/SKILL.md +30 -0
- package/guidance/generated/opencode/notchlet-mcp/SKILL.md +60 -0
- package/guidance/generated/opencode/notchlet-plan/SKILL.md +100 -0
- package/guidance/generated/opencode/notchlet-platform/SKILL.md +85 -0
- package/guidance/generated/opencode/notchlet-review/SKILL.md +68 -0
- package/guidance/generated/opencode/notchlet-super/SKILL.md +47 -0
- package/package.json +1 -6
- package/scripts/generate-guidance.mjs +115 -0
- package/README.md +0 -3
|
@@ -0,0 +1,806 @@
|
|
|
1
|
+
import { readFile, writeFile, mkdir, lstat, rename, rm } from 'node:fs/promises';
|
|
2
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
|
5
|
+
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
|
|
6
|
+
import { inspectGitContext, parseChange, scaffold, readChange } from '@notchlet/core';
|
|
7
|
+
import { getProfile, resolveCredential } from './auth.js';
|
|
8
|
+
const positiveId = (n) => Number.isSafeInteger(n) && n > 0;
|
|
9
|
+
export function normalizeRemote(remote) { return `${remote.host.toLowerCase()}/${remote.owner.toLowerCase()}/${remote.repo.replace(/\.git$/i, '').toLowerCase()}`; }
|
|
10
|
+
const MAX_SYNC_BYTES = 1_048_576;
|
|
11
|
+
const sha256 = (value) => createHash('sha256').update(value).digest('hex');
|
|
12
|
+
const syncDir = (root) => path.join(root, '.notchlet', '.local', 'sync');
|
|
13
|
+
async function syncState(root, id) {
|
|
14
|
+
try {
|
|
15
|
+
return JSON.parse(await readFile(path.join(syncDir(root), `${id}.json`), 'utf8'));
|
|
16
|
+
}
|
|
17
|
+
catch (error) {
|
|
18
|
+
if (error.code === 'ENOENT')
|
|
19
|
+
return null;
|
|
20
|
+
throw error;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
async function saveSyncState(root, id, state) {
|
|
24
|
+
const dir = syncDir(root);
|
|
25
|
+
await mkdir(dir, { recursive: true });
|
|
26
|
+
await writeFile(path.join(dir, `${id}.json`), `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 });
|
|
27
|
+
}
|
|
28
|
+
const operationFile = (root, id, step) => path.join(syncDir(root), `${id}.${step}.operation.json`);
|
|
29
|
+
async function readPendingOperation(root, id, step) {
|
|
30
|
+
try {
|
|
31
|
+
return JSON.parse(await readFile(operationFile(root, id, step), 'utf8'));
|
|
32
|
+
}
|
|
33
|
+
catch (error) {
|
|
34
|
+
if (error.code === 'ENOENT')
|
|
35
|
+
return null;
|
|
36
|
+
throw error;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
async function pendingOperation(root, id, step, payloadHash, details) {
|
|
40
|
+
const file = operationFile(root, id, step);
|
|
41
|
+
try {
|
|
42
|
+
const saved = JSON.parse(await readFile(file, 'utf8'));
|
|
43
|
+
if (saved.payloadHash !== payloadHash)
|
|
44
|
+
throw Object.assign(new Error('A previous sync operation has an unresolved response for different local content. Reconcile it before changing this payload.'), { code: 'operation_payload_conflict' });
|
|
45
|
+
return saved;
|
|
46
|
+
}
|
|
47
|
+
catch (error) {
|
|
48
|
+
if (error.code !== 'ENOENT')
|
|
49
|
+
throw error;
|
|
50
|
+
}
|
|
51
|
+
const saved = { operationId: randomUUID(), payloadHash, ...details };
|
|
52
|
+
await mkdir(syncDir(root), { recursive: true });
|
|
53
|
+
const temporary = `${file}.${randomUUID()}.tmp`;
|
|
54
|
+
await writeFile(temporary, `${JSON.stringify(saved, null, 2)}\n`, { flag: 'wx', mode: 0o600 });
|
|
55
|
+
await rename(temporary, file);
|
|
56
|
+
return saved;
|
|
57
|
+
}
|
|
58
|
+
async function clearPendingOperation(root, id, step) { await rm(operationFile(root, id, step), { force: true }); }
|
|
59
|
+
async function reconcileOperation(ctx, operationId, payloadHash) {
|
|
60
|
+
const response = await remoteJson(ctx, `/operations/${operationId}`);
|
|
61
|
+
if (response.status === 404)
|
|
62
|
+
return null;
|
|
63
|
+
if (!response.ok)
|
|
64
|
+
throw new Error('Could not reconcile the pending remote operation; it remains journaled for retry.');
|
|
65
|
+
const operation = await response.json();
|
|
66
|
+
if (operation.operationId !== operationId || operation.payloadHash !== payloadHash)
|
|
67
|
+
throw Object.assign(new Error('Remote operation identity or payload hash does not match the local journal.'), { code: 'operation_payload_conflict' });
|
|
68
|
+
if (operation.state !== 'succeeded' || !operation.response)
|
|
69
|
+
throw Object.assign(new Error('Remote operation is not yet complete; it remains journaled for retry.'), { code: 'operation_pending' });
|
|
70
|
+
return operation.response;
|
|
71
|
+
}
|
|
72
|
+
function canonical(value) {
|
|
73
|
+
if (Array.isArray(value))
|
|
74
|
+
return `[${value.map(canonical).join(',')}]`;
|
|
75
|
+
if (value && typeof value === 'object')
|
|
76
|
+
return `{${Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, entry]) => `${JSON.stringify(key)}:${canonical(entry)}`).join(',')}}`;
|
|
77
|
+
return JSON.stringify(value);
|
|
78
|
+
}
|
|
79
|
+
async function changePackage(root, id) {
|
|
80
|
+
const change = await readChange(root, id);
|
|
81
|
+
const artifacts = {};
|
|
82
|
+
for (const relative of Object.values(change.artifacts)) {
|
|
83
|
+
try {
|
|
84
|
+
artifacts[relative] = await readFile(path.join(root, '.notchlet', 'changes', id, relative), 'utf8');
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
if (error.code !== 'ENOENT')
|
|
88
|
+
throw error;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
let evidence = '';
|
|
92
|
+
try {
|
|
93
|
+
evidence = await readFile(path.join(root, '.notchlet', 'changes', id, 'evidence.jsonl'), 'utf8');
|
|
94
|
+
}
|
|
95
|
+
catch (error) {
|
|
96
|
+
if (error.code !== 'ENOENT')
|
|
97
|
+
throw error;
|
|
98
|
+
}
|
|
99
|
+
const payload = { change, artifacts, evidence };
|
|
100
|
+
const bytes = Buffer.from(canonical(payload));
|
|
101
|
+
if (bytes.byteLength > MAX_SYNC_BYTES)
|
|
102
|
+
throw Object.assign(new Error('Sync package exceeds the 1 MiB limit.'), { code: 'payload_too_large' });
|
|
103
|
+
return { payload, bytes, hash: sha256(bytes) };
|
|
104
|
+
}
|
|
105
|
+
async function syncContext(root, options) {
|
|
106
|
+
const workspace = JSON.parse(await readFile(path.join(root, '.notchlet', 'workspace.json'), 'utf8'));
|
|
107
|
+
const binding = workspace.binding;
|
|
108
|
+
if (!binding)
|
|
109
|
+
throw new Error('Workspace is not bound to a Development API product and repository.');
|
|
110
|
+
const profile = await getProfile(options.server ?? binding.server);
|
|
111
|
+
if (!profile || profile.origin !== binding.server)
|
|
112
|
+
throw new Error('Selected CLI profile does not match the workspace server binding.');
|
|
113
|
+
const { token } = await resolveCredential({ server: profile.origin, fetch: options.fetch, store: options.store, loadStore: options.loadStore });
|
|
114
|
+
const base = options.endpoint ?? binding.server;
|
|
115
|
+
const baseUrl = new URL(base);
|
|
116
|
+
if (baseUrl.origin !== binding.server || baseUrl.username || baseUrl.password || baseUrl.search || baseUrl.hash)
|
|
117
|
+
throw new Error('Sync endpoint does not match the bound server origin.');
|
|
118
|
+
const fetcher = options.fetch ?? fetch;
|
|
119
|
+
const headers = { Authorization: `Bearer ${token}`, 'X-Notchlet-Client-Version': '0.1.0' };
|
|
120
|
+
const response = await fetcher(`${baseUrl.origin}/development/v1/capabilities`, { headers });
|
|
121
|
+
if (response.status === 401)
|
|
122
|
+
throw Object.assign(new Error('Server rejected the credential; authenticate again. Pending sync operations remain saved locally.'), { code: 'credential_revoked' });
|
|
123
|
+
if (response.status === 403)
|
|
124
|
+
throw Object.assign(new Error('Credential lacks the required workspace:read scope. Pending sync operations remain saved locally.'), { code: 'scope_insufficient' });
|
|
125
|
+
if (!response.ok)
|
|
126
|
+
throw new Error('Development API capabilities are unavailable.');
|
|
127
|
+
const caps = await response.json();
|
|
128
|
+
if (caps.server?.id !== binding.serverIdentity)
|
|
129
|
+
throw new Error('Development API server identity differs from workspace binding.');
|
|
130
|
+
if (caps.protocol?.minimum !== binding.protocol?.minimum || caps.protocol?.maximum !== binding.protocol?.maximum || !caps.protocol?.minimum?.startsWith('1.') || Number(caps.protocol?.maximum?.split('.')[0]) < 1)
|
|
131
|
+
throw new Error('Development API protocol differs from workspace binding or is incompatible.');
|
|
132
|
+
const requiredOperations = ['createChange', 'uploadSnapshot', ...(options.requiredOperations ?? [])];
|
|
133
|
+
if (caps.versions?.schema !== binding.schemaVersion || caps.versions?.core !== binding.coreVersion || caps.limits?.snapshotUploadBytes !== MAX_SYNC_BYTES || !Array.isArray(caps.operations) || !requiredOperations.every(op => caps.operations.includes(op)))
|
|
134
|
+
throw new Error('Development API versions, limits, or required capabilities do not match the binding.');
|
|
135
|
+
return { fetcher, headers, binding, base: `${baseUrl.origin}/development/v1` };
|
|
136
|
+
}
|
|
137
|
+
async function remoteJson(ctx, route, init = {}) {
|
|
138
|
+
return ctx.fetcher(`${ctx.base}${route}`, { ...init, headers: { ...ctx.headers, ...(init.headers ?? {}) } });
|
|
139
|
+
}
|
|
140
|
+
function safeRelative(relative) {
|
|
141
|
+
if (typeof relative !== 'string' || !relative || relative.includes('\\') || path.posix.isAbsolute(relative) || /^[a-zA-Z]:/.test(relative))
|
|
142
|
+
throw new Error('Remote snapshot contains an unsafe artifact path.');
|
|
143
|
+
const parts = relative.split('/');
|
|
144
|
+
if (parts.some(part => !part || part === '.' || part === '..'))
|
|
145
|
+
throw new Error('Remote snapshot contains an unsafe artifact path.');
|
|
146
|
+
return parts.join(path.sep);
|
|
147
|
+
}
|
|
148
|
+
async function lstatOrNull(file) {
|
|
149
|
+
try {
|
|
150
|
+
return await lstat(file);
|
|
151
|
+
}
|
|
152
|
+
catch (error) {
|
|
153
|
+
if (error.code === 'ENOENT')
|
|
154
|
+
return null;
|
|
155
|
+
throw error;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
function validateRemotePackage(id, remotePackage) {
|
|
159
|
+
if (!remotePackage || typeof remotePackage !== 'object' || !remotePackage.change || !remotePackage.artifacts || typeof remotePackage.artifacts !== 'object' || typeof remotePackage.evidence !== 'string')
|
|
160
|
+
throw new Error('Remote snapshot is not a valid sync package.');
|
|
161
|
+
const remoteChange = parseChange(remotePackage.change);
|
|
162
|
+
if (remoteChange.id !== id || !remoteChange.artifacts || Object.keys(remotePackage.artifacts).length !== Object.keys(remoteChange.artifacts).length)
|
|
163
|
+
throw new Error('Remote package change identity or artifact declarations are invalid.');
|
|
164
|
+
const files = new Map();
|
|
165
|
+
for (const [key, declared] of Object.entries(remoteChange.artifacts)) {
|
|
166
|
+
const relative = safeRelative(declared);
|
|
167
|
+
if (key !== declared || typeof remotePackage.artifacts[key] !== 'string')
|
|
168
|
+
throw new Error('Remote package artifact contents do not match the declared artifact list.');
|
|
169
|
+
files.set(relative, remotePackage.artifacts[key]);
|
|
170
|
+
}
|
|
171
|
+
files.set('evidence.jsonl', remotePackage.evidence);
|
|
172
|
+
return { change: remoteChange, files };
|
|
173
|
+
}
|
|
174
|
+
async function reconcileRemotePackage(root, id, localPackage, remotePackage) {
|
|
175
|
+
const { files } = validateRemotePackage(id, remotePackage);
|
|
176
|
+
const changeDir = path.join(root, '.notchlet', 'changes', id);
|
|
177
|
+
const transaction = path.join(changeDir, `.sync-stage-${randomUUID()}`), backup = path.join(transaction, '.backup');
|
|
178
|
+
const installed = [], originals = new Map();
|
|
179
|
+
await mkdir(path.join(transaction, 'new'), { recursive: true });
|
|
180
|
+
try {
|
|
181
|
+
// Validate all target paths and stage the complete package before touching a workspace file.
|
|
182
|
+
for (const [relative, contents] of files) {
|
|
183
|
+
const safe = safeRelative(relative), target = path.join(changeDir, safe);
|
|
184
|
+
if (!target.startsWith(`${changeDir}${path.sep}`))
|
|
185
|
+
throw new Error('Remote snapshot path escapes the local change directory.');
|
|
186
|
+
let parent = changeDir;
|
|
187
|
+
for (const segment of path.dirname(safe).split(path.sep).filter(Boolean)) {
|
|
188
|
+
parent = path.join(parent, segment);
|
|
189
|
+
const stat = await lstatOrNull(parent);
|
|
190
|
+
if (stat?.isSymbolicLink() || (stat && !stat.isDirectory()))
|
|
191
|
+
throw new Error('Local artifact path traverses a non-directory or symlink.');
|
|
192
|
+
}
|
|
193
|
+
const existing = await lstatOrNull(target);
|
|
194
|
+
if (existing?.isSymbolicLink() || (existing && !existing.isFile()))
|
|
195
|
+
throw new Error('Local artifact target is not a regular file.');
|
|
196
|
+
const priorContent = relative === 'evidence.jsonl' ? localPackage.evidence : localPackage.artifacts[relative.replace(/\\/g, '/')];
|
|
197
|
+
if (existing) {
|
|
198
|
+
const current = await readFile(target);
|
|
199
|
+
if (typeof priorContent !== 'string' || !current.equals(Buffer.from(priorContent)))
|
|
200
|
+
throw Object.assign(new Error('Local artifact changed since its recorded sync base.'), { code: 'local_file_conflict' });
|
|
201
|
+
originals.set(safe, current);
|
|
202
|
+
}
|
|
203
|
+
else {
|
|
204
|
+
if (typeof priorContent === 'string' && (relative !== 'evidence.jsonl' || priorContent.length > 0))
|
|
205
|
+
throw Object.assign(new Error('A previously synchronized local artifact is missing.'), { code: 'local_file_conflict' });
|
|
206
|
+
originals.set(safe, null);
|
|
207
|
+
}
|
|
208
|
+
const stageTarget = path.join(transaction, 'new', safe);
|
|
209
|
+
await mkdir(path.dirname(stageTarget), { recursive: true });
|
|
210
|
+
await writeFile(stageTarget, contents, { flag: 'wx' });
|
|
211
|
+
}
|
|
212
|
+
for (const [relative] of files) {
|
|
213
|
+
const safe = safeRelative(relative), target = path.join(changeDir, safe), stageTarget = path.join(transaction, 'new', safe);
|
|
214
|
+
await mkdir(path.dirname(target), { recursive: true });
|
|
215
|
+
const old = originals.get(safe);
|
|
216
|
+
if (old !== null) {
|
|
217
|
+
const backupFile = path.join(backup, safe);
|
|
218
|
+
await mkdir(path.dirname(backupFile), { recursive: true });
|
|
219
|
+
await rename(target, backupFile);
|
|
220
|
+
}
|
|
221
|
+
try {
|
|
222
|
+
await rename(stageTarget, target);
|
|
223
|
+
installed.push(safe);
|
|
224
|
+
}
|
|
225
|
+
catch (error) {
|
|
226
|
+
if (old !== null)
|
|
227
|
+
await rename(path.join(backup, safe), target);
|
|
228
|
+
throw error;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
catch (error) {
|
|
233
|
+
for (const safe of installed.reverse()) {
|
|
234
|
+
const target = path.join(changeDir, safe), old = originals.get(safe);
|
|
235
|
+
await rm(target, { force: true });
|
|
236
|
+
if (old !== null)
|
|
237
|
+
await rename(path.join(backup, safe), target).catch(() => undefined);
|
|
238
|
+
}
|
|
239
|
+
throw error;
|
|
240
|
+
}
|
|
241
|
+
finally {
|
|
242
|
+
await rm(transaction, { recursive: true, force: true });
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
export async function syncStatus(root, id, options = {}) {
|
|
246
|
+
const pkg = await changePackage(root, id), state = await syncState(root, id);
|
|
247
|
+
if (!state)
|
|
248
|
+
return { change: id, state: 'local-only', localHash: pkg.hash, remoteId: null };
|
|
249
|
+
const ctx = await syncContext(root, options);
|
|
250
|
+
const response = await remoteJson(ctx, `/changes/${state.remoteId}/snapshots`);
|
|
251
|
+
if (!response.ok)
|
|
252
|
+
throw new Error('Could not read remote snapshots.');
|
|
253
|
+
const page = await response.json();
|
|
254
|
+
const latest = page.items?.sort((a, b) => b.revision - a.revision)[0];
|
|
255
|
+
return { change: id, remoteId: state.remoteId, baseHash: state.baseHash, localHash: pkg.hash, remoteHash: latest?.sha256 ?? null, remoteCapturedAt: latest?.createdAt ?? null, state: !latest ? 'remote-empty' : latest.sha256 === pkg.hash ? 'unchanged' : pkg.hash === state.baseHash ? 'remote-only' : latest.sha256 === state.baseHash ? 'local-only' : 'divergent' };
|
|
256
|
+
}
|
|
257
|
+
export async function syncPush(root, id, options = {}) {
|
|
258
|
+
const pkg = await changePackage(root, id), local = await syncState(root, id), ctx = await syncContext(root, options);
|
|
259
|
+
const hash = pkg.hash;
|
|
260
|
+
let remoteId = local?.remoteId, revision = 0;
|
|
261
|
+
if (remoteId) {
|
|
262
|
+
const pendingCreate = await readPendingOperation(root, id, 'create');
|
|
263
|
+
if (pendingCreate) {
|
|
264
|
+
const created = await reconcileOperation(ctx, pendingCreate.operationId, pendingCreate.payloadHash);
|
|
265
|
+
if (created && created.id !== remoteId)
|
|
266
|
+
throw new Error('Pending create operation does not match the saved remote change binding.');
|
|
267
|
+
await clearPendingOperation(root, id, 'create');
|
|
268
|
+
}
|
|
269
|
+
const existing = await remoteJson(ctx, `/changes/${remoteId}`);
|
|
270
|
+
if (!existing.ok)
|
|
271
|
+
throw new Error('Could not read remote change before push.');
|
|
272
|
+
const metadata = await existing.json();
|
|
273
|
+
revision = metadata.revision;
|
|
274
|
+
const snapshotsResponse = await remoteJson(ctx, `/changes/${remoteId}/snapshots`);
|
|
275
|
+
if (!snapshotsResponse.ok)
|
|
276
|
+
throw new Error('Could not read remote snapshots before push.');
|
|
277
|
+
const snapshots = await snapshotsResponse.json();
|
|
278
|
+
const latest = snapshots.items?.sort((a, b) => b.revision - a.revision)[0];
|
|
279
|
+
if (latest?.sha256 === hash) {
|
|
280
|
+
const pending = await readPendingOperation(root, id, 'snapshot');
|
|
281
|
+
if (pending) {
|
|
282
|
+
const result = await reconcileOperation(ctx, pending.operationId, pending.payloadHash);
|
|
283
|
+
if (result && (result.changeId !== remoteId || result.sha256 !== hash))
|
|
284
|
+
throw new Error('Pending snapshot operation result does not match the current remote snapshot.');
|
|
285
|
+
await clearPendingOperation(root, id, 'snapshot');
|
|
286
|
+
}
|
|
287
|
+
await saveSyncState(root, id, { remoteId, baseRevision: metadata.revision, baseHash: hash, capturedAt: latest.createdAt ?? new Date().toISOString() });
|
|
288
|
+
return { state: 'unchanged', remoteId, revision: metadata.revision, hash };
|
|
289
|
+
}
|
|
290
|
+
if (latest && latest.sha256 !== local?.baseHash)
|
|
291
|
+
return { state: 'conflict', conflict: 'remote_revision_changed', nextAction: 'Run sync pull --change and resolve the conflict before pushing.' };
|
|
292
|
+
}
|
|
293
|
+
const preview = { change: id, remoteId: remoteId ?? null, expectedRevision: revision, payloadHash: hash, bytes: pkg.bytes.byteLength, willCreate: !remoteId };
|
|
294
|
+
if (!options.yes && !options.preview)
|
|
295
|
+
return { state: 'preview', preview, nextAction: 'Review this package and repeat with --yes to apply.' };
|
|
296
|
+
if (!remoteId) {
|
|
297
|
+
const body = { productId: ctx.binding.productId, title: pkg.payload.change.name, description: pkg.payload.change.description ?? '' };
|
|
298
|
+
const bodyHash = sha256(canonical(body));
|
|
299
|
+
const journal = await pendingOperation(root, id, 'create', bodyHash, { method: 'POST', path: '/changes', body, expectedRevision: 0 });
|
|
300
|
+
let created = await reconcileOperation(ctx, journal.operationId, bodyHash);
|
|
301
|
+
if (!created) {
|
|
302
|
+
const response = await remoteJson(ctx, '/changes', { method: 'POST', headers: { 'Content-Type': 'application/json', 'If-Match': '"0"', 'Idempotency-Key': journal.operationId, 'X-Payload-SHA256': bodyHash }, body: canonical(body) });
|
|
303
|
+
if (response.status === 409 || response.status === 412) {
|
|
304
|
+
await clearPendingOperation(root, id, 'create');
|
|
305
|
+
throw Object.assign(new Error('Remote change creation conflicted; the local change is unchanged.'), { code: 'revision_conflict' });
|
|
306
|
+
}
|
|
307
|
+
if (!response.ok)
|
|
308
|
+
throw Object.assign(new Error('Remote change creation failed; its operation remains journaled for reconciliation.'), { code: 'remote_write_failed' });
|
|
309
|
+
created = await response.json();
|
|
310
|
+
}
|
|
311
|
+
remoteId = created.id;
|
|
312
|
+
revision = created.revision;
|
|
313
|
+
if (typeof remoteId !== 'string' || !Number.isSafeInteger(revision))
|
|
314
|
+
throw new Error('Reconciled remote change result is incomplete; operation remains journaled.');
|
|
315
|
+
await saveSyncState(root, id, { remoteId, baseRevision: revision, baseHash: null });
|
|
316
|
+
await clearPendingOperation(root, id, 'create');
|
|
317
|
+
}
|
|
318
|
+
const snapshotBody = { content: pkg.bytes.toString('base64'), contentType: 'application/json', sourceRevision: Number(pkg.payload.change.revision ?? 1), metadata: { localChangeId: id, payloadHash: hash } };
|
|
319
|
+
const snapshotHash = sha256(canonical(snapshotBody));
|
|
320
|
+
const journal = await pendingOperation(root, id, 'snapshot', snapshotHash, { method: 'POST', path: `/changes/${remoteId}/snapshots`, body: snapshotBody, expectedRevision: revision, remoteId });
|
|
321
|
+
let snapshot = await reconcileOperation(ctx, journal.operationId, snapshotHash);
|
|
322
|
+
if (!snapshot) {
|
|
323
|
+
const upload = await remoteJson(ctx, `/changes/${remoteId}/snapshots`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'If-Match': `"${revision}"`, 'Idempotency-Key': journal.operationId, 'X-Payload-SHA256': snapshotHash }, body: canonical(snapshotBody) });
|
|
324
|
+
if (upload.status === 409 || upload.status === 412) {
|
|
325
|
+
await clearPendingOperation(root, id, 'snapshot');
|
|
326
|
+
return { state: 'conflict', conflict: 'revision_conflict', nextAction: 'Run sync status and sync pull --change; the local change was not overwritten.' };
|
|
327
|
+
}
|
|
328
|
+
if (!upload.ok)
|
|
329
|
+
throw Object.assign(new Error('Remote snapshot upload failed; its operation remains journaled for reconciliation.'), { code: 'remote_write_failed' });
|
|
330
|
+
snapshot = await upload.json();
|
|
331
|
+
}
|
|
332
|
+
if (!snapshot || snapshot.changeId !== remoteId || snapshot.sha256 !== hash)
|
|
333
|
+
throw new Error('Reconciled snapshot result does not match the pending local payload.');
|
|
334
|
+
await saveSyncState(root, id, { remoteId, baseRevision: snapshot.changeRevision, baseHash: hash, capturedAt: snapshot.createdAt ?? new Date().toISOString() });
|
|
335
|
+
await clearPendingOperation(root, id, 'snapshot');
|
|
336
|
+
return { state: 'pushed', remoteId, revision: snapshot.changeRevision, hash };
|
|
337
|
+
}
|
|
338
|
+
export async function syncPull(root, id, options = {}) {
|
|
339
|
+
const local = await syncState(root, id);
|
|
340
|
+
if (!local)
|
|
341
|
+
return { state: 'conflict', conflict: 'unbound_local_change', nextAction: 'Push once to establish a remote binding; local files are unchanged.' };
|
|
342
|
+
const pkg = await changePackage(root, id), ctx = await syncContext(root, options);
|
|
343
|
+
const metadataResponse = await remoteJson(ctx, `/changes/${local.remoteId}`);
|
|
344
|
+
if (!metadataResponse.ok)
|
|
345
|
+
throw new Error('Could not read remote change.');
|
|
346
|
+
const metadata = await metadataResponse.json();
|
|
347
|
+
const listResponse = await remoteJson(ctx, `/changes/${local.remoteId}/snapshots`);
|
|
348
|
+
if (!listResponse.ok)
|
|
349
|
+
throw new Error('Could not read remote snapshots.');
|
|
350
|
+
const page = await listResponse.json(), latest = page.items?.sort((a, b) => b.revision - a.revision)[0];
|
|
351
|
+
if (!latest || latest.sha256 === pkg.hash)
|
|
352
|
+
return { state: 'unchanged', remoteId: local.remoteId, revision: metadata.revision };
|
|
353
|
+
if (pkg.hash !== local.baseHash)
|
|
354
|
+
return { state: 'conflict', conflict: 'divergent_edits', nextAction: 'Preserve local edits; compare the remote snapshot manually, then resolve before retrying.' };
|
|
355
|
+
const contentResponse = await remoteJson(ctx, `/changes/${local.remoteId}/snapshots/${latest.id}`);
|
|
356
|
+
if (!contentResponse.ok)
|
|
357
|
+
throw new Error('Could not retrieve remote snapshot content.');
|
|
358
|
+
const remote = await contentResponse.json();
|
|
359
|
+
const decoded = Buffer.from(remote.content, 'base64');
|
|
360
|
+
if (decoded.byteLength > MAX_SYNC_BYTES || sha256(decoded) !== remote.sha256)
|
|
361
|
+
throw new Error('Remote snapshot failed size or hash verification.');
|
|
362
|
+
let parsed;
|
|
363
|
+
try {
|
|
364
|
+
parsed = JSON.parse(decoded.toString('utf8'));
|
|
365
|
+
}
|
|
366
|
+
catch {
|
|
367
|
+
throw new Error('Remote snapshot is not a valid sync package.');
|
|
368
|
+
}
|
|
369
|
+
await reconcileRemotePackage(root, id, pkg.payload, parsed);
|
|
370
|
+
await saveSyncState(root, id, { remoteId: local.remoteId, baseRevision: metadata.revision, baseHash: latest.sha256, capturedAt: latest.createdAt ?? new Date().toISOString() });
|
|
371
|
+
return { state: 'pulled', remoteId: local.remoteId, revision: metadata.revision, hash: latest.sha256 };
|
|
372
|
+
}
|
|
373
|
+
export async function syncResolve(root, id, strategy, options = {}) {
|
|
374
|
+
const local = await syncState(root, id);
|
|
375
|
+
if (!local?.remoteId)
|
|
376
|
+
return { state: 'conflict', conflict: 'unbound_local_change', nextAction: 'Push once to establish a remote binding before resolving a conflict.' };
|
|
377
|
+
if (typeof local.baseHash !== 'string' || !/^[a-f0-9]{64}$/.test(local.baseHash) || !Number.isSafeInteger(local.baseRevision) || local.baseRevision < 1) {
|
|
378
|
+
return { state: 'conflict', conflict: 'missing_sync_base', nextAction: 'Fetch a verified base with sync pull or restore the local sync metadata; no remote write was attempted.' };
|
|
379
|
+
}
|
|
380
|
+
if (strategy !== 'keep-local')
|
|
381
|
+
throw new Error('Conflict resolution requires the explicit keep-local strategy.');
|
|
382
|
+
const pkg = await changePackage(root, id), ctx = await syncContext(root, options);
|
|
383
|
+
const metadataResponse = await remoteJson(ctx, `/changes/${local.remoteId}`);
|
|
384
|
+
if (!metadataResponse.ok)
|
|
385
|
+
throw new Error('Could not read the current remote revision; conflict remains unresolved.');
|
|
386
|
+
const metadata = await metadataResponse.json();
|
|
387
|
+
if (!Number.isSafeInteger(metadata.revision) || metadata.revision < 1)
|
|
388
|
+
return { state: 'conflict', conflict: 'incompatible_remote_revision', nextAction: 'Refresh workspace capabilities and inspect the remote change before retrying.' };
|
|
389
|
+
const listResponse = await remoteJson(ctx, `/changes/${local.remoteId}/snapshots`);
|
|
390
|
+
if (!listResponse.ok)
|
|
391
|
+
throw new Error('Could not read the current remote snapshot; conflict remains unresolved.');
|
|
392
|
+
const page = await listResponse.json();
|
|
393
|
+
if (!Array.isArray(page.items))
|
|
394
|
+
return { state: 'conflict', conflict: 'incompatible_remote_snapshot', nextAction: 'Remote snapshot metadata is malformed; no local base was advanced and no write was attempted.' };
|
|
395
|
+
const latest = page.items.slice().sort((a, b) => b.revision - a.revision)[0];
|
|
396
|
+
if (!latest || latest.changeId !== local.remoteId || !Number.isSafeInteger(latest.revision) || latest.revision < 1 || !/^[a-f0-9]{64}$/.test(latest.sha256) || latest.revision !== metadata.snapshotRevision) {
|
|
397
|
+
return { state: 'conflict', conflict: 'incompatible_remote_snapshot', nextAction: 'Remote snapshot metadata does not match the current change; no local base was advanced.' };
|
|
398
|
+
}
|
|
399
|
+
const contentResponse = await remoteJson(ctx, `/changes/${local.remoteId}/snapshots/${latest.id}`);
|
|
400
|
+
if (!contentResponse.ok)
|
|
401
|
+
throw new Error('Could not retrieve the current remote snapshot; conflict remains unresolved.');
|
|
402
|
+
const remote = await contentResponse.json();
|
|
403
|
+
let decoded;
|
|
404
|
+
try {
|
|
405
|
+
decoded = Buffer.from(remote.content, 'base64');
|
|
406
|
+
}
|
|
407
|
+
catch {
|
|
408
|
+
return { state: 'conflict', conflict: 'incompatible_remote_snapshot', nextAction: 'Remote snapshot content is malformed; no local base was advanced.' };
|
|
409
|
+
}
|
|
410
|
+
if (decoded.byteLength > MAX_SYNC_BYTES || remote.id !== latest.id || remote.changeId !== local.remoteId || remote.revision !== latest.revision || remote.sha256 !== latest.sha256 || sha256(decoded) !== latest.sha256) {
|
|
411
|
+
return { state: 'conflict', conflict: 'incompatible_remote_snapshot', nextAction: 'Remote snapshot failed identity, revision, size, or hash verification; no local base was advanced.' };
|
|
412
|
+
}
|
|
413
|
+
let remotePackage;
|
|
414
|
+
try {
|
|
415
|
+
remotePackage = JSON.parse(decoded.toString('utf8'));
|
|
416
|
+
validateRemotePackage(id, remotePackage);
|
|
417
|
+
}
|
|
418
|
+
catch {
|
|
419
|
+
return { state: 'conflict', conflict: 'incompatible_remote_snapshot', nextAction: 'Remote snapshot does not match this change schema or artifact identity; no local base was advanced.' };
|
|
420
|
+
}
|
|
421
|
+
if (latest.sha256 === local.baseHash) {
|
|
422
|
+
await saveSyncState(root, id, { ...local, baseRevision: metadata.revision, capturedAt: latest.createdAt ?? new Date().toISOString() });
|
|
423
|
+
return { state: 'no_conflict', remoteId: local.remoteId, baseRevision: metadata.revision, localHash: pkg.hash, remoteHash: latest.sha256 };
|
|
424
|
+
}
|
|
425
|
+
if (latest.sha256 === pkg.hash) {
|
|
426
|
+
await saveSyncState(root, id, { ...local, baseRevision: metadata.revision, baseHash: latest.sha256, capturedAt: latest.createdAt ?? new Date().toISOString() });
|
|
427
|
+
return { state: 'already_synced', remoteId: local.remoteId, baseRevision: metadata.revision, hash: pkg.hash };
|
|
428
|
+
}
|
|
429
|
+
// The user explicitly chose the reconciled local package as the next desired state.
|
|
430
|
+
// Advance only the verified base; the subsequent push still uses the current CAS revision.
|
|
431
|
+
await saveSyncState(root, id, { ...local, baseRevision: metadata.revision, baseHash: latest.sha256, capturedAt: latest.createdAt ?? new Date().toISOString(), resolution: { strategy, localHash: pkg.hash, remoteHash: latest.sha256, remoteRevision: metadata.revision, resolvedAt: new Date().toISOString() } });
|
|
432
|
+
return { state: 'resolved', strategy, remoteId: local.remoteId, baseRevision: metadata.revision, localHash: pkg.hash, remoteHash: latest.sha256, nextAction: 'Review the local artifacts, then run sync push --yes to retry conditionally against this remote revision.' };
|
|
433
|
+
}
|
|
434
|
+
export async function syncCheckpoint(root, id, input, options = {}) {
|
|
435
|
+
if (!input.name.trim() || input.name.length > 100 || (input.summary !== undefined && input.summary.length > 4096))
|
|
436
|
+
throw new Error('Checkpoint name or summary does not match the supported schema.');
|
|
437
|
+
const local = await syncState(root, id);
|
|
438
|
+
if (!local?.remoteId)
|
|
439
|
+
throw new Error('Change must be synchronized before creating a remote checkpoint.');
|
|
440
|
+
const ctx = await syncContext(root, { ...options, requiredOperations: ['checkpoint'] });
|
|
441
|
+
const metadataResponse = await remoteJson(ctx, `/changes/${local.remoteId}`);
|
|
442
|
+
if (!metadataResponse.ok)
|
|
443
|
+
throw new Error('Could not read remote change before checkpoint.');
|
|
444
|
+
const metadata = await metadataResponse.json();
|
|
445
|
+
if (!Number.isSafeInteger(metadata.snapshotRevision) || metadata.snapshotRevision < 1)
|
|
446
|
+
throw new Error('A synchronized snapshot is required before checkpointing.');
|
|
447
|
+
const body = { name: input.name, snapshotRevision: metadata.snapshotRevision, ...(input.summary === undefined ? {} : { summary: input.summary }), ...(input.backlogStatus === undefined ? {} : { backlogStatus: input.backlogStatus }) };
|
|
448
|
+
const bodyHash = sha256(canonical(body));
|
|
449
|
+
const journal = await pendingOperation(root, id, 'checkpoint', bodyHash, { method: 'POST', path: `/changes/${local.remoteId}/checkpoints`, body, expectedRevision: metadata.revision, remoteId: local.remoteId });
|
|
450
|
+
let result = await reconcileOperation(ctx, journal.operationId, bodyHash);
|
|
451
|
+
if (!result) {
|
|
452
|
+
const response = await remoteJson(ctx, `/changes/${local.remoteId}/checkpoints`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'If-Match': `"${journal.expectedRevision}"`, 'Idempotency-Key': journal.operationId, 'X-Payload-SHA256': bodyHash }, body: canonical(body) });
|
|
453
|
+
if (response.status === 409 || response.status === 412) {
|
|
454
|
+
await clearPendingOperation(root, id, 'checkpoint');
|
|
455
|
+
return { state: 'conflict', conflict: 'revision_conflict', nextAction: 'Refresh remote change state and create a new checkpoint after reviewing the revision.' };
|
|
456
|
+
}
|
|
457
|
+
if (!response.ok)
|
|
458
|
+
throw Object.assign(new Error('Remote checkpoint failed; its operation remains journaled for reconciliation.'), { code: 'remote_write_failed' });
|
|
459
|
+
result = await response.json();
|
|
460
|
+
}
|
|
461
|
+
if (!result || result.changeId !== local.remoteId || result.name !== body.name || result.snapshotRevision !== body.snapshotRevision)
|
|
462
|
+
throw new Error('Reconciled checkpoint result does not match the pending operation.');
|
|
463
|
+
await clearPendingOperation(root, id, 'checkpoint');
|
|
464
|
+
return { state: 'checkpointed', remoteId: local.remoteId, checkpoint: result };
|
|
465
|
+
}
|
|
466
|
+
async function discoverCapabilities(profile, options = {}) {
|
|
467
|
+
const { token } = await resolveCredential({ server: profile.origin, allowFileStore: options.allowFileStore, fetch: options.fetch, store: options.store, loadStore: options.loadStore });
|
|
468
|
+
const response = await (options.fetch ?? fetch)(`${profile.origin}/development/v1/capabilities`, { headers: { Authorization: `Bearer ${token}`, 'X-Notchlet-Client-Version': '0.1.0' } });
|
|
469
|
+
if (response.status === 401)
|
|
470
|
+
throw Object.assign(new Error('Server rejected the credential; authenticate again.'), { diagnostic: 'credential_revoked' });
|
|
471
|
+
if (response.status === 403)
|
|
472
|
+
throw Object.assign(new Error('Credential lacks the required workspace:read scope.'), { diagnostic: 'scope_insufficient' });
|
|
473
|
+
if (!response.ok)
|
|
474
|
+
throw Object.assign(new Error('Capabilities endpoint is unavailable.'), { diagnostic: 'server_unavailable' });
|
|
475
|
+
const capabilities = await response.json();
|
|
476
|
+
const version = (v) => v.split('.').map((x) => Number(x));
|
|
477
|
+
const compare = (a, b) => (a[0] - b[0]) || ((a[1] ?? 0) - (b[1] ?? 0));
|
|
478
|
+
const min = version(capabilities.protocol?.minimum ?? '0.0'), max = version(capabilities.protocol?.maximum ?? '0.0'), client = [1, 0];
|
|
479
|
+
if (!capabilities.server?.id || !capabilities.server.version || !capabilities.versions?.core || !capabilities.versions?.schema)
|
|
480
|
+
throw Object.assign(new Error('Capabilities response is incomplete.'), { diagnostic: 'backend_version_mismatch' });
|
|
481
|
+
if (compare(min, client) > 0 || compare(max, client) < 0)
|
|
482
|
+
return { capabilities, diagnostic: 'protocol_mismatch' };
|
|
483
|
+
if (capabilities.versions.schema !== '1.0.0' || capabilities.server.version !== capabilities.versions.core)
|
|
484
|
+
return { capabilities, diagnostic: 'backend_version_mismatch' };
|
|
485
|
+
return { capabilities, diagnostic: 'ok' };
|
|
486
|
+
}
|
|
487
|
+
function accessibleProducts(context) {
|
|
488
|
+
const organizations = Array.isArray(context) ? context : context?.organizations ?? [];
|
|
489
|
+
return organizations.flatMap((org) => org.teams ?? []).flatMap((team) => team.products ?? []);
|
|
490
|
+
}
|
|
491
|
+
const resultValue = (response) => {
|
|
492
|
+
const text = response.content?.find((part) => part.type === 'text')?.text;
|
|
493
|
+
if (text) {
|
|
494
|
+
try {
|
|
495
|
+
return JSON.parse(text);
|
|
496
|
+
}
|
|
497
|
+
catch {
|
|
498
|
+
return text;
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
return response.structuredContent ?? response;
|
|
502
|
+
};
|
|
503
|
+
function normalizedRepoRemote(repo) {
|
|
504
|
+
if (!repo || typeof repo.repoOwner !== 'string' || typeof repo.repoName !== 'string')
|
|
505
|
+
return null;
|
|
506
|
+
let host = '';
|
|
507
|
+
if (typeof repo.serverUrl === 'string' && repo.serverUrl) {
|
|
508
|
+
try {
|
|
509
|
+
host = new URL(repo.serverUrl).hostname.toLowerCase();
|
|
510
|
+
}
|
|
511
|
+
catch {
|
|
512
|
+
return null;
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
else {
|
|
516
|
+
const provider = String(repo.provider ?? '').toLowerCase();
|
|
517
|
+
host = provider === 'github' ? 'github.com' : provider === 'gitlab' ? 'gitlab.com' : provider === 'bitbucket' ? 'bitbucket.org' : '';
|
|
518
|
+
}
|
|
519
|
+
if (!host)
|
|
520
|
+
return null;
|
|
521
|
+
return normalizeRemote({ host, owner: repo.repoOwner, repo: repo.repoName });
|
|
522
|
+
}
|
|
523
|
+
async function verifyProductRepository(input) {
|
|
524
|
+
if (input.profile.authMode !== 'user') {
|
|
525
|
+
const options = { server: input.profile.origin, endpoint: input.endpoint, fetch: input.fetch, allowFileStore: input.allowFileStore, store: input.store, loadStore: input.loadStore };
|
|
526
|
+
const context = resultValue(await callMcpTool('workspace_context', {}, options));
|
|
527
|
+
if (!accessibleProducts(context).some((p) => Number(p.id) === input.productId))
|
|
528
|
+
throw Object.assign(new Error('Selected product is not accessible in workspace_context.'), { diagnostic: 'product_access_denied' });
|
|
529
|
+
const product = resultValue(await callMcpTool('product_get_details', { productId: input.productId }, options));
|
|
530
|
+
if (Number(product?.id ?? product?.product?.id) !== input.productId)
|
|
531
|
+
throw Object.assign(new Error('Selected product identity did not match the requested numeric ID.'), { diagnostic: 'product_access_denied' });
|
|
532
|
+
const response = resultValue(await callMcpTool('backlog_list', { productId: input.productId }, options));
|
|
533
|
+
const items = Array.isArray(response) ? response : Array.isArray(response?.items) ? response.items : [];
|
|
534
|
+
const carrier = items.find((candidate) => Number(candidate.productId ?? candidate.product?.id) === input.productId && positiveId(Number(candidate.id)));
|
|
535
|
+
if (!carrier)
|
|
536
|
+
throw Object.assign(new Error('No accessible backlog item is available to inspect this product repository list.'), { diagnostic: 'repository_unavailable' });
|
|
537
|
+
let cursor;
|
|
538
|
+
const seen = new Set();
|
|
539
|
+
for (let page = 0; page < 20; page++) {
|
|
540
|
+
const repositoryPage = resultValue(await callMcpTool('backlog_development_context', { itemId: Number(carrier.id), section: 'repositories', limit: 20, ...(cursor ? { cursor } : {}) }, options));
|
|
541
|
+
const repositories = repositoryPage?.items ?? repositoryPage?.git?.repositories?.items ?? [];
|
|
542
|
+
const selected = repositories.find((repo) => Number(repo.id) === input.repositoryId);
|
|
543
|
+
if (selected) {
|
|
544
|
+
const repositoryRemote = normalizedRepoRemote(selected);
|
|
545
|
+
if (!repositoryRemote)
|
|
546
|
+
throw Object.assign(new Error('Selected repository has no normalizable remote identity.'), { diagnostic: 'repository_mismatch' });
|
|
547
|
+
return { product, repository: selected, repositoryRemote };
|
|
548
|
+
}
|
|
549
|
+
const next = repositoryPage?.nextCursor ?? repositoryPage?.git?.repositories?.nextCursor;
|
|
550
|
+
if (typeof next !== 'string' || !next)
|
|
551
|
+
break;
|
|
552
|
+
if (seen.has(next))
|
|
553
|
+
throw Object.assign(new Error('Repository list returned a repeated cursor.'), { diagnostic: 'repository_mismatch' });
|
|
554
|
+
seen.add(next);
|
|
555
|
+
cursor = next;
|
|
556
|
+
}
|
|
557
|
+
throw Object.assign(new Error('Selected repository ID is not connected to the selected product.'), { diagnostic: 'repository_mismatch' });
|
|
558
|
+
}
|
|
559
|
+
const api = await platformApi(input.profile.origin, { fetch: input.fetch, allowFileStore: input.allowFileStore, store: input.store, loadStore: input.loadStore });
|
|
560
|
+
const product = await api.get(`/products/${input.productId}`);
|
|
561
|
+
if (Number(product?.id) !== input.productId)
|
|
562
|
+
throw Object.assign(new Error('Selected product identity did not match the requested numeric ID.'), { diagnostic: 'product_access_denied' });
|
|
563
|
+
const config = await api.get(`/git/config?productId=${input.productId}`);
|
|
564
|
+
const repositories = Array.isArray(config) ? config : config ? [config] : [];
|
|
565
|
+
const selected = repositories.find((repo) => Number(repo.id) === input.repositoryId);
|
|
566
|
+
if (!selected)
|
|
567
|
+
throw Object.assign(new Error('Selected repository ID is not connected to the selected product.'), { diagnostic: 'repository_mismatch' });
|
|
568
|
+
const repositoryRemote = normalizedRepoRemote(selected);
|
|
569
|
+
if (!repositoryRemote)
|
|
570
|
+
throw Object.assign(new Error('Selected repository has no normalizable remote identity.'), { diagnostic: 'repository_mismatch' });
|
|
571
|
+
return { product, repository: selected, repositoryRemote };
|
|
572
|
+
}
|
|
573
|
+
export async function bindWorkspace(root, input) {
|
|
574
|
+
if (!positiveId(input.productId) || !positiveId(input.repositoryId))
|
|
575
|
+
throw new Error('Product and repository IDs must be positive integers.');
|
|
576
|
+
const profile = await getProfile(input.server);
|
|
577
|
+
if (!profile)
|
|
578
|
+
throw new Error('No profile exists for the selected server; authenticate first.');
|
|
579
|
+
if (input.endpoint)
|
|
580
|
+
endpointFor(profile, input.endpoint);
|
|
581
|
+
const { capabilities } = await discoverCapabilities(profile, input);
|
|
582
|
+
const verified = await verifyProductRepository({ ...input, profile });
|
|
583
|
+
const git = await inspectGitContext(root);
|
|
584
|
+
if (!git.available || !git.isRepository)
|
|
585
|
+
throw new Error('Workspace binding requires a Git checkout.');
|
|
586
|
+
const localRemotes = git.repository.remotes.map(normalizeRemote);
|
|
587
|
+
const matchingRemote = localRemotes.includes(verified.repositoryRemote);
|
|
588
|
+
if (!matchingRemote)
|
|
589
|
+
throw Object.assign(new Error('Selected product repository remote does not match this Git checkout.'), { diagnostic: 'repository_mismatch' });
|
|
590
|
+
const file = path.join(root, '.notchlet', 'workspace.json');
|
|
591
|
+
const old = JSON.parse(await readFile(file, 'utf8'));
|
|
592
|
+
const binding = { serverIdentity: capabilities.server.id, server: profile.origin, endpoint: input.endpoint, protocol: capabilities.protocol, coreVersion: capabilities.versions.core, schemaVersion: capabilities.versions.schema, productId: input.productId, repositoryId: input.repositoryId, repositoryRemote: verified.repositoryRemote, gitRoot: git.repository.topLevel };
|
|
593
|
+
const prior = old.binding;
|
|
594
|
+
const fields = ['serverIdentity', 'server', 'productId', 'repositoryId', 'repositoryRemote', 'gitRoot'];
|
|
595
|
+
if (prior && !input.rebind && fields.some(field => prior[field] !== binding[field]))
|
|
596
|
+
throw new Error('Workspace binding differs from the current server or checkout; pass --rebind to confirm.');
|
|
597
|
+
if (prior && !input.rebind && (prior.coreVersion !== binding.coreVersion || prior.schemaVersion !== binding.schemaVersion || JSON.stringify(prior.protocol) !== JSON.stringify(binding.protocol)))
|
|
598
|
+
throw new Error('Server capability versions changed; pass --rebind to confirm the updated binding.');
|
|
599
|
+
if (prior && !input.rebind && prior.endpoint !== binding.endpoint)
|
|
600
|
+
throw new Error('Workspace MCP endpoint changed; pass --rebind to confirm.');
|
|
601
|
+
if (prior && !input.rebind && fields.every(field => prior[field] === binding[field]) && prior.coreVersion === binding.coreVersion && prior.schemaVersion === binding.schemaVersion && JSON.stringify(prior.protocol) === JSON.stringify(binding.protocol) && prior.endpoint === binding.endpoint)
|
|
602
|
+
return { binding: prior, rebound: false, alreadyBound: true };
|
|
603
|
+
old.binding = binding;
|
|
604
|
+
await writeFile(file, `${JSON.stringify(old, null, 2)}\n`);
|
|
605
|
+
return { binding, rebound: Boolean(prior && input.rebind) };
|
|
606
|
+
}
|
|
607
|
+
function endpointFor(profile, override) {
|
|
608
|
+
const raw = override ?? `${profile.origin}/mcp`;
|
|
609
|
+
const url = new URL(raw, profile.origin);
|
|
610
|
+
if ((url.protocol !== 'https:' && url.hostname !== 'localhost' && url.hostname !== '127.0.0.1') || url.username || url.password || url.search || url.hash)
|
|
611
|
+
throw new Error('MCP endpoint must use HTTPS (HTTP is allowed only on localhost) and contain no credentials, query, or fragment.');
|
|
612
|
+
return url;
|
|
613
|
+
}
|
|
614
|
+
export async function platformApi(server, options = {}) {
|
|
615
|
+
const { profile, token } = await resolveCredential({ server, allowFileStore: options.allowFileStore, fetch: options.fetch, store: options.store, loadStore: options.loadStore });
|
|
616
|
+
const fetcher = options.fetch ?? fetch;
|
|
617
|
+
return {
|
|
618
|
+
origin: profile.origin,
|
|
619
|
+
token,
|
|
620
|
+
fetcher,
|
|
621
|
+
async get(route, init = {}) {
|
|
622
|
+
const response = await fetcher(`${profile.origin}${route}`, { ...init, headers: { Authorization: `Bearer ${token}`, ...(init.headers ?? {}) } });
|
|
623
|
+
if (response.status === 401)
|
|
624
|
+
throw new Error('Notchlet rejected the login session. Run `notchlet auth login` again.');
|
|
625
|
+
if (response.status === 403)
|
|
626
|
+
throw new Error('This account does not have access to the selected Notchlet resource.');
|
|
627
|
+
if (!response.ok)
|
|
628
|
+
throw new Error(`Notchlet API request failed with HTTP ${response.status}.`);
|
|
629
|
+
return response.status === 204 ? undefined : response.json();
|
|
630
|
+
},
|
|
631
|
+
};
|
|
632
|
+
}
|
|
633
|
+
export async function setWorkspaceSyncMode(root, mode) {
|
|
634
|
+
const file = path.join(root, '.notchlet', 'workspace.json');
|
|
635
|
+
const workspace = JSON.parse(await readFile(file, 'utf8'));
|
|
636
|
+
workspace.preferences = { ...(workspace.preferences ?? {}), syncMode: mode };
|
|
637
|
+
const temporary = `${file}.${randomUUID()}.tmp`;
|
|
638
|
+
await writeFile(temporary, `${JSON.stringify(workspace, null, 2)}\n`, { flag: 'wx' });
|
|
639
|
+
await rename(temporary, file);
|
|
640
|
+
return { syncMode: mode };
|
|
641
|
+
}
|
|
642
|
+
export async function getWorkspaceSyncMode(root) {
|
|
643
|
+
try {
|
|
644
|
+
const workspace = JSON.parse(await readFile(path.join(root, '.notchlet', 'workspace.json'), 'utf8'));
|
|
645
|
+
return workspace.preferences?.syncMode === 'auto' ? 'auto' : 'manual';
|
|
646
|
+
}
|
|
647
|
+
catch (error) {
|
|
648
|
+
if (error.code === 'ENOENT')
|
|
649
|
+
return 'manual';
|
|
650
|
+
throw error;
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
/** Best-effort reconciliation in auto mode; pulls are guarded and divergent edits remain explicit. */
|
|
654
|
+
export async function autoSyncChange(root, id, options = {}) {
|
|
655
|
+
if (await getWorkspaceSyncMode(root) !== 'auto')
|
|
656
|
+
return { state: 'manual', change: id };
|
|
657
|
+
try {
|
|
658
|
+
const status = await syncStatus(root, id, options);
|
|
659
|
+
if (status.state === 'unchanged')
|
|
660
|
+
return { state: 'unchanged', change: id, remoteId: status.remoteId };
|
|
661
|
+
if (status.state === 'remote-only')
|
|
662
|
+
return { ...(await syncPull(root, id, options)), automatic: true };
|
|
663
|
+
if (status.state === 'divergent')
|
|
664
|
+
return { state: 'conflict', change: id, conflict: 'divergent_edits', nextAction: 'Local and remote edits differ from the shared base. Run sync status and resolve explicitly.' };
|
|
665
|
+
return { ...(await syncPush(root, id, { ...options, yes: true })), automatic: true };
|
|
666
|
+
}
|
|
667
|
+
catch (error) {
|
|
668
|
+
return { state: 'pending', change: id, message: error instanceof Error ? error.message : 'Sync unavailable; local work remains saved.' };
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
export async function callMcpTool(toolName, args, options = {}) {
|
|
672
|
+
const { profile, token } = await resolveCredential(options);
|
|
673
|
+
const transport = new StreamableHTTPClientTransport(endpointFor(profile, options.endpoint), { requestInit: { headers: { Authorization: `Bearer ${token}` } }, ...(options.fetch ? { fetch: options.fetch } : {}) });
|
|
674
|
+
const client = new Client({ name: 'notchlet-cli', version: '0.1.0' }, { capabilities: {} });
|
|
675
|
+
try {
|
|
676
|
+
await client.connect(transport);
|
|
677
|
+
const tools = await client.listTools();
|
|
678
|
+
if (!tools.tools.some(tool => tool.name === toolName))
|
|
679
|
+
throw new Error(`MCP server does not advertise required tool: ${toolName}`);
|
|
680
|
+
const result = await client.callTool({ name: toolName, arguments: args });
|
|
681
|
+
if (result.isError)
|
|
682
|
+
throw new Error(`MCP tool ${toolName} failed.`);
|
|
683
|
+
return result;
|
|
684
|
+
}
|
|
685
|
+
catch (error) {
|
|
686
|
+
const status = error.code;
|
|
687
|
+
if (status === 401 || status === 403)
|
|
688
|
+
throw new Error(status === 401 ? 'Server rejected the credential; authenticate again.' : 'Credential lacks the required workspace:read scope.');
|
|
689
|
+
throw error;
|
|
690
|
+
}
|
|
691
|
+
finally {
|
|
692
|
+
await client.close().catch(() => undefined);
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
export async function doctor(root, options = {}) {
|
|
696
|
+
const git = await inspectGitContext(root ?? process.cwd());
|
|
697
|
+
const profile = await getProfile(options.server);
|
|
698
|
+
if (!profile)
|
|
699
|
+
return { online: false, profile: null, git, binding: null, diagnostic: 'no_profile' };
|
|
700
|
+
let capabilities = null, online = false, diagnostic = 'offline';
|
|
701
|
+
try {
|
|
702
|
+
const discovered = await discoverCapabilities(profile, options);
|
|
703
|
+
capabilities = discovered.capabilities;
|
|
704
|
+
online = true;
|
|
705
|
+
diagnostic = discovered.diagnostic;
|
|
706
|
+
}
|
|
707
|
+
catch (error) {
|
|
708
|
+
diagnostic = error.diagnostic ?? 'offline';
|
|
709
|
+
}
|
|
710
|
+
let binding = null;
|
|
711
|
+
if (root)
|
|
712
|
+
try {
|
|
713
|
+
binding = JSON.parse(await readFile(path.join(root, '.notchlet', 'workspace.json'), 'utf8')).binding ?? null;
|
|
714
|
+
}
|
|
715
|
+
catch { /* uninitialized local workspace */ }
|
|
716
|
+
if (online && binding && capabilities) {
|
|
717
|
+
const bound = binding;
|
|
718
|
+
if (bound.serverIdentity !== capabilities.server.id || bound.server !== profile.origin)
|
|
719
|
+
diagnostic = 'server_identity_mismatch';
|
|
720
|
+
else if (JSON.stringify(bound.protocol) !== JSON.stringify(capabilities.protocol))
|
|
721
|
+
diagnostic = 'protocol_mismatch';
|
|
722
|
+
else if (bound.coreVersion !== capabilities.versions.core || bound.schemaVersion !== capabilities.versions.schema)
|
|
723
|
+
diagnostic = 'backend_version_mismatch';
|
|
724
|
+
try {
|
|
725
|
+
if (diagnostic !== 'ok')
|
|
726
|
+
throw Object.assign(new Error('Capability identity or version mismatch.'), { diagnostic });
|
|
727
|
+
const profileForBinding = { ...profile, origin: bound.server };
|
|
728
|
+
const verified = await verifyProductRepository({ productId: Number(bound.productId), repositoryId: Number(bound.repositoryId), profile: profileForBinding, endpoint: options.endpoint ?? bound.endpoint, allowFileStore: options.allowFileStore, fetch: options.fetch, store: options.store, loadStore: options.loadStore });
|
|
729
|
+
const currentRemote = git.available && git.isRepository ? git.repository.remotes.map(normalizeRemote).includes(verified.repositoryRemote) : false;
|
|
730
|
+
if (!currentRemote || bound.repositoryRemote !== verified.repositoryRemote || bound.gitRoot !== (git.available && git.isRepository ? git.repository.topLevel : null))
|
|
731
|
+
diagnostic = 'repository_mismatch';
|
|
732
|
+
}
|
|
733
|
+
catch (error) {
|
|
734
|
+
const code = error.diagnostic;
|
|
735
|
+
if (code)
|
|
736
|
+
diagnostic = code;
|
|
737
|
+
else if (diagnostic === 'ok')
|
|
738
|
+
diagnostic = 'product_access_denied';
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
const authScopes = !online ? [] : profile.authMode === 'user' ? ['workspace:read', 'changes:write', 'backlog:write'] : ['workspace:read'];
|
|
742
|
+
return { online, profile: { origin: profile.origin, serverIdentity: profile.serverIdentity, authMode: profile.authMode ?? 'token' }, capabilities, authScopes, git, binding, diagnostic };
|
|
743
|
+
}
|
|
744
|
+
export async function importBacklogItem(root, input) {
|
|
745
|
+
if (!positiveId(input.productId) || !positiveId(input.itemId))
|
|
746
|
+
throw new Error('Product and backlog item IDs must be positive integers.');
|
|
747
|
+
const selectedProfile = await getProfile(input.server);
|
|
748
|
+
const useMcp = selectedProfile?.authMode !== 'user';
|
|
749
|
+
const api = useMcp ? null : await platformApi(input.server, input);
|
|
750
|
+
const legacyCall = (name, args) => callMcpTool(name, args, input);
|
|
751
|
+
const item = api
|
|
752
|
+
? await api.get(`/backlog/${input.itemId}`)
|
|
753
|
+
: resultValue(await legacyCall('backlog_get', { itemId: input.itemId }));
|
|
754
|
+
if (Number(item?.id) !== input.itemId || Number(item?.productId) !== input.productId)
|
|
755
|
+
throw new Error('Selected backlog item does not belong to the selected product.');
|
|
756
|
+
const contextPages = [], seenCursors = new Set();
|
|
757
|
+
let cursor, contextTruncated = false;
|
|
758
|
+
for (let page = 0; page < 3; page++) {
|
|
759
|
+
const query = new URLSearchParams({ section: 'item', limit: '20', ...(cursor ? { cursor } : {}) });
|
|
760
|
+
const contextPage = api
|
|
761
|
+
? await api.get(`/backlog/${input.itemId}/development-context?${query.toString()}`)
|
|
762
|
+
: resultValue(await legacyCall('backlog_development_context', { itemId: input.itemId, section: 'item', limit: 20, ...(cursor ? { cursor } : {}) }));
|
|
763
|
+
const candidate = [...contextPages, contextPage];
|
|
764
|
+
if (Buffer.byteLength(JSON.stringify(candidate), 'utf8') > 32_768)
|
|
765
|
+
throw new Error('Backlog development context exceeds the 32 KiB import limit.');
|
|
766
|
+
contextPages.push(contextPage);
|
|
767
|
+
const next = contextPage?.nextCursor ?? contextPage?.pagination?.nextCursor;
|
|
768
|
+
if (typeof next !== 'string' || !next)
|
|
769
|
+
break;
|
|
770
|
+
if (seenCursors.has(next))
|
|
771
|
+
throw new Error('Backlog development context returned a repeated cursor.');
|
|
772
|
+
if (page === 2) {
|
|
773
|
+
contextTruncated = true;
|
|
774
|
+
break;
|
|
775
|
+
}
|
|
776
|
+
seenCursors.add(next);
|
|
777
|
+
cursor = next;
|
|
778
|
+
}
|
|
779
|
+
const description = String(item.description ?? item.item?.description ?? '');
|
|
780
|
+
const title = String(item.title ?? item.item?.title ?? `Backlog item ${input.itemId}`);
|
|
781
|
+
const id = `backlog-${input.itemId}`;
|
|
782
|
+
const markerDir = path.join(root, '.notchlet', 'imports');
|
|
783
|
+
await mkdir(markerDir, { recursive: true });
|
|
784
|
+
const marker = path.join(markerDir, `${input.itemId}.json`);
|
|
785
|
+
try {
|
|
786
|
+
await readFile(marker, 'utf8');
|
|
787
|
+
throw new Error(`Backlog item ${input.itemId} is already linked to a local change.`);
|
|
788
|
+
}
|
|
789
|
+
catch (e) {
|
|
790
|
+
if (e.code !== 'ENOENT')
|
|
791
|
+
throw e;
|
|
792
|
+
}
|
|
793
|
+
// Scaffold is create-only; a pre-existing change is never replaced.
|
|
794
|
+
const change = await scaffold(root, `Backlog item ${input.itemId}: ${title}`, 'quick');
|
|
795
|
+
const proposal = `# ${title}\n\n## Imported backlog description\n\n${description}\n\n## Bounded development context\n\n${JSON.stringify({ pages: contextPages, truncated: contextTruncated }, null, 2)}\n`;
|
|
796
|
+
await writeFile(path.join(root, '.notchlet', 'changes', change.id, 'proposal.md'), proposal);
|
|
797
|
+
const tasksFile = path.join(root, '.notchlet', 'changes', change.id, 'tasks.json');
|
|
798
|
+
const imported = parseChange(await readFile(tasksFile, 'utf8'));
|
|
799
|
+
const requirementId = `REQ-ITEM-${input.itemId}`;
|
|
800
|
+
const criteria = item.acceptanceCriteria ?? item.acceptanceCriteriaText ?? item.item?.acceptanceCriteria;
|
|
801
|
+
const checkDescriptions = Array.isArray(criteria) ? criteria.filter((v) => typeof v === 'string' && v.trim()) : typeof criteria === 'string' && criteria.trim() ? [criteria] : [];
|
|
802
|
+
const next = { ...imported, requirements: [{ id: requirementId, title, description: description || title }], checks: (checkDescriptions.length ? checkDescriptions : [`Verify the requirements and acceptance criteria for backlog item ${input.itemId}.`]).map((text, index) => ({ id: `CHECK-ITEM-${input.itemId}-${index + 1}`, description: text })), tasks: [{ id: `TASK-ITEM-${input.itemId}`, title: `Implement backlog item ${input.itemId}`, status: 'pending', dependencies: [], requirementIds: [requirementId] }] };
|
|
803
|
+
await writeFile(tasksFile, `${JSON.stringify(next, null, 2)}\n`);
|
|
804
|
+
await writeFile(marker, `${JSON.stringify({ server: (await getProfile(input.server))?.serverIdentity, productId: input.productId, itemId: input.itemId, changeId: change.id }, null, 2)}\n`, { flag: 'wx' });
|
|
805
|
+
return next;
|
|
806
|
+
}
|