castle-web-cli 0.4.227 → 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.js CHANGED
@@ -37,6 +37,7 @@ import { badTaskEndingsSince, platformInterruptionReason, ROUTER_STOPPED_RESULT,
37
37
  import { accountForRun, closingMessageOf } from './taskAccount.js';
38
38
  import { atomicWriteFileSync } from './atomicFile.js';
39
39
  import { AGENT_ATTACHMENT_PREFIX, AGENT_PLAYTEST_PREFIX, PLAN_FILE } from './localPaths.js';
40
+ import { readGitIncomingNote, removeGitIncoming } from './gitIncoming.js';
40
41
  import { applyPlanOps, buildRouterPromptParts, buildTaskPrompt, parsePlanOps, truncateToBytes, userTurnInstruction, CLAUDE_TASK_SYSTEM_REMINDER, modelTaskAddendum, isMuseModel, } from './agent-prompts.js';
41
42
  import { readCastleJson } from './castleJson.js';
42
43
  import { checkOpenrouterKey, checkOpenrouterModel, primeOpenrouterCatalog, } from './openrouter-catalog.js';
@@ -51,7 +52,9 @@ import { createRemotePlaytestExecutor } from './native/playtest-remote.js';
51
52
  import { runPlaytest, } from './native/playtest.js';
52
53
  import { AGENT_ROLE_ENV, cloudGitMode } from './cloudGit.js';
53
54
  import { createServeGitHooks, createServeMarkerPoll } from './cloudGitServe.js';
55
+ import { deckCollaborators, reportDeckEditorPresence, } from './api.js';
54
56
  export const AGENT_WS_PATH = '/__castle/agent';
57
+ const PRESENCE_INTERVAL_MS = 15_000;
55
58
  const DEFAULT_SETTINGS = {
56
59
  // Both roles run the claude CLI routed through OpenRouter at the slug below.
57
60
  // Note this takes the Anthropic credential out of play entirely: a role on
@@ -4535,16 +4538,20 @@ function maybeStartRouterQueueTurn(ctx) {
4535
4538
  persistPendingSends(ctx);
4536
4539
  const draft = state.pendingInterruptedDraft;
4537
4540
  state.pendingInterruptedDraft = '';
4541
+ state.turnInterrupted = false;
4538
4542
  state.routerRunning = true;
4539
4543
  broadcastQueueState(ctx);
4540
- startRouterTurn(ctx, userTurnInstruction({
4544
+ const instruction = userTurnInstruction({
4541
4545
  messages: texts,
4542
4546
  interruptedDraft: draft || undefined,
4543
4547
  attachments: attachmentPaths,
4544
4548
  marked: markedPaths,
4545
4549
  flattened,
4546
4550
  refs,
4547
- }));
4551
+ });
4552
+ const incoming = readGitIncomingNote(ctx.deckDir);
4553
+ state.incomingNoteShas = incoming.shas;
4554
+ startRouterTurn(ctx, incoming.note ? `${incoming.note}\n\n${instruction}` : instruction);
4548
4555
  }
4549
4556
  // The turn settled: clear the busy flag, broadcast it, then flush anything
4550
4557
  // that queued mid-turn (a clean end and an interrupt take the same path). A
@@ -4553,6 +4560,7 @@ function maybeStartRouterQueueTurn(ctx) {
4553
4560
  // which case flushing it supersedes the retry (its turn re-covers things).
4554
4561
  function onRouterQueueSettled(ctx, retryable) {
4555
4562
  const { state } = ctx;
4563
+ const interrupted = state.turnInterrupted;
4556
4564
  state.routerRunning = false;
4557
4565
  if (retryable &&
4558
4566
  !state.autoRetryUsed &&
@@ -4564,6 +4572,11 @@ function onRouterQueueSettled(ctx, retryable) {
4564
4572
  startRouterTurn(ctx, state.lastInstruction);
4565
4573
  return;
4566
4574
  }
4575
+ const incomingNoteShas = state.incomingNoteShas;
4576
+ state.incomingNoteShas = [];
4577
+ state.turnInterrupted = false;
4578
+ if (!retryable && !interrupted)
4579
+ removeGitIncoming(ctx.deckDir, incomingNoteShas);
4567
4580
  broadcastQueueState(ctx);
4568
4581
  maybeStartRouterQueueTurn(ctx);
4569
4582
  if (!state.routerRunning) {
@@ -4585,6 +4598,7 @@ function onRouterQueueSettled(ctx, retryable) {
4585
4598
  // combined instruction.
4586
4599
  function foldRouterQueueTurn(ctx) {
4587
4600
  const { state } = ctx;
4601
+ state.turnInterrupted = true;
4588
4602
  state.userEpoch += 1;
4589
4603
  killRouterChildren(ctx);
4590
4604
  reclaimInFlightSends(state.pendingSends, state.inFlightSends);
@@ -4660,6 +4674,7 @@ function interruptRouterQueue(ctx) {
4660
4674
  // the turn outright. Captured before reclaim, which would otherwise fill
4661
4675
  // the queue and make every Stop look like a Send now.
4662
4676
  const hasFollowUp = state.pendingSends.length > 0;
4677
+ state.turnInterrupted = true;
4663
4678
  state.userEpoch += 1;
4664
4679
  const draft = killRouterChildren(ctx);
4665
4680
  // Only a continued turn ("Send now") reclaims its in-flight sends so they
@@ -4711,6 +4726,8 @@ function createRouterQueue(deps) {
4711
4726
  autoRetryUsed: false,
4712
4727
  autoFoldUsed: false,
4713
4728
  lastInstruction: '',
4729
+ incomingNoteShas: [],
4730
+ turnInterrupted: false,
4714
4731
  },
4715
4732
  };
4716
4733
  // Restart recovery: re-enqueue sends that never reached the message log,
@@ -4837,6 +4854,85 @@ export function createAgentServer(opts) {
4837
4854
  socket.send(payload);
4838
4855
  }
4839
4856
  }
4857
+ const presenceDeckId = cloudGitMode(deckDir) ? readCastleJson(deckDir)?.deckId : undefined;
4858
+ let presenceOthers = [];
4859
+ let collaboratorRoster = [];
4860
+ let presenceTimer = null;
4861
+ let presenceTick = 0;
4862
+ let presenceRunning = false;
4863
+ let collaboratorsRunning = false;
4864
+ let presenceFailureLogged = false;
4865
+ let collaboratorsFailureLogged = false;
4866
+ const presenceEntry = (entry) => ({
4867
+ userId: String(entry.userId),
4868
+ username: String(entry.username),
4869
+ photoUrl: typeof entry.photo?.url === 'string' ? entry.photo.url : null,
4870
+ lastSeenAt: String(entry.lastSeenAt),
4871
+ });
4872
+ const collaboratorEntry = (entry) => ({
4873
+ userId: String(entry.userId),
4874
+ username: String(entry.username),
4875
+ photoUrl: typeof entry.photo?.url === 'string' ? entry.photo.url : null,
4876
+ addedAt: String(entry.addedAt),
4877
+ });
4878
+ async function refreshPresence() {
4879
+ if (!presenceDeckId || clients.size === 0 || presenceRunning)
4880
+ return;
4881
+ presenceRunning = true;
4882
+ try {
4883
+ presenceOthers = (await reportDeckEditorPresence(presenceDeckId)).map(presenceEntry);
4884
+ presenceFailureLogged = false;
4885
+ broadcast({ type: 'presence', others: presenceOthers });
4886
+ }
4887
+ catch (err) {
4888
+ if (!presenceFailureLogged) {
4889
+ console.error(`[presence] could not report deck editor presence: ${err instanceof Error ? err.message : String(err)}`);
4890
+ presenceFailureLogged = true;
4891
+ }
4892
+ }
4893
+ finally {
4894
+ presenceRunning = false;
4895
+ }
4896
+ }
4897
+ async function refreshCollaborators() {
4898
+ if (!presenceDeckId || clients.size === 0 || collaboratorsRunning)
4899
+ return;
4900
+ collaboratorsRunning = true;
4901
+ try {
4902
+ collaboratorRoster = (await deckCollaborators(presenceDeckId)).map(collaboratorEntry);
4903
+ collaboratorsFailureLogged = false;
4904
+ broadcast({ type: 'collaborators', collaborators: collaboratorRoster });
4905
+ }
4906
+ catch (err) {
4907
+ if (!collaboratorsFailureLogged) {
4908
+ console.error(`[presence] could not list deck collaborators: ${err instanceof Error ? err.message : String(err)}`);
4909
+ collaboratorsFailureLogged = true;
4910
+ }
4911
+ }
4912
+ finally {
4913
+ collaboratorsRunning = false;
4914
+ }
4915
+ }
4916
+ function tickPresence() {
4917
+ presenceTick += 1;
4918
+ void refreshPresence();
4919
+ if (presenceTick === 1 || (presenceTick - 1) % 4 === 0)
4920
+ void refreshCollaborators();
4921
+ }
4922
+ function startPresence() {
4923
+ if (!presenceDeckId || presenceTimer)
4924
+ return;
4925
+ tickPresence();
4926
+ presenceTimer = setInterval(tickPresence, PRESENCE_INTERVAL_MS);
4927
+ presenceTimer.unref();
4928
+ }
4929
+ function stopPresence() {
4930
+ if (presenceTimer)
4931
+ clearInterval(presenceTimer);
4932
+ presenceTimer = null;
4933
+ presenceTick = 0;
4934
+ presenceOthers = [];
4935
+ }
4840
4936
  const log = createMessageLog(messagesPath, broadcast, welcomeMessage, (message) => asClientMessage(message, opts.signPath));
4841
4937
  const messages = log.messages;
4842
4938
  const addLog = (text) => log.addLog(text);
@@ -5005,8 +5101,12 @@ export function createAgentServer(opts) {
5005
5101
  queued: routerQueue.queuedSnippets(),
5006
5102
  usage: usageFeed.latest(),
5007
5103
  accounts: accountsFeed.snapshot(),
5104
+ presence: presenceOthers,
5105
+ collaborators: collaboratorRoster,
5008
5106
  };
5009
5107
  socket.send(JSON.stringify(hello));
5108
+ if (clients.size === 1)
5109
+ startPresence();
5010
5110
  // A newly attached client is the one moment the cached value may be stale
5011
5111
  // by a whole poll interval (nothing refreshes while nobody is watching).
5012
5112
  usageFeed.refresh();
@@ -5100,6 +5200,8 @@ export function createAgentServer(opts) {
5100
5200
  });
5101
5201
  socket.on('close', () => {
5102
5202
  clients.delete(socket);
5203
+ if (clients.size === 0)
5204
+ stopPresence();
5103
5205
  });
5104
5206
  }
5105
5207
  function handleUpgrade(req, socket, head) {
@@ -5124,6 +5226,7 @@ export function createAgentServer(opts) {
5124
5226
  return handleAttachment(req, res, reqPath) || handlePlaytestFrame(req, res, reqPath);
5125
5227
  }
5126
5228
  function shutdown() {
5229
+ stopPresence();
5127
5230
  gitHooks?.stop();
5128
5231
  markerPoll?.stop();
5129
5232
  taskStore.shutdown();
package/dist/api.d.ts CHANGED
@@ -72,6 +72,24 @@ export interface MeProfile {
72
72
  }
73
73
  export declare function me(): Promise<MeProfile | null>;
74
74
  export declare function whoAmI(): Promise<Pick<MeProfile, 'userId' | 'username'> | null>;
75
+ export interface DeckEditorPresenceEntry {
76
+ userId: string;
77
+ username: string;
78
+ photo?: {
79
+ url?: string;
80
+ } | null;
81
+ lastSeenAt: string;
82
+ }
83
+ export interface DeckCollaborator {
84
+ userId: string;
85
+ username: string;
86
+ photo?: {
87
+ url?: string;
88
+ } | null;
89
+ addedAt: string;
90
+ }
91
+ export declare function reportDeckEditorPresence(deckId: string): Promise<DeckEditorPresenceEntry[]>;
92
+ export declare function deckCollaborators(deckId: string): Promise<DeckCollaborator[]>;
75
93
  export interface DeckRow {
76
94
  deckId: string;
77
95
  title: string | null;
package/dist/api.js CHANGED
@@ -103,6 +103,24 @@ export async function whoAmI() {
103
103
  handleAPIError(data);
104
104
  return pickData(data, 'me');
105
105
  }
106
+ export async function reportDeckEditorPresence(deckId) {
107
+ const data = await graphql(`mutation($deckId: ID!) {
108
+ reportDeckEditorPresence(deckId: $deckId) {
109
+ userId username photo { url } lastSeenAt
110
+ }
111
+ }`, { deckId });
112
+ handleAPIError(data);
113
+ return pickData(data, 'reportDeckEditorPresence') ?? [];
114
+ }
115
+ export async function deckCollaborators(deckId) {
116
+ const data = await graphql(`query($deckId: ID!) {
117
+ deckCollaborators(deckId: $deckId) {
118
+ userId username photo { url } addedAt
119
+ }
120
+ }`, { deckId });
121
+ handleAPIError(data);
122
+ return pickData(data, 'deckCollaborators') ?? [];
123
+ }
106
124
  // Everything an import-picker row shows for one deck: what it is, whose it is,
107
125
  // what it looks like, and who it was remixed from. One fragment, so the three
108
126
  // list queries below can't drift apart.
@@ -14,6 +14,12 @@ export interface HostContext {
14
14
  isAnonymous?: boolean;
15
15
  deepLinkUri?: string | null;
16
16
  partyId?: string | null;
17
+ joinHint?: {
18
+ deckId: string;
19
+ sessionId?: string | null;
20
+ routeId?: string | null;
21
+ slot?: string | null;
22
+ } | null;
17
23
  }
18
24
 
19
25
  export interface GraphqlError {
@@ -40,6 +40,7 @@ const COMMAND_NAMES = [
40
40
  "portal.info",
41
41
  "haptics.play",
42
42
  "multiplayer.getSession",
43
+ "multiplayer.getJoinHint",
43
44
  "multiplayer.joinDestination",
44
45
  "voice.getState",
45
46
  "voice.requestJoin",
@@ -188,6 +189,8 @@ function runCommand(ctx, command, params, caps, options) {
188
189
  return passHas(ctx, params, caps);
189
190
  case "multiplayer.getSession":
190
191
  return multiplayerGetSession(ctx, params, caps);
192
+ case "multiplayer.getJoinHint":
193
+ return Promise.resolve(multiplayerGetJoinHint(ctx));
191
194
  case "voice.getState":
192
195
  return voiceGetState(ctx, params, caps);
193
196
  case "voice.requestJoin":
@@ -240,13 +243,47 @@ function runCommand(ctx, command, params, caps, options) {
240
243
  async function multiplayerGetSession(ctx, params, caps) {
241
244
  const request = multiplayerSessionRequest(params);
242
245
  const deckId = requireDeckId(ctx, "multiplayer.getSession");
246
+ const hintedSessionId = multiplayerHintedSessionId(ctx, deckId);
243
247
  // Which shared session a play belongs to is the host's call, not the deck's,
244
248
  // the way `shared.cpp` reads the party off the engine rather than the scene.
245
- // A play that arrived through a party stays inside it; otherwise public.
246
- const mode = request.mode === "public" && ctx.partyId ? "party" : request.mode;
247
- const data = await graphql(caps.graphqlFetch, CAULDRON_MULTIPLAYER_SESSION_QUERY, { deckId, mode, key: request.key ?? null, partyId: ctx.partyId ?? null }, "multiplayer.getSession");
249
+ // A play that arrived through a party stays inside it unless trusted host
250
+ // chrome is sending this public join to the room where a friend is playing.
251
+ const mode = request.mode === "public" && ctx.partyId && !hintedSessionId
252
+ ? "party"
253
+ : request.mode;
254
+ const data = await graphql(caps.graphqlFetch, CAULDRON_MULTIPLAYER_SESSION_QUERY, {
255
+ deckId,
256
+ mode,
257
+ key: request.key ?? null,
258
+ sessionId: request.mode === "public" ? hintedSessionId : null,
259
+ partyId: ctx.partyId ?? null,
260
+ }, "multiplayer.getSession");
248
261
  return multiplayerSessionResult(data.getCauldronMultiplayerSession);
249
262
  }
263
+ const MULTIPLAYER_SESSION_ID_MAX_LENGTH = 256;
264
+ function multiplayerHintedSessionId(ctx, deckId) {
265
+ const hint = ctx.joinHint;
266
+ if (!hint || hint.deckId !== deckId)
267
+ return null;
268
+ return typeof hint.sessionId === "string" &&
269
+ hint.sessionId.length > 0 &&
270
+ hint.sessionId.length <= MULTIPLAYER_SESSION_ID_MAX_LENGTH
271
+ ? hint.sessionId
272
+ : null;
273
+ }
274
+ function multiplayerGetJoinHint(ctx) {
275
+ const hint = ctx.joinHint;
276
+ if (!ctx.deckId ||
277
+ !hint ||
278
+ hint.deckId !== ctx.deckId ||
279
+ typeof hint.routeId !== "string" ||
280
+ hint.routeId.length === 0 ||
281
+ typeof hint.slot !== "string" ||
282
+ hint.slot.length === 0) {
283
+ return null;
284
+ }
285
+ return { routeId: hint.routeId, slot: hint.slot };
286
+ }
250
287
  function multiplayerSessionRequest(params) {
251
288
  const mode = asMultiplayerMode(params.mode);
252
289
  return {
@@ -2421,12 +2458,14 @@ const CAULDRON_MULTIPLAYER_SESSION_QUERY = `
2421
2458
  $deckId: ID!
2422
2459
  $mode: String!
2423
2460
  $key: String
2461
+ $sessionId: ID
2424
2462
  $partyId: ID
2425
2463
  ) {
2426
2464
  getCauldronMultiplayerSession(
2427
2465
  deckId: $deckId
2428
2466
  mode: $mode
2429
2467
  key: $key
2468
+ sessionId: $sessionId
2430
2469
  partyId: $partyId
2431
2470
  ) {
2432
2471
  sessionId
@@ -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 CLOUD_EXCLUDES = ['node_modules/', 'dist/', '/imports/', '.castle/', '.vite/'];
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
- "[Castle] Syncing this deck with its Castle git remote hit a merge conflict: someone pushed to main from another computer (most likely the user's laptop) while this sandbox had changes of its own. Git merged what it could.",
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). The other computer'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 the other computer's version)` : `${f.path} (the other computer deleted it)`)));
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('What the other computer 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 the other computer'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 other-computer 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 another computer\"`, 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 another computer, what conflicted, and what was kept from each side.');
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 = { at, files: files.map((f) => f.path), theirs, ours, instruction };
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 another computer`,
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');
@@ -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 CONFLICT_NOTICE = 'Changes pushed from another computer conflicted with this deck; the agent is resolving them.';
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 ? report.notice : CONFLICT_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
- '[Castle] The merge with changes from another computer is still not concluded, so no commit can land until it is.',
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
- 'Spawn one task agent to remove every conflict marker (<<<<<<< / ||||||| / ======= / >>>>>>>) from the conflicted files, preferring the other computer\'s side, and finish with `castle-web commit --resolve -m "Merge changes from another computer"`. Never force-push.',
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
- notice: 'A merge with changes from another computer is still unresolved; the agent is taking another look.',
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;