castle-web-cli 0.4.227 → 0.4.229
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 +9 -3
- package/dist/agent-prompts.js +140 -48
- package/dist/agent.js +127 -14
- package/dist/api.d.ts +37 -0
- package/dist/api.js +29 -0
- package/dist/castle-host/host.d.ts +6 -0
- package/dist/castle-host/host.js +42 -3
- package/dist/castleJson.d.ts +15 -0
- package/dist/castleJson.js +136 -3
- package/dist/cloudGit.d.ts +27 -1
- package/dist/cloudGit.js +359 -24
- package/dist/cloudGitServe.js +9 -5
- 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/imports.js +4 -2
- package/dist/index.js +5 -0
- package/dist/init.js +1 -1
- package/dist/native/playtest-browser.js +13 -1
- package/dist/platformDoc.js +1 -1
- package/dist/save-deck.js +3 -0
- package/dist/serve.js +17 -0
- package/dist/shell/assets/index-Cf61cNfT.css +1 -0
- package/dist/shell/assets/{index-D006JHww.js → index-D2tWM896.js} +71 -71
- package/dist/shell/index.html +2 -2
- package/dist/sourceLineage.d.ts +42 -0
- package/dist/sourceLineage.js +380 -0
- package/dist/webSourceSync.d.ts +9 -0
- package/dist/webSourceSync.js +24 -9
- package/kits/base/castle.json +1 -1
- package/kits/base/sdk/README.md +81 -0
- package/kits/base/sdk/castle.d.ts +1 -1
- package/kits/base/sdk/commands.d.ts +6 -0
- package/kits/base/sdk/multiplayer.d.ts +44 -6
- package/kits/base/sdk/multiplayer.js +62 -1
- package/kits/base/sdk/server/platformHandle.d.ts +9 -1
- package/kits/base/sdk/server/wrapper.d.ts +111 -4
- package/kits/base/sdk/server/wrapper.js +650 -24
- package/package.json +10 -2
- package/dist/shell/assets/index-BxDYy_-C.css +0 -1
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.
|
|
@@ -36,6 +38,11 @@ export const EXIT_CONFLICT = 3;
|
|
|
36
38
|
* the snapshot bundle could bring them back. Nothing was changed; the next command retries.
|
|
37
39
|
*/
|
|
38
40
|
export const EXIT_HISTORY_UNAVAILABLE = 4;
|
|
41
|
+
/**
|
|
42
|
+
* A first attach outran the caller's deadline and carries on in the background (see
|
|
43
|
+
* attachThroughChild). Not attached yet; the deck works without git until it is.
|
|
44
|
+
*/
|
|
45
|
+
export const EXIT_ATTACH_CONTINUING = 5;
|
|
39
46
|
export const HISTORY_UNAVAILABLE_CODE = 'GIT_HISTORY_UNAVAILABLE';
|
|
40
47
|
export class CloudGitError extends Error {
|
|
41
48
|
exitCode;
|
|
@@ -47,7 +54,8 @@ export class CloudGitError extends Error {
|
|
|
47
54
|
}
|
|
48
55
|
// Castle's excludes, in .git/info/exclude rather than a .gitignore, so they apply whatever
|
|
49
56
|
// the deck's own .gitignore says and never show up as a change to the deck.
|
|
50
|
-
export const
|
|
57
|
+
export const CLOUD_LOCKFILES = ['package-lock.json', 'pnpm-lock.yaml', 'yarn.lock', 'bun.lock', 'bun.lockb'];
|
|
58
|
+
export const CLOUD_EXCLUDES = ['node_modules/', 'dist/', '/imports/', '.castle/', '.vite/', ...CLOUD_LOCKFILES];
|
|
51
59
|
// More loose objects than this and a commit packs the repo. Draft checkpoints no longer carry
|
|
52
60
|
// `.git/objects` (history is rebuilt from the remote, the S3 mirror and the snapshot bundle on
|
|
53
61
|
// a cold resume), but a pile of loose objects still slows every git command and the bundle.
|
|
@@ -828,20 +836,21 @@ export function conflictInstruction(summary) {
|
|
|
828
836
|
const marked = summary.files.filter((f) => f.resolution === 'markers' || f.resolution === 'manual').map((f) => f.path);
|
|
829
837
|
const taken = summary.files.filter((f) => f.resolution === 'took-laptop' || f.resolution === 'laptop-deleted');
|
|
830
838
|
const head = summary.head.slice(0, 10);
|
|
839
|
+
const otherSide = summary.otherSide ?? 'another computer';
|
|
831
840
|
const parts = [
|
|
832
|
-
|
|
841
|
+
`[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
842
|
'Files with conflict markers (<<<<<<< / ||||||| / ======= / >>>>>>>) to resolve:',
|
|
834
843
|
list(marked),
|
|
835
844
|
];
|
|
836
845
|
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).
|
|
846
|
+
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
847
|
}
|
|
839
|
-
parts.push(
|
|
848
|
+
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
849
|
return parts.join('\n');
|
|
841
850
|
}
|
|
842
851
|
// A conflicted merge: take the other computer's side where git left no markers, record the
|
|
843
852
|
// rest in .git/castle-merge.json, and write the marker the serve turns into an agent turn.
|
|
844
|
-
function recordConflict(ctx) {
|
|
853
|
+
function recordConflict(ctx, otherSide) {
|
|
845
854
|
const head = revParse(ctx, 'HEAD') ?? '';
|
|
846
855
|
const mergeHead = revParse(ctx, 'MERGE_HEAD') ?? '';
|
|
847
856
|
const files = [];
|
|
@@ -854,10 +863,18 @@ function recordConflict(ctx) {
|
|
|
854
863
|
const theirs = commitSubjects(ctx, base ? `${base}..MERGE_HEAD` : 'MERGE_HEAD');
|
|
855
864
|
const ours = commitSubjects(ctx, base ? `${base}..HEAD` : 'HEAD');
|
|
856
865
|
const at = new Date(ctx.deps.now()).toISOString();
|
|
857
|
-
const instruction = conflictInstruction({ files, theirs, ours, head });
|
|
858
|
-
const state = { at, head, mergeHead, files, instruction };
|
|
866
|
+
const instruction = conflictInstruction({ files, theirs, ours, head, otherSide });
|
|
867
|
+
const state = { at, head, mergeHead, files, instruction, otherSide };
|
|
859
868
|
writeJsonAtomic(mergeStatePath(ctx.dir), state);
|
|
860
|
-
const report = {
|
|
869
|
+
const report = {
|
|
870
|
+
at,
|
|
871
|
+
files: files.map((f) => f.path),
|
|
872
|
+
theirs,
|
|
873
|
+
ours,
|
|
874
|
+
instruction,
|
|
875
|
+
otherSide,
|
|
876
|
+
notice: `Changes from ${otherSide} conflicted with this deck; the agent is resolving them.`,
|
|
877
|
+
};
|
|
861
878
|
writeJsonAtomic(path.join(ctx.dir, CONFLICT_MARKER_FILE), report);
|
|
862
879
|
return state;
|
|
863
880
|
}
|
|
@@ -952,6 +969,16 @@ export const REHYDRATE_STATE_FILE = path.join('.git', 'castle-rehydrate-state.js
|
|
|
952
969
|
export const REHYDRATE_LOG_FILE = path.join('.castle', 'agent', 'git-rehydrate.log');
|
|
953
970
|
/** `off` stops commands from starting a background rehydrate (tests). */
|
|
954
971
|
export const BACKGROUND_REHYDRATE_ENV = 'CASTLE_GIT_BACKGROUND_REHYDRATE';
|
|
972
|
+
/** A file each rehydrate appends one JSON outcome line to. The sandbox image points it at the
|
|
973
|
+
* container's own stdout (/proc/1/fd/1), which the host ships to Loki; the log file above does
|
|
974
|
+
* not leave the container. Unset: no event. */
|
|
975
|
+
export const CONTAINER_EVENT_LOG_ENV = 'CASTLE_CONTAINER_EVENT_LOG';
|
|
976
|
+
/** Held by the child a first attach runs in, for its whole run (see attachThroughChild). */
|
|
977
|
+
export const ATTACH_LOCK_FILE = path.join('.git', 'castle-attach-lock');
|
|
978
|
+
/** Where that child writes its output. */
|
|
979
|
+
export const ATTACH_LOG_FILE = path.join('.castle', 'agent', 'git-attach.log');
|
|
980
|
+
/** `1` in that child: it attaches in its own process, bound by no caller's deadline. */
|
|
981
|
+
export const BACKGROUND_ATTACH_ENV = 'CASTLE_GIT_BACKGROUND_ATTACH';
|
|
955
982
|
// The host's capture refuses any file over 32 MiB and fails the whole checkpoint with it. The
|
|
956
983
|
// snapshot and one set-aside lost snapshot stay under 48 MiB together.
|
|
957
984
|
export const SNAPSHOT_CAP_BYTES = 24 * 1024 * 1024;
|
|
@@ -1943,6 +1970,7 @@ function dropBrokenRefs(ctx) {
|
|
|
1943
1970
|
// Under the deck lock, after rehydrateObjects: give up lost local commits only when every
|
|
1944
1971
|
// source answered cleanly, settle castle/main and the other refs, check the history is whole,
|
|
1945
1972
|
// and re-hash staged blobs. Throws GIT_HISTORY_UNAVAILABLE (nothing changed) otherwise.
|
|
1973
|
+
// True when it gave up local commits nobody had (recoverLostHistory).
|
|
1946
1974
|
async function finishRehydrate(ctx, result) {
|
|
1947
1975
|
const tried = () => `Tried: ${result.notes.join('; ') || 'nothing could be tried'}.`;
|
|
1948
1976
|
const branches = historyMissing(ctx).filter((tip) => isBranchTip(tip.name));
|
|
@@ -1965,6 +1993,7 @@ async function finishRehydrate(ctx, result) {
|
|
|
1965
1993
|
}
|
|
1966
1994
|
await recoverLostHistory(ctx, branches, result);
|
|
1967
1995
|
}
|
|
1996
|
+
const lost = branches.length > 0;
|
|
1968
1997
|
// castle/main is where the remote was last seen: kept while its commit is here (the next
|
|
1969
1998
|
// sync fetches), else what was just fetched, else the mirror's main.
|
|
1970
1999
|
const remote = refValue(ctx, REMOTE_MAIN);
|
|
@@ -1989,6 +2018,7 @@ async function finishRehydrate(ctx, result) {
|
|
|
1989
2018
|
refreshSnapshot(ctx, false);
|
|
1990
2019
|
ctx.deps.log(`Rebuilt this deck's git history from ${result.used.join(', ') || 'what was already here'}` +
|
|
1991
2020
|
(reindexed.length ? `; re-hashed ${reindexed.length} staged file(s) from disk.` : '.'));
|
|
2021
|
+
return lost;
|
|
1992
2022
|
}
|
|
1993
2023
|
// The whole rehydrate, under REHYDRATE_LOCK_FILE: objects first, without the deck lock, then
|
|
1994
2024
|
// the deck's refs under it. Any failure is recorded for the backoff and surfaces as
|
|
@@ -2008,13 +2038,13 @@ async function runRehydrate(ctx) {
|
|
|
2008
2038
|
}
|
|
2009
2039
|
if (historyMissing(ctx).length === 0) {
|
|
2010
2040
|
fs.rmSync(path.join(ctx.dir, REHYDRATE_STATE_FILE), { force: true });
|
|
2011
|
-
return 'complete';
|
|
2041
|
+
return { outcome: 'complete', historyLost: false, used: [] };
|
|
2012
2042
|
}
|
|
2013
2043
|
const budgetEnd = ctx.deadline ?? ctx.deps.now() + REHYDRATE_BUDGET_MS;
|
|
2014
2044
|
const result = await rehydrateObjects(ctx, budgetEnd);
|
|
2015
|
-
await withDeckLock(ctx, () => finishRehydrate(ctx, result));
|
|
2045
|
+
const historyLost = await withDeckLock(ctx, () => finishRehydrate(ctx, result));
|
|
2016
2046
|
fs.rmSync(path.join(ctx.dir, REHYDRATE_STATE_FILE), { force: true });
|
|
2017
|
-
return 'rebuilt';
|
|
2047
|
+
return { outcome: 'rebuilt', historyLost, used: result.used };
|
|
2018
2048
|
}
|
|
2019
2049
|
catch (e) {
|
|
2020
2050
|
const error = e instanceof CloudGitError && e.exitCode === EXIT_HISTORY_UNAVAILABLE
|
|
@@ -2054,7 +2084,57 @@ export async function cloudRehydrate(dir, deps) {
|
|
|
2054
2084
|
catch {
|
|
2055
2085
|
throw new CloudGitError(`${ctx.dir} has no git repo to rehydrate.`, EXIT_NOT_ENABLED);
|
|
2056
2086
|
}
|
|
2057
|
-
|
|
2087
|
+
const startedAt = ctx.deps.now();
|
|
2088
|
+
const emit = (fields) => emitContainerEvent(ctx.deps.env, {
|
|
2089
|
+
event: 'sandbox_git_rehydrate',
|
|
2090
|
+
// castle.json is the user's to edit: only a real deck id goes in.
|
|
2091
|
+
deck_id: /^[A-Za-z0-9_-]{1,64}$/.test(readDeckId(ctx.dir) ?? '') ? readDeckId(ctx.dir) : null,
|
|
2092
|
+
...fields,
|
|
2093
|
+
duration_ms: ctx.deps.now() - startedAt,
|
|
2094
|
+
});
|
|
2095
|
+
let run;
|
|
2096
|
+
try {
|
|
2097
|
+
run = await runRehydrate(ctx);
|
|
2098
|
+
}
|
|
2099
|
+
catch (e) {
|
|
2100
|
+
emit({ outcome: 'failed', error: errorText(e).slice(0, 500) });
|
|
2101
|
+
throw e;
|
|
2102
|
+
}
|
|
2103
|
+
emit({ outcome: run.historyLost ? 'history_lost' : run.outcome, used: run.used });
|
|
2104
|
+
return run.outcome;
|
|
2105
|
+
}
|
|
2106
|
+
// One JSON line to CONTAINER_EVENT_LOG_ENV's file, at most PIPE_BUF bytes so a pipe takes it
|
|
2107
|
+
// whole (an event that would not fit loses its error and sources). Opened non-blocking: a full
|
|
2108
|
+
// pipe drops the line (EAGAIN) rather than stalling the rehydrate. Best effort throughout.
|
|
2109
|
+
const CONTAINER_EVENT_MAX_BYTES = 4096;
|
|
2110
|
+
function emitContainerEvent(env, event) {
|
|
2111
|
+
const target = env[CONTAINER_EVENT_LOG_ENV];
|
|
2112
|
+
if (!target)
|
|
2113
|
+
return;
|
|
2114
|
+
let line = Buffer.from(`${JSON.stringify(event)}\n`);
|
|
2115
|
+
if (line.length > CONTAINER_EVENT_MAX_BYTES) {
|
|
2116
|
+
line = Buffer.from(`${JSON.stringify({ ...event, error: undefined, used: undefined, truncated: true })}\n`);
|
|
2117
|
+
if (line.length > CONTAINER_EVENT_MAX_BYTES)
|
|
2118
|
+
return;
|
|
2119
|
+
}
|
|
2120
|
+
let fd;
|
|
2121
|
+
try {
|
|
2122
|
+
fd = fs.openSync(target, fs.constants.O_WRONLY | fs.constants.O_APPEND | fs.constants.O_CREAT | fs.constants.O_NONBLOCK, 0o600);
|
|
2123
|
+
fs.writeSync(fd, line);
|
|
2124
|
+
}
|
|
2125
|
+
catch {
|
|
2126
|
+
/* best effort */
|
|
2127
|
+
}
|
|
2128
|
+
finally {
|
|
2129
|
+
if (fd !== undefined) {
|
|
2130
|
+
try {
|
|
2131
|
+
fs.closeSync(fd);
|
|
2132
|
+
}
|
|
2133
|
+
catch {
|
|
2134
|
+
/* best effort */
|
|
2135
|
+
}
|
|
2136
|
+
}
|
|
2137
|
+
}
|
|
2058
2138
|
}
|
|
2059
2139
|
// Concludes the merge in progress as one whole commit -- only when no conflicted file still
|
|
2060
2140
|
// has markers. Git refuses a partial commit mid-merge, so named paths are not used.
|
|
@@ -2141,17 +2221,18 @@ async function commitLocked(ctx, opts) {
|
|
|
2141
2221
|
if (recovered && !recovered.committed)
|
|
2142
2222
|
markRecoveredCommitted(ctx);
|
|
2143
2223
|
};
|
|
2224
|
+
topUpCloudExcludes(ctx);
|
|
2144
2225
|
if (opts.paths && opts.paths.length > 0) {
|
|
2145
2226
|
const specs = commitPathspecs(ctx, opts.paths);
|
|
2146
2227
|
if (specs.length === 0)
|
|
2147
2228
|
return { sha: null };
|
|
2148
|
-
must(ctx, ['add', '-A', '--', ...specs]);
|
|
2229
|
+
must(ctx, [...BIG_FILE_ARGS, 'add', '-A', '--', ...specs]);
|
|
2149
2230
|
if (ok(ctx, ['diff', '--cached', '--quiet', '--', ...specs]))
|
|
2150
2231
|
return { sha: null };
|
|
2151
2232
|
await commit([...commitMessageArgs(opts, reason), '--', ...specs]);
|
|
2152
2233
|
}
|
|
2153
2234
|
else {
|
|
2154
|
-
must(ctx, ['add', '-A']);
|
|
2235
|
+
must(ctx, [...BIG_FILE_ARGS, 'add', '-A']);
|
|
2155
2236
|
if (ok(ctx, ['diff', '--cached', '--quiet']))
|
|
2156
2237
|
return { sha: null };
|
|
2157
2238
|
await commit(commitMessageArgs(opts, reason));
|
|
@@ -2168,8 +2249,13 @@ function fetchRemote(ctx) {
|
|
|
2168
2249
|
// One pack per fetch: all or nothing, even when a fetch is killed partway.
|
|
2169
2250
|
const args = ['fetch', '--quiet', '--prune', '--no-tags', GIT_REMOTE_NAME];
|
|
2170
2251
|
const fetched = run(ctx, ['-c', 'fetch.unpackLimit=1', '-c', 'transfer.unpackLimit=1', ...args], { timeoutMs: NETWORK_TIMEOUT_MS });
|
|
2171
|
-
if (fetched.status !== 0)
|
|
2252
|
+
if (fetched.status !== 0) {
|
|
2253
|
+
const detail = `${fetched.stderr}\n${fetched.stdout}\n${fetched.error?.message ?? ''}`;
|
|
2254
|
+
if (/repo_missing/i.test(detail)) {
|
|
2255
|
+
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.");
|
|
2256
|
+
}
|
|
2172
2257
|
throw new CloudGitError(describeFailure(args, fetched));
|
|
2258
|
+
}
|
|
2173
2259
|
return revParse(ctx, REMOTE_MAIN);
|
|
2174
2260
|
}
|
|
2175
2261
|
// Bring castle/main into local main. Local work is already committed by the caller.
|
|
@@ -2191,6 +2277,46 @@ async function commitRecoveredRoot(ctx) {
|
|
|
2191
2277
|
return;
|
|
2192
2278
|
await commitLocked(ctx, { reason: 'sync' });
|
|
2193
2279
|
}
|
|
2280
|
+
// The newest MAX_INCOMING_COMMITS only: a long-diverged remote (a first sync after a long
|
|
2281
|
+
// absence) is described, not enumerated, and each commit costs two git calls here.
|
|
2282
|
+
const MAX_INCOMING_COMMITS = 50;
|
|
2283
|
+
function incomingRemoteCommits(ctx, remote, head) {
|
|
2284
|
+
const shas = lines(must(ctx, ['rev-list', '--reverse', '-n', String(MAX_INCOMING_COMMITS), remote, '--not', head]));
|
|
2285
|
+
return shas.map((sha) => {
|
|
2286
|
+
const [fullSha, name, email, at, ...subjectParts] = must(ctx, [
|
|
2287
|
+
'show',
|
|
2288
|
+
'-s',
|
|
2289
|
+
'--format=%H%x1f%an%x1f%ae%x1f%aI%x1f%s',
|
|
2290
|
+
sha,
|
|
2291
|
+
]).trim().split('\x1f');
|
|
2292
|
+
const files = must(ctx, ['diff-tree', '--no-commit-id', '--name-only', '-r', '-z', sha])
|
|
2293
|
+
.split('\0')
|
|
2294
|
+
.filter(Boolean);
|
|
2295
|
+
return {
|
|
2296
|
+
sha: fullSha || sha,
|
|
2297
|
+
name: name || 'Castle user',
|
|
2298
|
+
email: email || '',
|
|
2299
|
+
author: castleUsernameFromEmail(email || '') ?? (name?.trim() || 'A collaborator'),
|
|
2300
|
+
subject: subjectParts.join('\x1f'),
|
|
2301
|
+
files,
|
|
2302
|
+
at: at || new Date(ctx.deps.now()).toISOString(),
|
|
2303
|
+
};
|
|
2304
|
+
});
|
|
2305
|
+
}
|
|
2306
|
+
function noteCollaboratorCommits(ctx, commits, ownEmail) {
|
|
2307
|
+
const others = commits.flatMap((commit) => {
|
|
2308
|
+
const author = collaboratorUsername(commit.email, ownEmail);
|
|
2309
|
+
return author ? [{ ...commit, author }] : [];
|
|
2310
|
+
});
|
|
2311
|
+
if (others.length === 0)
|
|
2312
|
+
return;
|
|
2313
|
+
try {
|
|
2314
|
+
appendGitIncoming(ctx.dir, others.map(({ sha, author, subject, files, at }) => ({ sha, author, subject, files, at })));
|
|
2315
|
+
}
|
|
2316
|
+
catch (err) {
|
|
2317
|
+
ctx.deps.warn(`Could not note incoming collaborator commits: ${err instanceof Error ? err.message : String(err)}`);
|
|
2318
|
+
}
|
|
2319
|
+
}
|
|
2194
2320
|
async function integrate(ctx, remote) {
|
|
2195
2321
|
await commitRecoveredRoot(ctx);
|
|
2196
2322
|
const head = revParse(ctx, 'HEAD');
|
|
@@ -2203,10 +2329,15 @@ async function integrate(ctx, remote) {
|
|
|
2203
2329
|
}
|
|
2204
2330
|
if (head === remote || ok(ctx, ['merge-base', '--is-ancestor', remote, head]))
|
|
2205
2331
|
return 'none';
|
|
2332
|
+
await identityArgs(ctx);
|
|
2333
|
+
const ownEmail = localConfig(ctx, 'user.email');
|
|
2334
|
+
const incoming = incomingRemoteCommits(ctx, remote, head);
|
|
2335
|
+
const otherSide = otherSideLabel(incoming, ownEmail);
|
|
2206
2336
|
if (deferIfBusy(ctx))
|
|
2207
2337
|
return 'deferred';
|
|
2208
2338
|
if (ok(ctx, ['merge-base', '--is-ancestor', head, remote])) {
|
|
2209
2339
|
must(ctx, ['merge', '--ff-only', '--quiet', REMOTE_MAIN]);
|
|
2340
|
+
noteCollaboratorCommits(ctx, incoming, ownEmail);
|
|
2210
2341
|
return 'fast-forward';
|
|
2211
2342
|
}
|
|
2212
2343
|
const identity = await identityArgs(ctx);
|
|
@@ -2224,13 +2355,15 @@ async function integrate(ctx, remote) {
|
|
|
2224
2355
|
'-X',
|
|
2225
2356
|
'diff-algorithm=histogram',
|
|
2226
2357
|
'-m',
|
|
2227
|
-
`Merge changes from
|
|
2358
|
+
`Merge changes from ${otherSide}`,
|
|
2228
2359
|
REMOTE_MAIN,
|
|
2229
2360
|
]);
|
|
2230
|
-
if (merge.status === 0)
|
|
2361
|
+
if (merge.status === 0) {
|
|
2362
|
+
noteCollaboratorCommits(ctx, incoming, ownEmail);
|
|
2231
2363
|
return 'merged';
|
|
2364
|
+
}
|
|
2232
2365
|
if (mergeInProgress(ctx.dir) && unmergedStages(ctx).size > 0) {
|
|
2233
|
-
const state = recordConflict(ctx);
|
|
2366
|
+
const state = recordConflict(ctx, otherSide);
|
|
2234
2367
|
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
2368
|
return 'conflict';
|
|
2236
2369
|
}
|
|
@@ -2243,10 +2376,17 @@ function isRejectedPush(result) {
|
|
|
2243
2376
|
return /\[rejected\]|non-fast-forward|fetch first|failed to update ref|incorrect old value|cannot lock ref|stale info/i.test(result.stderr);
|
|
2244
2377
|
}
|
|
2245
2378
|
const PUSH_ARGS = ['push', '--quiet', GIT_REMOTE_NAME, `${MAIN}:refs/heads/${MAIN}`];
|
|
2379
|
+
// For a commit's add and a push only: blobs over a megabyte go straight into a pack as they are,
|
|
2380
|
+
// and a push sends them without a delta search against the deck's other files. A deck's big
|
|
2381
|
+
// files are images and audio that never delta, and that search was most of a first push (a
|
|
2382
|
+
// 144 MB deck took 35 s in a sandbox; locally its push went from 9 s to 1.4 s). Not repo config:
|
|
2383
|
+
// snapshot bundles and repacks still delta, so a big file's many revisions stay small in the
|
|
2384
|
+
// capped snapshot, and the agent's own git diff still reads such a file as text.
|
|
2385
|
+
const BIG_FILE_ARGS = ['-c', 'core.bigFileThreshold=1m'];
|
|
2246
2386
|
// Main only, never forced. On success castle/main is moved without another fetch, so the next
|
|
2247
2387
|
// sync's comparisons hold.
|
|
2248
2388
|
function pushMain(ctx, local) {
|
|
2249
|
-
const push = run(ctx, PUSH_ARGS, { timeoutMs: NETWORK_TIMEOUT_MS });
|
|
2389
|
+
const push = run(ctx, [...BIG_FILE_ARGS, ...PUSH_ARGS], { timeoutMs: NETWORK_TIMEOUT_MS });
|
|
2250
2390
|
if (push.status === 0) {
|
|
2251
2391
|
run(ctx, ['update-ref', REMOTE_MAIN, local]);
|
|
2252
2392
|
markIntegrated(ctx, local);
|
|
@@ -2275,12 +2415,27 @@ function pushOnly(ctx) {
|
|
|
2275
2415
|
ctx.deps.warn('The Castle remote has changes this sandbox does not have yet; they are merged once the deck is idle.');
|
|
2276
2416
|
return { merge: 'deferred', pushed: false };
|
|
2277
2417
|
}
|
|
2418
|
+
// The child's seed push: never a merge, so a remote that moved meanwhile fails it (and the seed
|
|
2419
|
+
// is undone) rather than have the working tree written under the user.
|
|
2420
|
+
async function seedPushOnly(ctx) {
|
|
2421
|
+
requireMainBranch(ctx);
|
|
2422
|
+
if (mergeWaiting(ctx.dir))
|
|
2423
|
+
throw mergeWaitingError(ctx);
|
|
2424
|
+
await commitLocked(ctx, { reason: 'sync' });
|
|
2425
|
+
const local = revParse(ctx, 'HEAD');
|
|
2426
|
+
if (!local)
|
|
2427
|
+
return { merge: 'none', pushed: false };
|
|
2428
|
+
const push = pushMain(ctx, local);
|
|
2429
|
+
if (push.status !== 0)
|
|
2430
|
+
throw new CloudGitError(describeFailure(PUSH_ARGS, push));
|
|
2431
|
+
return { merge: 'seeded', pushed: true };
|
|
2432
|
+
}
|
|
2278
2433
|
async function syncLocked(ctx, opts) {
|
|
2279
2434
|
requireMainBranch(ctx);
|
|
2280
|
-
if (opts.commitFirst)
|
|
2281
|
-
await commitLocked(ctx, { reason: 'sync' });
|
|
2282
2435
|
if (mergeWaiting(ctx.dir))
|
|
2283
2436
|
throw mergeWaitingError(ctx);
|
|
2437
|
+
if (opts.commitFirst)
|
|
2438
|
+
await commitLocked(ctx, { reason: 'sync' });
|
|
2284
2439
|
if (opts.mode === 'push-only')
|
|
2285
2440
|
return pushOnly(ctx);
|
|
2286
2441
|
let merge = 'none';
|
|
@@ -2763,6 +2918,11 @@ function forgetOtherDecksRemote(ctx, deckId) {
|
|
|
2763
2918
|
const other = CASTLE_REMOTE_RE.exec(current)?.[2];
|
|
2764
2919
|
if (!other || other === deckId)
|
|
2765
2920
|
return null;
|
|
2921
|
+
// The other deck's snapshot key would let a checkpoint leave out objects this deck's remote
|
|
2922
|
+
// does not have yet (its first push can run in the background). Gone first, before the other
|
|
2923
|
+
// remote is: from here on a checkpoint keeps the objects until this deck has a snapshot of its own.
|
|
2924
|
+
for (const rel of [SNAPSHOT_KEY_FILE, SNAPSHOT_BUNDLE_FILE])
|
|
2925
|
+
fs.rmSync(path.join(ctx.dir, rel), { force: true });
|
|
2766
2926
|
must(ctx, ['remote', 'remove', GIT_REMOTE_NAME]);
|
|
2767
2927
|
for (const key of ['castle.cloud', 'castle.seed', 'user.name', 'user.email']) {
|
|
2768
2928
|
run(ctx, ['config', '--local', '--unset-all', key]);
|
|
@@ -2845,6 +3005,19 @@ export function writeCloudExcludes(dir) {
|
|
|
2845
3005
|
const prefix = existing && !existing.endsWith('\n') ? '\n' : '';
|
|
2846
3006
|
fs.appendFileSync(file, `${prefix}# Castle cloud sandbox\n${missing.join('\n')}\n`);
|
|
2847
3007
|
}
|
|
3008
|
+
function topUpCloudExcludes(ctx) {
|
|
3009
|
+
writeCloudExcludes(ctx.dir);
|
|
3010
|
+
const lockfiles = new Set(CLOUD_LOCKFILES);
|
|
3011
|
+
const tracked = must(ctx, ['ls-files', '-z'])
|
|
3012
|
+
.split('\0')
|
|
3013
|
+
.filter((file) => file && lockfiles.has(path.posix.basename(file)));
|
|
3014
|
+
if (tracked.length === 0)
|
|
3015
|
+
return;
|
|
3016
|
+
// Two sandboxes install dependencies independently, so tracked lockfiles conflict on nearly
|
|
3017
|
+
// every sync. package.json still carries the deck's dependencies; keep each lockfile in the
|
|
3018
|
+
// working copy while removing it from the shared cloud history once.
|
|
3019
|
+
must(ctx, ['rm', '--cached', '--quiet', '--ignore-unmatch', '--', ...tracked]);
|
|
3020
|
+
}
|
|
2848
3021
|
/** `castle-web git attach <dir> --remote <url>`. */
|
|
2849
3022
|
export async function cloudAttach(dir, remoteUrl, deps) {
|
|
2850
3023
|
requireSandbox(deps, 'git attach');
|
|
@@ -2884,13 +3057,33 @@ export async function cloudAttach(dir, remoteUrl, deps) {
|
|
|
2884
3057
|
must(ctx, ['config', '--local', 'core.createObject', 'rename']);
|
|
2885
3058
|
// The base in conflict markers is what lets the agent see what each side changed.
|
|
2886
3059
|
must(ctx, ['config', '--local', 'merge.conflictStyle', 'diff3']);
|
|
3060
|
+
if (deps.env[BACKGROUND_ATTACH_ENV] === '1')
|
|
3061
|
+
return attachInChild(ctx, repo);
|
|
3062
|
+
if (ctx.deadline === undefined || localConfig(ctx, 'castle.cloud') === 'true')
|
|
3063
|
+
return attachLocked(ctx, repo, 'inline');
|
|
3064
|
+
// An earlier open's child is still pushing: wait on it rather than queue on the deck lock.
|
|
3065
|
+
if ((await waitForAttachChild(ctx)) && localConfig(ctx, 'castle.cloud') === 'true') {
|
|
3066
|
+
return attachLocked(ctx, repo, 'inline');
|
|
3067
|
+
}
|
|
3068
|
+
try {
|
|
3069
|
+
return await attachLocked(ctx, repo, 'seed-elsewhere');
|
|
3070
|
+
}
|
|
3071
|
+
catch (e) {
|
|
3072
|
+
if (!(e instanceof SeedInChild))
|
|
3073
|
+
throw e;
|
|
3074
|
+
}
|
|
3075
|
+
return attachThroughChild(ctx, remoteUrl);
|
|
3076
|
+
}
|
|
3077
|
+
class SeedInChild extends Error {
|
|
3078
|
+
}
|
|
3079
|
+
async function attachLocked(ctx, repo, seedMode) {
|
|
2887
3080
|
return withDeckLock(ctx, async () => {
|
|
2888
3081
|
// A cold resume's repo has refs but no objects: the rehydrate runs in the background, and
|
|
2889
3082
|
// this attach stops at once (castle-www runs it in the background on open).
|
|
2890
3083
|
requireHistory(ctx, { leave: false });
|
|
2891
3084
|
try {
|
|
2892
3085
|
ensureMainBranch(ctx);
|
|
2893
|
-
const outcome = await firstSync(ctx, repo);
|
|
3086
|
+
const outcome = await firstSync(ctx, repo, seedMode);
|
|
2894
3087
|
// Marked attached only once the repo shares history with the remote: a deck whose
|
|
2895
3088
|
// first fetch failed must not start a local history of its own, which the next attach
|
|
2896
3089
|
// could not merge. The next open retries the whole attach.
|
|
@@ -2904,6 +3097,143 @@ export async function cloudAttach(dir, remoteUrl, deps) {
|
|
|
2904
3097
|
}
|
|
2905
3098
|
});
|
|
2906
3099
|
}
|
|
3100
|
+
// --- attach: a first seed, in a child of its own ----------------------------------------------
|
|
3101
|
+
//
|
|
3102
|
+
// A first attach onto an empty remote pushes the whole deck, and castle-www's open waits on it:
|
|
3103
|
+
// it is the one attach on an open's critical path. A big deck's push can outlast the open's
|
|
3104
|
+
// budget every time -- the seed is undone each time it is cut short -- so the deck would never
|
|
3105
|
+
// get git, and every open would wait out the budget first. So under a deadline that seed and
|
|
3106
|
+
// push run in a detached child bound by no deadline, and the command waits for it only until its
|
|
3107
|
+
// own deadline: a small deck attaches within the wait exactly as before, a big one finishes in
|
|
3108
|
+
// the background (EXIT_ATTACH_CONTINUING) and the next open finds it attached. Only the seed: a
|
|
3109
|
+
// first attach that takes or merges the remote's version writes the working tree, which must
|
|
3110
|
+
// finish before the deck is served.
|
|
3111
|
+
// Short of the caller's deadline: relaying the child's outcome takes a moment.
|
|
3112
|
+
const ATTACH_WAIT_MARGIN_MS = 1_000;
|
|
3113
|
+
const ATTACH_POLL_MS = 200;
|
|
3114
|
+
const ATTACH_LOG_MAX_BYTES = 256 * 1024;
|
|
3115
|
+
const ATTACH_OUTPUT_MAX_BYTES = 64 * 1024;
|
|
3116
|
+
function attachContinuing(why) {
|
|
3117
|
+
return new CloudGitError(`${why} It carries on in the background (log: ${ATTACH_LOG_FILE}); the deck has git once it finishes.`, EXIT_ATTACH_CONTINUING);
|
|
3118
|
+
}
|
|
3119
|
+
function attachChildRunning(ctx) {
|
|
3120
|
+
try {
|
|
3121
|
+
const seen = inspectLock(path.join(ctx.dir, ATTACH_LOCK_FILE));
|
|
3122
|
+
return seen !== null && !holderIsGone(ctx.deps, seen);
|
|
3123
|
+
}
|
|
3124
|
+
catch {
|
|
3125
|
+
return false;
|
|
3126
|
+
}
|
|
3127
|
+
}
|
|
3128
|
+
function attachWaitUntil(ctx) {
|
|
3129
|
+
return ctx.deadline - ATTACH_WAIT_MARGIN_MS;
|
|
3130
|
+
}
|
|
3131
|
+
function delay(ms) {
|
|
3132
|
+
return new Promise((resolve) => setTimeout(resolve, Math.max(0, ms)));
|
|
3133
|
+
}
|
|
3134
|
+
// False when no child was running; true when one was and has finished. Still running at the
|
|
3135
|
+
// deadline: EXIT_ATTACH_CONTINUING.
|
|
3136
|
+
async function waitForAttachChild(ctx) {
|
|
3137
|
+
if (!attachChildRunning(ctx))
|
|
3138
|
+
return false;
|
|
3139
|
+
while (attachChildRunning(ctx)) {
|
|
3140
|
+
if (ctx.deps.now() >= attachWaitUntil(ctx))
|
|
3141
|
+
throw attachContinuing('An earlier first attach of this deck is still running.');
|
|
3142
|
+
await delay(Math.min(ATTACH_POLL_MS, attachWaitUntil(ctx) - ctx.deps.now()));
|
|
3143
|
+
}
|
|
3144
|
+
return true;
|
|
3145
|
+
}
|
|
3146
|
+
// What a file gained past `offset`, at most the last ATTACH_OUTPUT_MAX_BYTES of it.
|
|
3147
|
+
function readFrom(file, offset) {
|
|
3148
|
+
try {
|
|
3149
|
+
const size = fileSize(file);
|
|
3150
|
+
const start = Math.max(offset, size - ATTACH_OUTPUT_MAX_BYTES);
|
|
3151
|
+
if (size <= start)
|
|
3152
|
+
return '';
|
|
3153
|
+
const fd = fs.openSync(file, 'r');
|
|
3154
|
+
try {
|
|
3155
|
+
const buffer = Buffer.alloc(size - start);
|
|
3156
|
+
const read = fs.readSync(fd, buffer, 0, buffer.length, start);
|
|
3157
|
+
return buffer.subarray(0, read).toString('utf-8');
|
|
3158
|
+
}
|
|
3159
|
+
finally {
|
|
3160
|
+
fs.closeSync(fd);
|
|
3161
|
+
}
|
|
3162
|
+
}
|
|
3163
|
+
catch {
|
|
3164
|
+
return '';
|
|
3165
|
+
}
|
|
3166
|
+
}
|
|
3167
|
+
/** Starts the child for a seed firstSync found to be needed, and waits for it until the deadline. */
|
|
3168
|
+
async function attachThroughChild(ctx, remoteUrl) {
|
|
3169
|
+
const log = path.join(ctx.dir, ATTACH_LOG_FILE);
|
|
3170
|
+
fs.mkdirSync(path.dirname(log), { recursive: true });
|
|
3171
|
+
if (fileSize(log) > ATTACH_LOG_MAX_BYTES)
|
|
3172
|
+
fs.rmSync(log, { force: true });
|
|
3173
|
+
const offset = fileSize(log);
|
|
3174
|
+
const childEnv = { ...ctx.deps.env, [BACKGROUND_ATTACH_ENV]: '1' };
|
|
3175
|
+
delete childEnv[DEADLINE_ENV];
|
|
3176
|
+
const fd = fs.openSync(log, 'a');
|
|
3177
|
+
let child;
|
|
3178
|
+
try {
|
|
3179
|
+
child = spawn(process.execPath, [CLI_ENTRY, 'git', 'attach', ctx.dir, '--remote', remoteUrl], {
|
|
3180
|
+
cwd: ctx.dir,
|
|
3181
|
+
env: childEnv,
|
|
3182
|
+
detached: true,
|
|
3183
|
+
stdio: ['ignore', fd, fd],
|
|
3184
|
+
});
|
|
3185
|
+
}
|
|
3186
|
+
finally {
|
|
3187
|
+
fs.closeSync(fd);
|
|
3188
|
+
}
|
|
3189
|
+
const exited = new Promise((resolve) => {
|
|
3190
|
+
child.on('error', () => resolve('error'));
|
|
3191
|
+
child.on('exit', (code) => resolve(code ?? EXIT_ERROR));
|
|
3192
|
+
});
|
|
3193
|
+
const code = await Promise.race([exited, delay(attachWaitUntil(ctx) - ctx.deps.now()).then(() => 'running')]);
|
|
3194
|
+
if (code === 'running') {
|
|
3195
|
+
child.unref();
|
|
3196
|
+
throw attachContinuing("This deck's first push is taking longer than the open waits.");
|
|
3197
|
+
}
|
|
3198
|
+
if (code === 'error')
|
|
3199
|
+
throw new CloudGitError('Could not start the attach.');
|
|
3200
|
+
const output = readFrom(log, offset);
|
|
3201
|
+
if (code === EXIT_OK)
|
|
3202
|
+
return { output };
|
|
3203
|
+
throw new CloudGitError(output.trim() || `The attach exited ${code}.`, code);
|
|
3204
|
+
}
|
|
3205
|
+
/** The child's side: one at a time, and its outcome to the container's event log. */
|
|
3206
|
+
async function attachInChild(ctx, repo) {
|
|
3207
|
+
const startedAt = ctx.deps.now();
|
|
3208
|
+
const deckId = remoteDeckId(ctx);
|
|
3209
|
+
const emit = (fields) => emitContainerEvent(ctx.deps.env, {
|
|
3210
|
+
event: 'sandbox_git_attach',
|
|
3211
|
+
deck_id: deckId && /^[A-Za-z0-9_-]{1,64}$/.test(deckId) ? deckId : null,
|
|
3212
|
+
...fields,
|
|
3213
|
+
duration_ms: ctx.deps.now() - startedAt,
|
|
3214
|
+
});
|
|
3215
|
+
let release;
|
|
3216
|
+
try {
|
|
3217
|
+
release = acquireLockFile(path.join(ctx.dir, ATTACH_LOCK_FILE), ctx.deps);
|
|
3218
|
+
}
|
|
3219
|
+
catch (e) {
|
|
3220
|
+
emit({ outcome: 'failed', error: errorText(e).slice(0, 500) });
|
|
3221
|
+
throw e;
|
|
3222
|
+
}
|
|
3223
|
+
try {
|
|
3224
|
+
const outcome = await attachLocked(ctx, repo, 'seed-only');
|
|
3225
|
+
emit({ outcome: 'attached', attach: outcome.outcome });
|
|
3226
|
+
return outcome;
|
|
3227
|
+
}
|
|
3228
|
+
catch (e) {
|
|
3229
|
+
const code = e instanceof CloudGitError ? e.exitCode : EXIT_ERROR;
|
|
3230
|
+
emit({ outcome: code === EXIT_HISTORY_UNAVAILABLE ? 'history_loading' : 'failed', error: errorText(e).slice(0, 500) });
|
|
3231
|
+
throw e;
|
|
3232
|
+
}
|
|
3233
|
+
finally {
|
|
3234
|
+
release();
|
|
3235
|
+
}
|
|
3236
|
+
}
|
|
2907
3237
|
// The seed commit an attach made for an empty remote, until it is pushed. Should the push
|
|
2908
3238
|
// fail (or the process die first), the commit is undone so the next attach starts from an
|
|
2909
3239
|
// unborn main again: it then takes whatever the remote has by then, where keeping the seed
|
|
@@ -2921,12 +3251,17 @@ function undoUnpushedSeed(ctx) {
|
|
|
2921
3251
|
}
|
|
2922
3252
|
run(ctx, ['config', '--local', '--unset-all', SEED_KEY]);
|
|
2923
3253
|
}
|
|
2924
|
-
async function firstSync(ctx, repo) {
|
|
3254
|
+
async function firstSync(ctx, repo, seedMode) {
|
|
2925
3255
|
undoUnpushedSeed(ctx);
|
|
2926
3256
|
await commitRecoveredRoot(ctx);
|
|
2927
3257
|
const remote = fetchRemote(ctx);
|
|
2928
3258
|
const head = revParse(ctx, 'HEAD');
|
|
3259
|
+
if (remote && seedMode === 'seed-only') {
|
|
3260
|
+
throw new CloudGitError('The Castle remote has history now; the next open of the deck takes it.');
|
|
3261
|
+
}
|
|
2929
3262
|
if (!remote) {
|
|
3263
|
+
if (seedMode === 'seed-elsewhere')
|
|
3264
|
+
throw new SeedInChild();
|
|
2930
3265
|
if (!head) {
|
|
2931
3266
|
const seed = await commitLocked(ctx, { reason: 'sync', message: 'Start of history' });
|
|
2932
3267
|
if (seed.sha)
|
|
@@ -2934,7 +3269,7 @@ async function firstSync(ctx, repo) {
|
|
|
2934
3269
|
}
|
|
2935
3270
|
let sync;
|
|
2936
3271
|
try {
|
|
2937
|
-
sync = await syncLocked(ctx, { commitFirst: true, mode: 'full' });
|
|
3272
|
+
sync = seedMode === 'seed-only' ? await seedPushOnly(ctx) : await syncLocked(ctx, { commitFirst: true, mode: 'full' });
|
|
2938
3273
|
}
|
|
2939
3274
|
catch (e) {
|
|
2940
3275
|
undoUnpushedSeed(ctx);
|
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) {
|
|
@@ -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;
|