castle-web-cli 0.4.226 → 0.4.228
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/agent-prompts.d.ts +5 -0
- package/dist/agent-prompts.js +7 -7
- package/dist/agent.d.ts +1 -0
- package/dist/agent.js +159 -48
- package/dist/api.d.ts +21 -0
- package/dist/api.js +21 -3
- package/dist/castle-host/host.d.ts +6 -0
- package/dist/castle-host/host.js +42 -3
- package/dist/cloudGit.d.ts +7 -0
- package/dist/cloudGit.js +92 -14
- package/dist/cloudGitServe.js +9 -5
- package/dist/get-deck.js +5 -2
- package/dist/gitCollaborators.d.ts +16 -0
- package/dist/gitCollaborators.js +42 -0
- package/dist/gitIncoming.d.ts +17 -0
- package/dist/gitIncoming.js +113 -0
- package/dist/gitRemote.js +2 -2
- package/dist/importBrowse.js +7 -6
- package/dist/imports.d.ts +2 -1
- package/dist/imports.js +82 -13
- package/dist/init.js +17 -4
- package/dist/native/playtest-browser.js +13 -1
- package/dist/platformDoc.d.ts +1 -0
- package/dist/platformDoc.js +31 -9
- package/dist/playPagePolicy.js +35 -1
- package/dist/remix.js +1 -1
- package/dist/save-deck.d.ts +1 -7
- package/dist/save-deck.js +18 -26
- package/dist/saveFailure.d.ts +26 -0
- package/dist/saveFailure.js +102 -0
- package/dist/serve.js +17 -0
- package/dist/shell/assets/index-Cf61cNfT.css +1 -0
- package/dist/shell/assets/{index-C7ksEq3_.js → index-D2tWM896.js} +94 -94
- package/dist/shell/index.html +2 -2
- package/kits/base/CLAUDE.md +2 -1
- package/kits/base/castle.json +1 -1
- package/kits/base/sdk/README.md +87 -0
- package/kits/base/sdk/castle.d.ts +3 -1
- package/kits/base/sdk/castle.js +1 -0
- package/kits/base/sdk/commands.d.ts +6 -0
- package/kits/base/sdk/display.d.ts +36 -0
- package/kits/base/sdk/display.js +96 -0
- package/kits/base/sdk/multiplayer.d.ts +3 -1
- package/kits/base/sdk/multiplayer.js +11 -1
- package/kits/base/sdk/runtime.js +35 -17
- package/kits/base/sdk/server/platformHandle.d.ts +2 -0
- package/kits/base/sdk/server/wrapper.d.ts +58 -0
- package/kits/base/sdk/server/wrapper.js +350 -8
- package/package.json +11 -3
- package/dist/shell/assets/index-4G5NKIQ8.css +0 -1
package/dist/cloudGit.d.ts
CHANGED
|
@@ -20,6 +20,7 @@ export declare class CloudGitError extends Error {
|
|
|
20
20
|
readonly exitCode: number;
|
|
21
21
|
constructor(message: string, exitCode?: number);
|
|
22
22
|
}
|
|
23
|
+
export declare const CLOUD_LOCKFILES: string[];
|
|
23
24
|
export declare const CLOUD_EXCLUDES: string[];
|
|
24
25
|
export declare const LOOSE_OBJECT_LIMIT = 200;
|
|
25
26
|
export declare const STALE_GIT_LOCK_MS = 60000;
|
|
@@ -184,6 +185,8 @@ export interface MergeState {
|
|
|
184
185
|
mergeHead: string;
|
|
185
186
|
files: ConflictedFile[];
|
|
186
187
|
instruction: string;
|
|
188
|
+
/** Who authored the remote side, phrased for user-facing conflict copy. */
|
|
189
|
+
otherSide?: string;
|
|
187
190
|
/**
|
|
188
191
|
* Left by a rehydrate that gave up lost history mid-merge: no MERGE_HEAD any more, but the
|
|
189
192
|
* files still have markers, and the next commit must be a `--resolve`.
|
|
@@ -197,6 +200,8 @@ export interface ConflictReport {
|
|
|
197
200
|
theirs: string[];
|
|
198
201
|
ours: string[];
|
|
199
202
|
instruction: string;
|
|
203
|
+
otherSide?: string;
|
|
204
|
+
notice?: string;
|
|
200
205
|
}
|
|
201
206
|
export interface ConflictSummary {
|
|
202
207
|
files: Pick<ConflictedFile, 'path' | 'resolution'>[];
|
|
@@ -204,6 +209,8 @@ export interface ConflictSummary {
|
|
|
204
209
|
ours: string[];
|
|
205
210
|
/** This sandbox's commit when the merge started, where its version of every file is. */
|
|
206
211
|
head: string;
|
|
212
|
+
/** Defaults to the legacy generic wording for old callers and records. */
|
|
213
|
+
otherSide?: string;
|
|
207
214
|
}
|
|
208
215
|
export declare function conflictInstruction(summary: ConflictSummary): string;
|
|
209
216
|
export interface CommitOptions {
|
package/dist/cloudGit.js
CHANGED
|
@@ -6,6 +6,8 @@ import * as path from 'path';
|
|
|
6
6
|
import { fileURLToPath } from 'url';
|
|
7
7
|
import { GIT_HOSTS, GIT_REMOTE_NAME, isSandboxToken, runGit } from './gitRemote.js';
|
|
8
8
|
import { COVER_FILE } from './localPaths.js';
|
|
9
|
+
import { castleUsernameFromEmail, collaboratorUsername, otherSideLabel, } from './gitCollaborators.js';
|
|
10
|
+
import { appendGitIncoming } from './gitIncoming.js';
|
|
9
11
|
export const COMMIT_REASONS = ['turn', 'task', 'leave', 'manual', 'sync'];
|
|
10
12
|
// Commits the agent made are marked so the Versions panel (and a laptop's git log) can tell
|
|
11
13
|
// them from the user's own edits. The commit is still authored as the user.
|
|
@@ -47,7 +49,8 @@ export class CloudGitError extends Error {
|
|
|
47
49
|
}
|
|
48
50
|
// Castle's excludes, in .git/info/exclude rather than a .gitignore, so they apply whatever
|
|
49
51
|
// the deck's own .gitignore says and never show up as a change to the deck.
|
|
50
|
-
export const
|
|
52
|
+
export const CLOUD_LOCKFILES = ['package-lock.json', 'pnpm-lock.yaml', 'yarn.lock', 'bun.lock', 'bun.lockb'];
|
|
53
|
+
export const CLOUD_EXCLUDES = ['node_modules/', 'dist/', '/imports/', '.castle/', '.vite/', ...CLOUD_LOCKFILES];
|
|
51
54
|
// More loose objects than this and a commit packs the repo. Draft checkpoints no longer carry
|
|
52
55
|
// `.git/objects` (history is rebuilt from the remote, the S3 mirror and the snapshot bundle on
|
|
53
56
|
// a cold resume), but a pile of loose objects still slows every git command and the bundle.
|
|
@@ -828,20 +831,21 @@ export function conflictInstruction(summary) {
|
|
|
828
831
|
const marked = summary.files.filter((f) => f.resolution === 'markers' || f.resolution === 'manual').map((f) => f.path);
|
|
829
832
|
const taken = summary.files.filter((f) => f.resolution === 'took-laptop' || f.resolution === 'laptop-deleted');
|
|
830
833
|
const head = summary.head.slice(0, 10);
|
|
834
|
+
const otherSide = summary.otherSide ?? 'another computer';
|
|
831
835
|
const parts = [
|
|
832
|
-
|
|
836
|
+
`[Castle] Syncing this deck with its Castle git remote hit a merge conflict: changes from ${otherSide} reached main while this sandbox had changes of its own. Git merged what it could.`,
|
|
833
837
|
'Files with conflict markers (<<<<<<< / ||||||| / ======= / >>>>>>>) to resolve:',
|
|
834
838
|
list(marked),
|
|
835
839
|
];
|
|
836
840
|
if (taken.length > 0) {
|
|
837
|
-
parts.push(`Files git could not merge line by line (binary, or changed on one side and deleted on the other).
|
|
841
|
+
parts.push(`Files git could not merge line by line (binary, or changed on one side and deleted on the other). ${otherSide}'s side was taken for these automatically; this sandbox's version of each is still in commit ${head} (\`git show ${head}:<path>\`):`, list(taken.map((f) => f.resolution === 'took-laptop' ? `${f.path} (took ${otherSide}'s version)` : `${f.path} (${otherSide} deleted it)`)));
|
|
838
842
|
}
|
|
839
|
-
parts.push(
|
|
843
|
+
parts.push(`What ${otherSide} pushed (castle/main):`, list(summary.theirs), 'What was committed here since the two diverged:', list(summary.ours), `Resolve it now. Spawn one task agent to do it, told the following: open each file with conflict markers and remove every marker so the file is whole and working again. Prefer ${otherSide}'s side -- keep what was pushed, and redo this sandbox's own change on top of it where it still makes sense; dropping this sandbox's change is acceptable, breaking the pushed work is not. For a file whose ${otherSide} version was taken automatically, bring this sandbox's change back on top only if it still matters. Revert a whole commit from either side only if that is the cleanest way to a working deck. Do not run git reset, rebase, checkout, merge or push, and never force-push. No other commit lands until this merge is concluded. When no markers remain, finish with \`castle-web commit --resolve -m "Merge changes from ${otherSide}"\`, which concludes the merge and pushes it; if it exits 3, it names the files that still have markers.`, `Then tell the user in chat, briefly and plainly, that their deck had changes from ${otherSide}, what conflicted, and what was kept from each side.`);
|
|
840
844
|
return parts.join('\n');
|
|
841
845
|
}
|
|
842
846
|
// A conflicted merge: take the other computer's side where git left no markers, record the
|
|
843
847
|
// rest in .git/castle-merge.json, and write the marker the serve turns into an agent turn.
|
|
844
|
-
function recordConflict(ctx) {
|
|
848
|
+
function recordConflict(ctx, otherSide) {
|
|
845
849
|
const head = revParse(ctx, 'HEAD') ?? '';
|
|
846
850
|
const mergeHead = revParse(ctx, 'MERGE_HEAD') ?? '';
|
|
847
851
|
const files = [];
|
|
@@ -854,10 +858,18 @@ function recordConflict(ctx) {
|
|
|
854
858
|
const theirs = commitSubjects(ctx, base ? `${base}..MERGE_HEAD` : 'MERGE_HEAD');
|
|
855
859
|
const ours = commitSubjects(ctx, base ? `${base}..HEAD` : 'HEAD');
|
|
856
860
|
const at = new Date(ctx.deps.now()).toISOString();
|
|
857
|
-
const instruction = conflictInstruction({ files, theirs, ours, head });
|
|
858
|
-
const state = { at, head, mergeHead, files, instruction };
|
|
861
|
+
const instruction = conflictInstruction({ files, theirs, ours, head, otherSide });
|
|
862
|
+
const state = { at, head, mergeHead, files, instruction, otherSide };
|
|
859
863
|
writeJsonAtomic(mergeStatePath(ctx.dir), state);
|
|
860
|
-
const report = {
|
|
864
|
+
const report = {
|
|
865
|
+
at,
|
|
866
|
+
files: files.map((f) => f.path),
|
|
867
|
+
theirs,
|
|
868
|
+
ours,
|
|
869
|
+
instruction,
|
|
870
|
+
otherSide,
|
|
871
|
+
notice: `Changes from ${otherSide} conflicted with this deck; the agent is resolving them.`,
|
|
872
|
+
};
|
|
861
873
|
writeJsonAtomic(path.join(ctx.dir, CONFLICT_MARKER_FILE), report);
|
|
862
874
|
return state;
|
|
863
875
|
}
|
|
@@ -2141,6 +2153,7 @@ async function commitLocked(ctx, opts) {
|
|
|
2141
2153
|
if (recovered && !recovered.committed)
|
|
2142
2154
|
markRecoveredCommitted(ctx);
|
|
2143
2155
|
};
|
|
2156
|
+
topUpCloudExcludes(ctx);
|
|
2144
2157
|
if (opts.paths && opts.paths.length > 0) {
|
|
2145
2158
|
const specs = commitPathspecs(ctx, opts.paths);
|
|
2146
2159
|
if (specs.length === 0)
|
|
@@ -2168,8 +2181,13 @@ function fetchRemote(ctx) {
|
|
|
2168
2181
|
// One pack per fetch: all or nothing, even when a fetch is killed partway.
|
|
2169
2182
|
const args = ['fetch', '--quiet', '--prune', '--no-tags', GIT_REMOTE_NAME];
|
|
2170
2183
|
const fetched = run(ctx, ['-c', 'fetch.unpackLimit=1', '-c', 'transfer.unpackLimit=1', ...args], { timeoutMs: NETWORK_TIMEOUT_MS });
|
|
2171
|
-
if (fetched.status !== 0)
|
|
2184
|
+
if (fetched.status !== 0) {
|
|
2185
|
+
const detail = `${fetched.stderr}\n${fetched.stdout}\n${fetched.error?.message ?? ''}`;
|
|
2186
|
+
if (/repo_missing/i.test(detail)) {
|
|
2187
|
+
throw new CloudGitError("This deck's Castle git repo does not exist yet. The deck's owner needs to open it in the cloud editor once with git on.");
|
|
2188
|
+
}
|
|
2172
2189
|
throw new CloudGitError(describeFailure(args, fetched));
|
|
2190
|
+
}
|
|
2173
2191
|
return revParse(ctx, REMOTE_MAIN);
|
|
2174
2192
|
}
|
|
2175
2193
|
// Bring castle/main into local main. Local work is already committed by the caller.
|
|
@@ -2191,6 +2209,46 @@ async function commitRecoveredRoot(ctx) {
|
|
|
2191
2209
|
return;
|
|
2192
2210
|
await commitLocked(ctx, { reason: 'sync' });
|
|
2193
2211
|
}
|
|
2212
|
+
// The newest MAX_INCOMING_COMMITS only: a long-diverged remote (a first sync after a long
|
|
2213
|
+
// absence) is described, not enumerated, and each commit costs two git calls here.
|
|
2214
|
+
const MAX_INCOMING_COMMITS = 50;
|
|
2215
|
+
function incomingRemoteCommits(ctx, remote, head) {
|
|
2216
|
+
const shas = lines(must(ctx, ['rev-list', '--reverse', '-n', String(MAX_INCOMING_COMMITS), remote, '--not', head]));
|
|
2217
|
+
return shas.map((sha) => {
|
|
2218
|
+
const [fullSha, name, email, at, ...subjectParts] = must(ctx, [
|
|
2219
|
+
'show',
|
|
2220
|
+
'-s',
|
|
2221
|
+
'--format=%H%x1f%an%x1f%ae%x1f%aI%x1f%s',
|
|
2222
|
+
sha,
|
|
2223
|
+
]).trim().split('\x1f');
|
|
2224
|
+
const files = must(ctx, ['diff-tree', '--no-commit-id', '--name-only', '-r', '-z', sha])
|
|
2225
|
+
.split('\0')
|
|
2226
|
+
.filter(Boolean);
|
|
2227
|
+
return {
|
|
2228
|
+
sha: fullSha || sha,
|
|
2229
|
+
name: name || 'Castle user',
|
|
2230
|
+
email: email || '',
|
|
2231
|
+
author: castleUsernameFromEmail(email || '') ?? (name?.trim() || 'A collaborator'),
|
|
2232
|
+
subject: subjectParts.join('\x1f'),
|
|
2233
|
+
files,
|
|
2234
|
+
at: at || new Date(ctx.deps.now()).toISOString(),
|
|
2235
|
+
};
|
|
2236
|
+
});
|
|
2237
|
+
}
|
|
2238
|
+
function noteCollaboratorCommits(ctx, commits, ownEmail) {
|
|
2239
|
+
const others = commits.flatMap((commit) => {
|
|
2240
|
+
const author = collaboratorUsername(commit.email, ownEmail);
|
|
2241
|
+
return author ? [{ ...commit, author }] : [];
|
|
2242
|
+
});
|
|
2243
|
+
if (others.length === 0)
|
|
2244
|
+
return;
|
|
2245
|
+
try {
|
|
2246
|
+
appendGitIncoming(ctx.dir, others.map(({ sha, author, subject, files, at }) => ({ sha, author, subject, files, at })));
|
|
2247
|
+
}
|
|
2248
|
+
catch (err) {
|
|
2249
|
+
ctx.deps.warn(`Could not note incoming collaborator commits: ${err instanceof Error ? err.message : String(err)}`);
|
|
2250
|
+
}
|
|
2251
|
+
}
|
|
2194
2252
|
async function integrate(ctx, remote) {
|
|
2195
2253
|
await commitRecoveredRoot(ctx);
|
|
2196
2254
|
const head = revParse(ctx, 'HEAD');
|
|
@@ -2203,10 +2261,15 @@ async function integrate(ctx, remote) {
|
|
|
2203
2261
|
}
|
|
2204
2262
|
if (head === remote || ok(ctx, ['merge-base', '--is-ancestor', remote, head]))
|
|
2205
2263
|
return 'none';
|
|
2264
|
+
await identityArgs(ctx);
|
|
2265
|
+
const ownEmail = localConfig(ctx, 'user.email');
|
|
2266
|
+
const incoming = incomingRemoteCommits(ctx, remote, head);
|
|
2267
|
+
const otherSide = otherSideLabel(incoming, ownEmail);
|
|
2206
2268
|
if (deferIfBusy(ctx))
|
|
2207
2269
|
return 'deferred';
|
|
2208
2270
|
if (ok(ctx, ['merge-base', '--is-ancestor', head, remote])) {
|
|
2209
2271
|
must(ctx, ['merge', '--ff-only', '--quiet', REMOTE_MAIN]);
|
|
2272
|
+
noteCollaboratorCommits(ctx, incoming, ownEmail);
|
|
2210
2273
|
return 'fast-forward';
|
|
2211
2274
|
}
|
|
2212
2275
|
const identity = await identityArgs(ctx);
|
|
@@ -2224,13 +2287,15 @@ async function integrate(ctx, remote) {
|
|
|
2224
2287
|
'-X',
|
|
2225
2288
|
'diff-algorithm=histogram',
|
|
2226
2289
|
'-m',
|
|
2227
|
-
`Merge changes from
|
|
2290
|
+
`Merge changes from ${otherSide}`,
|
|
2228
2291
|
REMOTE_MAIN,
|
|
2229
2292
|
]);
|
|
2230
|
-
if (merge.status === 0)
|
|
2293
|
+
if (merge.status === 0) {
|
|
2294
|
+
noteCollaboratorCommits(ctx, incoming, ownEmail);
|
|
2231
2295
|
return 'merged';
|
|
2296
|
+
}
|
|
2232
2297
|
if (mergeInProgress(ctx.dir) && unmergedStages(ctx).size > 0) {
|
|
2233
|
-
const state = recordConflict(ctx);
|
|
2298
|
+
const state = recordConflict(ctx, otherSide);
|
|
2234
2299
|
ctx.deps.warn(`Merge conflict with the Castle remote in: ${state.files.map((f) => f.path).join(', ')}. Left it for the agent to resolve.`);
|
|
2235
2300
|
return 'conflict';
|
|
2236
2301
|
}
|
|
@@ -2277,10 +2342,10 @@ function pushOnly(ctx) {
|
|
|
2277
2342
|
}
|
|
2278
2343
|
async function syncLocked(ctx, opts) {
|
|
2279
2344
|
requireMainBranch(ctx);
|
|
2280
|
-
if (opts.commitFirst)
|
|
2281
|
-
await commitLocked(ctx, { reason: 'sync' });
|
|
2282
2345
|
if (mergeWaiting(ctx.dir))
|
|
2283
2346
|
throw mergeWaitingError(ctx);
|
|
2347
|
+
if (opts.commitFirst)
|
|
2348
|
+
await commitLocked(ctx, { reason: 'sync' });
|
|
2284
2349
|
if (opts.mode === 'push-only')
|
|
2285
2350
|
return pushOnly(ctx);
|
|
2286
2351
|
let merge = 'none';
|
|
@@ -2845,6 +2910,19 @@ export function writeCloudExcludes(dir) {
|
|
|
2845
2910
|
const prefix = existing && !existing.endsWith('\n') ? '\n' : '';
|
|
2846
2911
|
fs.appendFileSync(file, `${prefix}# Castle cloud sandbox\n${missing.join('\n')}\n`);
|
|
2847
2912
|
}
|
|
2913
|
+
function topUpCloudExcludes(ctx) {
|
|
2914
|
+
writeCloudExcludes(ctx.dir);
|
|
2915
|
+
const lockfiles = new Set(CLOUD_LOCKFILES);
|
|
2916
|
+
const tracked = must(ctx, ['ls-files', '-z'])
|
|
2917
|
+
.split('\0')
|
|
2918
|
+
.filter((file) => file && lockfiles.has(path.posix.basename(file)));
|
|
2919
|
+
if (tracked.length === 0)
|
|
2920
|
+
return;
|
|
2921
|
+
// Two sandboxes install dependencies independently, so tracked lockfiles conflict on nearly
|
|
2922
|
+
// every sync. package.json still carries the deck's dependencies; keep each lockfile in the
|
|
2923
|
+
// working copy while removing it from the shared cloud history once.
|
|
2924
|
+
must(ctx, ['rm', '--cached', '--quiet', '--ignore-unmatch', '--', ...tracked]);
|
|
2925
|
+
}
|
|
2848
2926
|
/** `castle-web git attach <dir> --remote <url>`. */
|
|
2849
2927
|
export async function cloudAttach(dir, remoteUrl, deps) {
|
|
2850
2928
|
requireSandbox(deps, 'git attach');
|
package/dist/cloudGitServe.js
CHANGED
|
@@ -30,7 +30,7 @@ const CONFLICT_POLL_MS = 1500;
|
|
|
30
30
|
export const MERGE_CHECK_MS = 2 * 60_000;
|
|
31
31
|
const MAX_TITLES_IN_MESSAGE = 3;
|
|
32
32
|
export const REASK_MS = 10 * 60_000;
|
|
33
|
-
const
|
|
33
|
+
const conflictNotice = (otherSide = 'another computer') => `Changes from ${otherSide} conflicted with this deck; the agent is resolving them.`;
|
|
34
34
|
/** Run this CLI as a child and collect its exit code and (the tail of) its output. */
|
|
35
35
|
export function runCastleWeb(args, cwd, env = process.env, timeoutMs = COMMIT_TIMEOUT_MS, graceMs = KILL_GRACE_MS) {
|
|
36
36
|
return new Promise((resolve) => {
|
|
@@ -129,7 +129,9 @@ export function consumeAgentMarker(deckDir, rel, sink, beforeTurn) {
|
|
|
129
129
|
fs.rmSync(file, { force: true });
|
|
130
130
|
if (typeof report.instruction !== 'string' || !report.instruction)
|
|
131
131
|
return false;
|
|
132
|
-
sink.addLog(typeof report.notice === 'string' && report.notice
|
|
132
|
+
sink.addLog(typeof report.notice === 'string' && report.notice
|
|
133
|
+
? report.notice
|
|
134
|
+
: conflictNotice(typeof report.otherSide === 'string' ? report.otherSide : undefined));
|
|
133
135
|
beforeTurn?.();
|
|
134
136
|
sink.enqueueInstruction(report.instruction);
|
|
135
137
|
return true;
|
|
@@ -263,22 +265,24 @@ export function createServeGitHooks(opts) {
|
|
|
263
265
|
return;
|
|
264
266
|
const state = readMergeState(opts.deckDir);
|
|
265
267
|
const leave = readLeavePending(opts.deckDir);
|
|
268
|
+
const otherSide = state?.otherSide ?? 'another computer';
|
|
266
269
|
const instruction = [
|
|
267
|
-
|
|
270
|
+
`[Castle] The merge with changes from ${otherSide} is still not concluded, so no commit can land until it is.`,
|
|
268
271
|
...(leave
|
|
269
272
|
? [
|
|
270
273
|
`The user left the deck at ${leave.at} with edits that could not be committed because of it${leave.paths.length ? ` (${leave.paths.slice(0, 20).join(', ')}${leave.paths.length > 20 ? ', ...' : ''})` : ''}. They are still on disk; concluding the merge commits them too, so keep them.`,
|
|
271
274
|
]
|
|
272
275
|
: []),
|
|
273
276
|
state?.instruction ??
|
|
274
|
-
|
|
277
|
+
`Spawn one task agent to remove every conflict marker (<<<<<<< / ||||||| / ======= / >>>>>>>) from the conflicted files, preferring ${otherSide}'s side, and finish with \`castle-web commit --resolve -m "Merge changes from ${otherSide}"\`. Never force-push.`,
|
|
275
278
|
].join('\n');
|
|
276
279
|
try {
|
|
277
280
|
const file = path.join(opts.deckDir, CONFLICT_MARKER_FILE);
|
|
278
281
|
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
279
282
|
fs.writeFileSync(file, JSON.stringify({
|
|
280
283
|
instruction,
|
|
281
|
-
|
|
284
|
+
otherSide,
|
|
285
|
+
notice: `A merge with changes from ${otherSide} is still unresolved; the agent is taking another look.`,
|
|
282
286
|
}));
|
|
283
287
|
}
|
|
284
288
|
catch (err) {
|
package/dist/get-deck.js
CHANGED
|
@@ -110,7 +110,10 @@ export async function getDeck(dir, options = {}) {
|
|
|
110
110
|
}
|
|
111
111
|
}
|
|
112
112
|
fs.mkdirSync(targetDir, { recursive: true });
|
|
113
|
-
|
|
113
|
+
// --no-same-owner: an archive saved on a laptop records the laptop's uid, and tar
|
|
114
|
+
// run as root (a cloud sandbox) keeps it; git then refuses the deck as "dubious
|
|
115
|
+
// ownership" and the cloud git attach fails. Same for every unpack of a deck archive.
|
|
116
|
+
await runTar(['-xzf', tmpFile, '--no-same-owner', '-C', targetDir]);
|
|
114
117
|
}
|
|
115
118
|
finally {
|
|
116
119
|
try {
|
|
@@ -247,7 +250,7 @@ async function getDeckSide(dir, options) {
|
|
|
247
250
|
const staging = path.join(root, `.partial-${nanoid(8)}`);
|
|
248
251
|
try {
|
|
249
252
|
fs.mkdirSync(staging, { recursive: true });
|
|
250
|
-
await runTar(['-xzf', tmpFile, '-C', staging]);
|
|
253
|
+
await runTar(['-xzf', tmpFile, '--no-same-owner', '-C', staging]);
|
|
251
254
|
fs.rmSync(dest, { recursive: true, force: true });
|
|
252
255
|
fs.renameSync(staging, dest);
|
|
253
256
|
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export interface GitCommitAuthor {
|
|
2
|
+
name: string;
|
|
3
|
+
email: string;
|
|
4
|
+
}
|
|
5
|
+
export interface CastleGitIdentity {
|
|
6
|
+
userId: string;
|
|
7
|
+
username: string;
|
|
8
|
+
}
|
|
9
|
+
export declare function castleIdentityFromEmail(email: string): CastleGitIdentity | null;
|
|
10
|
+
export declare function castleUsernameFromEmail(email: string): string | null;
|
|
11
|
+
/** The collaborator username for an incoming commit, or null for this user and laptop commits. */
|
|
12
|
+
export declare function collaboratorUsername(authorEmail: string, ownEmail: string | null): string | null;
|
|
13
|
+
/** "a", "a and b", "a, b, and c". */
|
|
14
|
+
export declare function joinedNames(names: string[]): string;
|
|
15
|
+
/** The human-readable source of commits fetched from castle/main. */
|
|
16
|
+
export declare function otherSideLabel(authors: GitCommitAuthor[], ownEmail: string | null): string;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
const CASTLE_NOREPLY = /^([^+@]+)\+([^@]+)@users\.noreply\.castle\.xyz$/i;
|
|
2
|
+
export function castleIdentityFromEmail(email) {
|
|
3
|
+
const match = CASTLE_NOREPLY.exec(email.trim());
|
|
4
|
+
return match?.[1] && match[2] ? { userId: match[1], username: match[2] } : null;
|
|
5
|
+
}
|
|
6
|
+
export function castleUsernameFromEmail(email) {
|
|
7
|
+
return castleIdentityFromEmail(email)?.username ?? null;
|
|
8
|
+
}
|
|
9
|
+
/** The collaborator username for an incoming commit, or null for this user and laptop commits. */
|
|
10
|
+
export function collaboratorUsername(authorEmail, ownEmail) {
|
|
11
|
+
const author = castleIdentityFromEmail(authorEmail);
|
|
12
|
+
const own = ownEmail ? castleIdentityFromEmail(ownEmail) : null;
|
|
13
|
+
if (!author || !own || author.userId.toLowerCase() === own.userId.toLowerCase())
|
|
14
|
+
return null;
|
|
15
|
+
return author.username;
|
|
16
|
+
}
|
|
17
|
+
/** "a", "a and b", "a, b, and c". */
|
|
18
|
+
export function joinedNames(names) {
|
|
19
|
+
if (names.length <= 1)
|
|
20
|
+
return names[0] ?? '';
|
|
21
|
+
if (names.length === 2)
|
|
22
|
+
return `${names[0]} and ${names[1]}`;
|
|
23
|
+
return `${names.slice(0, -1).join(', ')}, and ${names[names.length - 1]}`;
|
|
24
|
+
}
|
|
25
|
+
/** The human-readable source of commits fetched from castle/main. */
|
|
26
|
+
export function otherSideLabel(authors, ownEmail) {
|
|
27
|
+
const own = ownEmail ? castleIdentityFromEmail(ownEmail) : null;
|
|
28
|
+
if (!own)
|
|
29
|
+
return 'another computer';
|
|
30
|
+
const others = new Set();
|
|
31
|
+
for (const author of authors) {
|
|
32
|
+
const identity = castleIdentityFromEmail(author.email);
|
|
33
|
+
if (!identity)
|
|
34
|
+
return 'another computer';
|
|
35
|
+
if (identity.userId.toLowerCase() !== own.userId.toLowerCase())
|
|
36
|
+
others.add(identity.username);
|
|
37
|
+
}
|
|
38
|
+
if (others.size === 0)
|
|
39
|
+
return 'your laptop';
|
|
40
|
+
const names = [...others];
|
|
41
|
+
return `${joinedNames(names)} (${names.length === 1 ? 'a collaborator' : 'collaborators'} on this deck)`;
|
|
42
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export declare const GIT_INCOMING_FILE: string;
|
|
2
|
+
export interface GitIncomingCommit {
|
|
3
|
+
sha: string;
|
|
4
|
+
author: string;
|
|
5
|
+
subject: string;
|
|
6
|
+
files: string[];
|
|
7
|
+
at: string;
|
|
8
|
+
}
|
|
9
|
+
export declare function appendGitIncoming(deckDir: string, commits: GitIncomingCommit[]): void;
|
|
10
|
+
export declare function readGitIncoming(deckDir: string): GitIncomingCommit[];
|
|
11
|
+
export declare function formatGitIncomingNote(commits: GitIncomingCommit[]): string | null;
|
|
12
|
+
export declare function readGitIncomingNote(deckDir: string): {
|
|
13
|
+
note: string | null;
|
|
14
|
+
shas: string[];
|
|
15
|
+
};
|
|
16
|
+
/** Removes only commits covered by a completed turn, preserving anything appended while it ran. */
|
|
17
|
+
export declare function removeGitIncoming(deckDir: string, shas: string[]): void;
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import * as fs from 'fs';
|
|
2
|
+
import * as path from 'path';
|
|
3
|
+
import { joinedNames } from './gitCollaborators.js';
|
|
4
|
+
export const GIT_INCOMING_FILE = path.join('.castle', 'agent', 'git-incoming.json');
|
|
5
|
+
const LOCK_FILE = path.join('.castle', 'agent', 'git-incoming.lock');
|
|
6
|
+
const MAX_COMMITS = 50;
|
|
7
|
+
const LOCK_STALE_MS = 30_000;
|
|
8
|
+
function validCommit(value) {
|
|
9
|
+
if (!value || typeof value !== 'object')
|
|
10
|
+
return false;
|
|
11
|
+
const item = value;
|
|
12
|
+
return (typeof item.sha === 'string' &&
|
|
13
|
+
typeof item.author === 'string' &&
|
|
14
|
+
typeof item.subject === 'string' &&
|
|
15
|
+
Array.isArray(item.files) &&
|
|
16
|
+
item.files.every((file) => typeof file === 'string') &&
|
|
17
|
+
typeof item.at === 'string');
|
|
18
|
+
}
|
|
19
|
+
function readFile(file) {
|
|
20
|
+
try {
|
|
21
|
+
const parsed = JSON.parse(fs.readFileSync(file, 'utf-8'));
|
|
22
|
+
return Array.isArray(parsed) ? parsed.filter(validCommit) : [];
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return [];
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
function withStoreLock(deckDir, fallback, fn) {
|
|
29
|
+
const lock = path.join(deckDir, LOCK_FILE);
|
|
30
|
+
fs.mkdirSync(path.dirname(lock), { recursive: true });
|
|
31
|
+
for (let attempt = 0; attempt < 50; attempt += 1) {
|
|
32
|
+
try {
|
|
33
|
+
const fd = fs.openSync(lock, 'wx');
|
|
34
|
+
try {
|
|
35
|
+
return fn();
|
|
36
|
+
}
|
|
37
|
+
finally {
|
|
38
|
+
fs.closeSync(fd);
|
|
39
|
+
fs.rmSync(lock, { force: true });
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
catch (err) {
|
|
43
|
+
if (err.code !== 'EEXIST')
|
|
44
|
+
throw err;
|
|
45
|
+
try {
|
|
46
|
+
if (Date.now() - fs.statSync(lock).mtimeMs > LOCK_STALE_MS) {
|
|
47
|
+
fs.rmSync(lock, { force: true });
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return fallback;
|
|
58
|
+
}
|
|
59
|
+
function writeAtomic(file, commits) {
|
|
60
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
61
|
+
const temp = `${file}.${process.pid}.tmp`;
|
|
62
|
+
fs.writeFileSync(temp, JSON.stringify(commits, null, 2) + '\n');
|
|
63
|
+
fs.renameSync(temp, file);
|
|
64
|
+
}
|
|
65
|
+
export function appendGitIncoming(deckDir, commits) {
|
|
66
|
+
if (commits.length === 0)
|
|
67
|
+
return;
|
|
68
|
+
withStoreLock(deckDir, undefined, () => {
|
|
69
|
+
const file = path.join(deckDir, GIT_INCOMING_FILE);
|
|
70
|
+
const bySha = new Map(readFile(file).map((commit) => [commit.sha, commit]));
|
|
71
|
+
for (const commit of commits)
|
|
72
|
+
bySha.set(commit.sha, commit);
|
|
73
|
+
writeAtomic(file, [...bySha.values()].slice(-MAX_COMMITS));
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
export function readGitIncoming(deckDir) {
|
|
77
|
+
return withStoreLock(deckDir, [], () => readFile(path.join(deckDir, GIT_INCOMING_FILE)));
|
|
78
|
+
}
|
|
79
|
+
function namesFor(commits) {
|
|
80
|
+
const names = [...new Set(commits.map((commit) => commit.author).filter(Boolean))];
|
|
81
|
+
return names.length === 0 ? 'A collaborator' : joinedNames(names);
|
|
82
|
+
}
|
|
83
|
+
export function formatGitIncomingNote(commits) {
|
|
84
|
+
if (commits.length === 0)
|
|
85
|
+
return null;
|
|
86
|
+
const heading = `[Castle] Since your last turn, ${namesFor(commits)} landed these changes to this deck (already merged into the working tree):`;
|
|
87
|
+
const multipleAuthors = new Set(commits.map((commit) => commit.author)).size > 1;
|
|
88
|
+
const rows = commits.map((commit) => {
|
|
89
|
+
const shown = commit.files.slice(0, 6);
|
|
90
|
+
const files = shown.length > 0 ? `${shown.join(', ')}${commit.files.length > shown.length ? ', …' : ''}` : 'no files';
|
|
91
|
+
const author = multipleAuthors ? ` — ${commit.author}` : '';
|
|
92
|
+
return `- ${commit.sha.slice(0, 7)} ${commit.subject}${author} (${files})`;
|
|
93
|
+
});
|
|
94
|
+
return [heading, ...rows].join('\n');
|
|
95
|
+
}
|
|
96
|
+
export function readGitIncomingNote(deckDir) {
|
|
97
|
+
const commits = readGitIncoming(deckDir);
|
|
98
|
+
return { note: formatGitIncomingNote(commits), shas: commits.map((commit) => commit.sha) };
|
|
99
|
+
}
|
|
100
|
+
/** Removes only commits covered by a completed turn, preserving anything appended while it ran. */
|
|
101
|
+
export function removeGitIncoming(deckDir, shas) {
|
|
102
|
+
if (shas.length === 0)
|
|
103
|
+
return;
|
|
104
|
+
withStoreLock(deckDir, undefined, () => {
|
|
105
|
+
const file = path.join(deckDir, GIT_INCOMING_FILE);
|
|
106
|
+
const removed = new Set(shas);
|
|
107
|
+
const remaining = readFile(file).filter((commit) => !removed.has(commit.sha));
|
|
108
|
+
if (remaining.length > 0)
|
|
109
|
+
writeAtomic(file, remaining);
|
|
110
|
+
else
|
|
111
|
+
fs.rmSync(file, { force: true });
|
|
112
|
+
});
|
|
113
|
+
}
|
package/dist/gitRemote.js
CHANGED
|
@@ -485,7 +485,7 @@ function explainRemoteFailure(result, deckId, environment) {
|
|
|
485
485
|
if (/repository '[^']*' not found|error: 404/.test(why))
|
|
486
486
|
return noHistoryError(deckId, environment);
|
|
487
487
|
if (/error: 403/.test(why)) {
|
|
488
|
-
return new Error(`You don't have access to deck ${deckId}: only its owner can clone it.`);
|
|
488
|
+
return new Error(`You don't have access to deck ${deckId}: only its owner or a collaborator can clone it.`);
|
|
489
489
|
}
|
|
490
490
|
if (/error: 401|Authentication failed|could not read (Username|Password)/i.test(why)) {
|
|
491
491
|
return new Error('Castle did not accept your login. Run `castle-web login`, then retry.');
|
|
@@ -496,7 +496,7 @@ function noHistoryError(deckId, environment) {
|
|
|
496
496
|
const editor = environment === 'staging'
|
|
497
497
|
? `https://castle.xyz/create/${deckId}?sandbox=staging`
|
|
498
498
|
: `https://castle.xyz/create/${deckId}`;
|
|
499
|
-
return new Error(`Deck ${deckId} has no git history${environment === 'staging' ? ' on staging' : ''} yet (or doesn't exist).
|
|
499
|
+
return new Error(`Deck ${deckId} has no git history${environment === 'staging' ? ' on staging' : ''} yet (or doesn't exist). Its owner needs to open it in the cloud editor once with git on (${editor}), which starts its history; then clone again.`);
|
|
500
500
|
}
|
|
501
501
|
/** Clones a deck's Castle repo, with the remote named `castle` and the credential helper in the clone's config. */
|
|
502
502
|
export function gitClone(target, dirArg, opts, deps, cwd = process.cwd()) {
|
package/dist/importBrowse.js
CHANGED
|
@@ -18,7 +18,7 @@ import * as api from './api.js';
|
|
|
18
18
|
import * as config from './config.js';
|
|
19
19
|
import { runTar } from './save-deck.js';
|
|
20
20
|
import { readCastleJson } from './castleJson.js';
|
|
21
|
-
import { ImportError, addImportTo, importedDeckIds,
|
|
21
|
+
import { ImportError, addImportTo, importedDeckIds, resolveDeckRef as resolveImportDeckRef, } from './imports.js';
|
|
22
22
|
import { errorMessage, readRequestBody, sendJson } from './httpJson.js';
|
|
23
23
|
export const IMPORT_API_PREFIX = '/__castle/import/';
|
|
24
24
|
// Rows per list, and how many decks we are willing to ask the source question
|
|
@@ -136,13 +136,10 @@ export async function listImportable(deckDir, tab) {
|
|
|
136
136
|
// NOT hide a deck with no source -- naming a specific deck and getting nothing
|
|
137
137
|
// back says less than naming it and being told it was never saved.
|
|
138
138
|
export async function resolveDeckRef(deckDir, ref) {
|
|
139
|
-
const deckId =
|
|
139
|
+
const deckId = await resolveImportDeckRef(ref);
|
|
140
140
|
if (!deckId) {
|
|
141
141
|
throw new ImportError('bad-deck-ref', `Not a deck id or a castle deck link: ${ref}`);
|
|
142
142
|
}
|
|
143
|
-
if (readCastleJson(deckDir)?.deckId === deckId) {
|
|
144
|
-
throw new ImportError('self-import', `That is this deck -- a deck can't import itself.`);
|
|
145
|
-
}
|
|
146
143
|
const [rows, source] = await Promise.all([
|
|
147
144
|
api.deckRows([deckId]),
|
|
148
145
|
api.webDeckSource(deckId).catch(() => null),
|
|
@@ -150,7 +147,11 @@ export async function resolveDeckRef(deckDir, ref) {
|
|
|
150
147
|
const row = rows[0];
|
|
151
148
|
if (!row)
|
|
152
149
|
throw new ImportError('bad-deck-ref', `No deck ${deckId} on the server.`);
|
|
153
|
-
|
|
150
|
+
if (readCastleJson(deckDir)?.deckId === row.deckId) {
|
|
151
|
+
throw new ImportError('self-import', `That is this deck -- a deck can't import itself.`);
|
|
152
|
+
}
|
|
153
|
+
const canonicalSource = source ?? (row.deckId !== deckId ? await api.webDeckSource(row.deckId).catch(() => null) : null);
|
|
154
|
+
return stampImported(deckDir, [toCandidate(row, canonicalSource !== null)])[0];
|
|
154
155
|
}
|
|
155
156
|
// How many files a deck's source holds. Not on any list query, so it is counted
|
|
156
157
|
// from the archive itself -- which means downloading it, which is why the picker
|
package/dist/imports.d.ts
CHANGED
|
@@ -6,12 +6,13 @@ export interface ImportVersion {
|
|
|
6
6
|
}
|
|
7
7
|
export declare function writeImportVersion(importDir: string, value: ImportVersion): void;
|
|
8
8
|
export declare function readImportVersion(deckDir: string, alias: string): ImportVersion | null;
|
|
9
|
-
export type ImportErrorCode = 'no-deck-ref' | 'bad-deck-ref' | 'no-such-dir' | 'self-import' | 'no-source' | 'bad-alias' | 'already-imported';
|
|
9
|
+
export type ImportErrorCode = 'no-deck-ref' | 'bad-deck-ref' | 'not-a-deck-link' | 'link-unreachable' | 'no-such-dir' | 'self-import' | 'classic-deck' | 'no-source' | 'bad-alias' | 'already-imported';
|
|
10
10
|
export declare class ImportError extends Error {
|
|
11
11
|
code: ImportErrorCode;
|
|
12
12
|
constructor(code: ImportErrorCode, message: string);
|
|
13
13
|
}
|
|
14
14
|
export declare function parseDeckRef(raw: string): string | null;
|
|
15
|
+
export declare function resolveDeckRef(raw: string): Promise<string | null>;
|
|
15
16
|
export declare function lockImportTree(dir: string): void;
|
|
16
17
|
export declare function syncImportDependencies(deckDir: string): string[];
|
|
17
18
|
export declare function restoreMissingImports(deckDir: string): Promise<string[]>;
|