@ycodium-ai/plugin-team 0.2.4688 → 0.2.5004

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/index.js CHANGED
@@ -8,7 +8,7 @@ var __export = (target, all3) => {
8
8
  import { definePlugin } from "@ycodium-ai/plugin-api";
9
9
 
10
10
  // ../../packages/plugin-api/src/version.ts
11
- var PLUGIN_API_VERSION = 128;
11
+ var PLUGIN_API_VERSION = 142;
12
12
 
13
13
  // ../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=2379c0b6f6365efdc960ef467ae589e40827f36fbfe7992e14580cecfa87fd2b/node_modules/effect/dist/Pipeable.js
14
14
  var pipeArguments = (self, args2) => {
@@ -7430,12 +7430,14 @@ function registerGoalCommands(ctx, service2) {
7430
7430
  ctx.command({
7431
7431
  name: "goal",
7432
7432
  scope: "read",
7433
+ homeOnly: true,
7433
7434
  payloadSchema: payloadSchemaOf(ReadGoalInput),
7434
7435
  handle: (input) => service2.read(decodeReadGoal(input).projectId)
7435
7436
  });
7436
7437
  ctx.command({
7437
7438
  name: "startGoal",
7438
7439
  scope: "operate",
7440
+ homeOnly: true,
7439
7441
  payloadSchema: payloadSchemaOf(StartGoalInput),
7440
7442
  handle: (input) => service2.start(input)
7441
7443
  });
@@ -7726,6 +7728,7 @@ function registerTeamWatch(ctx, options) {
7726
7728
  ctx.stream({
7727
7729
  name: "watch",
7728
7730
  scope: "read",
7731
+ homeOnly: true,
7729
7732
  payloadSchema: payloadSchemaOf(ReadBoardInput),
7730
7733
  buffer: { latest: 1 },
7731
7734
  handle: async (payload, emit, signal) => {
@@ -7822,6 +7825,7 @@ function registerBoardCommands(ctx, goals, rosters, options = {}) {
7822
7825
  const view = await rosters.activeView(projectId).catch(() => null);
7823
7826
  const roster = view?.team ?? null;
7824
7827
  const members = view?.active ?? null;
7828
+ const rosterMembers = roster?.members ?? view?.teamMembers ?? [];
7825
7829
  const read = await goals.read(projectId, {
7826
7830
  roster,
7827
7831
  ...members === null ? {} : { known: members },
@@ -7829,6 +7833,7 @@ function registerBoardCommands(ctx, goals, rosters, options = {}) {
7829
7833
  });
7830
7834
  return {
7831
7835
  roster,
7836
+ rosterMembers,
7832
7837
  // 线上没有目标时 read 会退回项目级目标;团队层只认这条线自己的。
7833
7838
  goal: read !== null && workLineId !== void 0 && read.workLineId !== workLineId ? null : read
7834
7839
  };
@@ -7836,10 +7841,11 @@ function registerBoardCommands(ctx, goals, rosters, options = {}) {
7836
7841
  ctx.command({
7837
7842
  name: "board",
7838
7843
  scope: "read",
7844
+ homeOnly: true,
7839
7845
  payloadSchema: payloadSchemaOf(ReadBoardInput),
7840
7846
  handle: async (payload, invocation) => {
7841
7847
  const { projectId, workLineId } = decodeRead2(payload);
7842
- const [stateList, { goal, roster }, toolkitStates, people, machines, viewer] = await Promise.all([
7848
+ const [stateList, { goal, roster, rosterMembers }, toolkitStates, people, machines, viewer] = await Promise.all([
7843
7849
  ctx.work.states.list({ projectId }),
7844
7850
  readTeam(projectId, workLineId),
7845
7851
  ctx.projects.toolkits.get({ projectId }),
@@ -7855,7 +7861,7 @@ function registerBoardCommands(ctx, goals, rosters, options = {}) {
7855
7861
  const goalItemId = goal === null ? null : teamGoalItemId(projectId, goal.goalId);
7856
7862
  const [remoteWork, goalItem] = await Promise.all([
7857
7863
  Promise.all(
7858
- (roster?.members ?? []).flatMap(
7864
+ rosterMembers.flatMap(
7859
7865
  (member) => member.principal === void 0 ? [] : [
7860
7866
  ctx.work.remoteAgentPending.get({ projectId, principalId: member.principal.principalId }).then(
7861
7867
  // 一台机器上可能有好几个成员:只算派给这个成员的(与直接派给那台机器的)。
@@ -7915,7 +7921,7 @@ function registerBoardCommands(ctx, goals, rosters, options = {}) {
7915
7921
  key: personKey(row.person),
7916
7922
  displayName: row.displayName
7917
7923
  })),
7918
- rosterMembers: roster?.members ?? [],
7924
+ rosterMembers,
7919
7925
  ...roster?.aliases === void 0 ? {} : { rosterAliases: roster.aliases },
7920
7926
  ...machines === null ? { machinesUnavailable: true } : {},
7921
7927
  machines: [...machines?.values() ?? []].map(
@@ -8068,7 +8074,13 @@ function createRosterService(ctx, options = {}) {
8068
8074
  listMembers(ctx, projectId),
8069
8075
  machinesOf(projectId)
8070
8076
  ]);
8071
- return { stored, active, machines: where.machines, ...resolveTeam(stored, active, where) };
8077
+ return {
8078
+ stored,
8079
+ active,
8080
+ machines: where.machines,
8081
+ teamMembers: active.filter(isActiveAgent).map((member) => toTeamMember(member, where)),
8082
+ ...resolveTeam(stored, active, where)
8083
+ };
8072
8084
  };
8073
8085
  const inspect = async (projectId) => {
8074
8086
  const [view, history] = await Promise.all([
@@ -9015,6 +9027,18 @@ var en_default = {
9015
9027
  trial_started: "Start trial",
9016
9028
  trial_done: "Finish trial",
9017
9029
  retry_trial: "Retry trial"
9030
+ },
9031
+ runtime: {
9032
+ status: {
9033
+ working: "Working",
9034
+ attention: "Needs you",
9035
+ failed: "Failed",
9036
+ idle: "Idle",
9037
+ stopped: "Stopped"
9038
+ },
9039
+ none: "No status reported yet",
9040
+ offline: "Offline, last seen {{time}}",
9041
+ stale: "Status out of date"
9018
9042
  }
9019
9043
  };
9020
9044
 
@@ -9608,6 +9632,7 @@ function registerCoordinator(ctx, runtime) {
9608
9632
  tools: [
9609
9633
  {
9610
9634
  name: "create_member",
9635
+ homeOnly: true,
9611
9636
  remoteAvailable: true,
9612
9637
  description: coordinatorMessage("createTool"),
9613
9638
  inputSchema: toolSchema(CreateMemberToolInput),
@@ -9615,6 +9640,7 @@ function registerCoordinator(ctx, runtime) {
9615
9640
  },
9616
9641
  {
9617
9642
  name: "update_member",
9643
+ homeOnly: true,
9618
9644
  remoteAvailable: true,
9619
9645
  description: coordinatorMessage("updateTool"),
9620
9646
  inputSchema: toolSchema(UpdateMemberToolInput),
@@ -9622,6 +9648,7 @@ function registerCoordinator(ctx, runtime) {
9622
9648
  },
9623
9649
  {
9624
9650
  name: "remove_member",
9651
+ homeOnly: true,
9625
9652
  remoteAvailable: true,
9626
9653
  description: coordinatorMessage("removeTool"),
9627
9654
  inputSchema: toolSchema(MemberRefToolInput),
@@ -9629,6 +9656,7 @@ function registerCoordinator(ctx, runtime) {
9629
9656
  },
9630
9657
  {
9631
9658
  name: "restore_member",
9659
+ homeOnly: true,
9632
9660
  remoteAvailable: true,
9633
9661
  description: coordinatorMessage("restoreTool"),
9634
9662
  inputSchema: toolSchema(MemberRefToolInput),
@@ -9747,6 +9775,29 @@ function foldMemberChanges(state, event) {
9747
9775
  }
9748
9776
  }
9749
9777
 
9778
+ // src/runtime/projectHome.ts
9779
+ import { projectOrNull } from "@ycodium-ai/plugin-api";
9780
+ function projectHomeVerdicts(ctx) {
9781
+ const known = /* @__PURE__ */ new Map();
9782
+ return async (projectId) => {
9783
+ const cached2 = known.get(projectId);
9784
+ if (cached2 !== void 0) return cached2;
9785
+ const verdict = await projectOrNull(ctx.projects, projectId).then(
9786
+ (project2) => {
9787
+ const home = project2?.homeEnvironmentId;
9788
+ return home == null || home === ctx.environment.id ? "here" : "elsewhere";
9789
+ },
9790
+ () => "unknown"
9791
+ );
9792
+ known.set(projectId, verdict);
9793
+ return verdict;
9794
+ };
9795
+ }
9796
+ function homeGate(ctx) {
9797
+ const verdictOf = projectHomeVerdicts(ctx);
9798
+ return async (projectId) => await verdictOf(projectId) === "here";
9799
+ }
9800
+
9750
9801
  // src/coordinator/runtime.ts
9751
9802
  var GUARD_MESSAGES = {
9752
9803
  "member-not-found": "memberNotFound",
@@ -9843,7 +9894,9 @@ function startCoordinatorRuntime(ctx, deps) {
9843
9894
  return await settleFromReceipt(intent) ?? complete(intent, { status: "voided" });
9844
9895
  };
9845
9896
  const flush = () => serial(async () => {
9897
+ const runnable = homeGate(ctx);
9846
9898
  for (const intent of Object.values((await state.get()).pending)) {
9899
+ if (!await runnable(intent.projectId)) continue;
9847
9900
  try {
9848
9901
  await reconcile(intent);
9849
9902
  } catch (error) {
@@ -10393,7 +10446,6 @@ var staleSessions = (state) => {
10393
10446
  );
10394
10447
  return Object.entries(state.sessions).filter(([threadId]) => !live.has(threadId)).map(([threadId, { projectId }]) => ({ threadId, projectId, finishing: passed.has(threadId) }));
10395
10448
  };
10396
- var occupiedSessions = (state) => Object.keys(state.sessions).length - staleSessions(state).filter((row) => !row.finishing).length;
10397
10449
  var rebindTargets = (state, projectId) => boundGoals(state, projectId).flatMap(
10398
10450
  (bound) => Object.entries(bound.specs).flatMap(([memberId, specKey]) => {
10399
10451
  const record2 = recordOf(state, projectId, memberId);
@@ -10426,6 +10478,7 @@ function registerMemberCommands(ctx, rosters, writer, trials2) {
10426
10478
  ctx.command({
10427
10479
  name: "members",
10428
10480
  scope: "read",
10481
+ homeOnly: true,
10429
10482
  payloadSchema: payloadSchemaOf(ReadMembersInput),
10430
10483
  handle: async (payload, invocation) => {
10431
10484
  const { projectId } = decodeReadMembers(payload);
@@ -10444,6 +10497,7 @@ function registerMemberCommands(ctx, rosters, writer, trials2) {
10444
10497
  ctx.command({
10445
10498
  name: "roster",
10446
10499
  scope: "read",
10500
+ homeOnly: true,
10447
10501
  payloadSchema: payloadSchemaOf(ReadMembersInput),
10448
10502
  handle: (payload) => rosters.read(decodeReadMembers(payload).projectId)
10449
10503
  });
@@ -10464,41 +10518,68 @@ function registerMemberCommands(ctx, rosters, writer, trials2) {
10464
10518
  ctx.command({
10465
10519
  name: "createMember",
10466
10520
  scope: "operate",
10521
+ homeOnly: true,
10467
10522
  payloadSchema: payloadSchemaOf(CreateMemberInput),
10468
10523
  handle: (payload, invocation) => writer.create(payload, invocation)
10469
10524
  });
10470
10525
  ctx.command({
10471
10526
  name: "updateMember",
10472
10527
  scope: "operate",
10528
+ homeOnly: true,
10473
10529
  payloadSchema: payloadSchemaOf(UpdateMemberInput),
10474
10530
  handle: (payload, invocation) => writer.update(payload, invocation)
10475
10531
  });
10476
10532
  ctx.command({
10477
10533
  name: "removeMember",
10478
10534
  scope: "operate",
10535
+ homeOnly: true,
10479
10536
  payloadSchema: payloadSchemaOf(MemberRefInput),
10480
10537
  handle: (payload, invocation) => writer.remove(payload, invocation)
10481
10538
  });
10482
10539
  ctx.command({
10483
10540
  name: "restoreMember",
10484
10541
  scope: "operate",
10542
+ homeOnly: true,
10485
10543
  payloadSchema: payloadSchemaOf(MemberRefInput),
10486
10544
  handle: (payload, invocation) => writer.restore(payload, invocation)
10487
10545
  });
10488
10546
  ctx.command({
10489
10547
  name: "setLead",
10490
10548
  scope: "operate",
10549
+ homeOnly: true,
10491
10550
  payloadSchema: payloadSchemaOf(SetLeadInput),
10492
10551
  handle: (payload) => rosters.setLead(payload)
10493
10552
  });
10494
10553
  ctx.command({
10495
10554
  name: "importRoster",
10496
10555
  scope: "operate",
10556
+ homeOnly: true,
10497
10557
  payloadSchema: payloadSchemaOf(ImportRosterInput),
10498
10558
  handle: (payload, invocation) => writer.importLegacy(payload, invocation)
10499
10559
  });
10500
10560
  }
10501
10561
 
10562
+ // src/members/runtimeStream.ts
10563
+ var decodeRead3 = decodeUnknownSync(ReadMembersInput);
10564
+ function registerMemberRuntimeStream(ctx) {
10565
+ ctx.stream({
10566
+ name: "runtime",
10567
+ scope: "read",
10568
+ payloadSchema: payloadSchemaOf(ReadMembersInput),
10569
+ buffer: { latest: 1 },
10570
+ handle: async (payload, emit, signal) => {
10571
+ const { projectId } = decodeRead3(payload);
10572
+ await ctx.members.runtime.subscribe(
10573
+ { projectId },
10574
+ async (frame) => {
10575
+ if (frame._tag === "snapshot") await emit({ items: frame.value.items });
10576
+ },
10577
+ signal
10578
+ );
10579
+ }
10580
+ });
10581
+ }
10582
+
10502
10583
  // src/members/writes.ts
10503
10584
  var decodeCreate2 = decodeUnknownOption2(CreateMemberInput);
10504
10585
  var decodeUpdate2 = decodeUnknownOption2(UpdateMemberInput);
@@ -11434,8 +11515,8 @@ function registerDispatchGate(ctx, deps) {
11434
11515
  if (!exemptFromTrial(project2, { threadId }, input.workItemId ?? void 0) && !isReady2(input.projectId, input.memberId, scope2.goalId))
11435
11516
  return hold("the member has not passed its trial run yet");
11436
11517
  if (input.reason === "group" && input.recordId !== void 0) {
11437
- const [record2] = await ctx.communication.records.get({ recordIds: [input.recordId] });
11438
- const fromAgent = record2 !== void 0 && record2.from.kind !== "user" && record2.from.kind !== "local-owner";
11518
+ const [entry] = await ctx.communication.posts.get({ recordIds: [input.recordId] });
11519
+ const fromAgent = entry !== void 0 && (entry.kind === "post" ? entry.author.kind !== "human" : entry.kind === "record" && entry.from.kind !== "user" && entry.from.kind !== "local-owner");
11439
11520
  if (fromAgent && !await pacing.allows(threadId, await deps.now()))
11440
11521
  return hold("slowed down: the member made no progress in its last turns");
11441
11522
  }
@@ -11465,13 +11546,13 @@ function registerDispatchGate(ctx, deps) {
11465
11546
  }
11466
11547
 
11467
11548
  // src/trial/hostState.ts
11468
- import { projectOrNull } from "@ycodium-ai/plugin-api";
11549
+ import { projectOrNull as projectOrNull2 } from "@ycodium-ai/plugin-api";
11469
11550
  function projectGone(ctx) {
11470
11551
  const known = /* @__PURE__ */ new Map();
11471
11552
  return async (projectId) => {
11472
11553
  const cached2 = known.get(projectId);
11473
11554
  if (cached2 !== void 0) return cached2;
11474
- const gone = await projectOrNull(ctx.projects, projectId).then(
11555
+ const gone = await projectOrNull2(ctx.projects, projectId).then(
11475
11556
  (project2) => project2 === null || project2.archivedAt != null,
11476
11557
  () => false
11477
11558
  );
@@ -11680,9 +11761,11 @@ function startMemberBindingRuntime(ctx, goals, rosters, wakes, trials2) {
11680
11761
  };
11681
11762
  const execute = async (only) => {
11682
11763
  const [everyGoal, wake] = await Promise.all([goals.everyGoal(), wakes.get()]);
11764
+ const runnable = homeGate(ctx);
11683
11765
  for (const goal of everyGoal) {
11684
11766
  const { projectId } = goal;
11685
11767
  if (only !== void 0 && projectId !== only) continue;
11768
+ if (!await runnable(projectId)) continue;
11686
11769
  try {
11687
11770
  if (roomThreadOf(goal) === void 0) continue;
11688
11771
  if (goal.workLineId !== void 0 && wake[projectId]?.lineStops?.[goal.workLineId] === "deleted")
@@ -11880,8 +11963,10 @@ function startMemberRemovalRuntime(ctx, goals, wakes) {
11880
11963
  };
11881
11964
  const execute = async (only) => {
11882
11965
  const state = await wakes.get();
11966
+ const runnable = homeGate(ctx);
11883
11967
  for (const [projectId, project2] of Object.entries(state)) {
11884
11968
  if (only !== void 0 && projectId !== only) continue;
11969
+ if (!await runnable(projectId)) continue;
11885
11970
  const assigned = new Set(
11886
11971
  Object.values(project2.items).flatMap(
11887
11972
  (item) => isClosed(item) ? [] : item.assigneeMembers ?? []
@@ -12997,8 +13082,10 @@ function startWakeRuntime(ctx, goals, options = {}) {
12997
13082
  const execute = async () => {
12998
13083
  let state = await wakes.get();
12999
13084
  const isReady2 = options.readiness === void 0 ? () => true : await options.readiness();
13085
+ const runnable = homeGate(ctx);
13000
13086
  for (const wake of dueWakes(state)) {
13001
13087
  if (!isWakeDue(state, wake)) continue;
13088
+ if (!await runnable(wake.projectId)) continue;
13002
13089
  const memberId = memberOfRecipient(state[wake.projectId], wake);
13003
13090
  if (memberId !== void 0 && !exemptFromTrial(state[wake.projectId], wake, wake.workItemId) && !isReady2(
13004
13091
  wake.projectId,
@@ -13076,29 +13163,39 @@ function startWakeRuntime(ctx, goals, options = {}) {
13076
13163
  }
13077
13164
 
13078
13165
  // src/runtime/wakeSupplement.ts
13079
- var decodeDispatched2 = decodeUnknownOption2(
13080
- Struct({ projectId: String4, threadId: String4 })
13081
- );
13166
+ var SWEEP_MS = 12e4;
13082
13167
  function registerWakeSupplement(ctx, wakes, groupDigest) {
13083
13168
  const add3 = async (input) => {
13169
+ const home = await projectHomeVerdicts(ctx)(input.projectId);
13170
+ if (home === "elsewhere") return null;
13171
+ if (home === "unknown")
13172
+ throw new Error(
13173
+ "the team cannot tell where this project's home is right now, so it cannot hand this work item over yet"
13174
+ );
13084
13175
  const state = await wakes.state.get({ throughSequence: input.throughSequence });
13085
13176
  const project2 = readFact(state, input.projectId);
13086
13177
  if (project2 === null || lineScopeOfThread(project2, input.threadId) === void 0) return null;
13087
13178
  const decision = teamItemDecision(project2, input.projectId, input.workItemId, input.threadId);
13088
13179
  if (decision.kind === "held")
13089
13180
  throw new Error(`the team cannot hand this work item over now: ${decision.reason}`);
13090
- const { text } = await wakes.compose(decision.wake, state);
13181
+ const { digest, text } = await wakes.compose(decision.wake, state);
13182
+ if (digest !== null)
13183
+ await groupDigest?.bind(input.projectId, digest, {
13184
+ workItemId: input.workItemId,
13185
+ memberId: input.memberId
13186
+ });
13091
13187
  return text();
13092
13188
  };
13189
+ const confirm = (throughSequence) => groupDigest === void 0 ? Promise.resolve() : groupDigest.confirmDispatched(homeGate(ctx), throughSequence);
13093
13190
  ctx.reactor({
13094
13191
  name: "team-board-handover",
13095
13192
  events: ["work.item-dispatched"],
13096
- handle: async (event) => {
13097
- const decoded = decodeDispatched2(event.payload);
13098
- if (isNone2(decoded) || groupDigest === void 0) return;
13099
- await groupDigest.confirmPrepared(decoded.value.projectId, decoded.value.threadId);
13100
- }
13193
+ handle: (event) => confirm(event.sequence)
13101
13194
  });
13195
+ ctx.interval({ name: "team-board-handover", everyMs: SWEEP_MS, handle: () => confirm() });
13196
+ void confirm().catch(
13197
+ (error) => ctx.log.warn("team digest confirmation catch-up failed", { error })
13198
+ );
13102
13199
  return ctx.operations.supplement({ operations: ["work.dispatch"], add: add3 });
13103
13200
  }
13104
13201
 
@@ -13108,6 +13205,7 @@ function startWorktreeSetupRuntime(ctx, deps) {
13108
13205
  const requested = /* @__PURE__ */ new Map();
13109
13206
  let running = Promise.resolve();
13110
13207
  const setUp = async (projectId, threadId) => {
13208
+ if (!await homeGate(ctx)(projectId)) return;
13111
13209
  const project2 = (await deps.wakes.get())[projectId];
13112
13210
  const worktree = memberWorktreeFor(deps.goals, project2, projectId, { threadId });
13113
13211
  if (worktree === void 0 || worktree.failure !== void 0) return;
@@ -13176,6 +13274,12 @@ function startRecoveryRuntime(ctx, goals, state, worktrees) {
13176
13274
  )
13177
13275
  );
13178
13276
  }
13277
+ const runnable = homeGate(ctx);
13278
+ projects = Object.fromEntries(
13279
+ (await Promise.all(
13280
+ Object.entries(projects).map(async (row) => await runnable(row[0]) ? [row] : [])
13281
+ )).flat()
13282
+ );
13179
13283
  for (const [key, entry] of skipped)
13180
13284
  if (readFact(current, entry.projectId)?.recovery?.[entry.threadId]?.pending?.turnId !== entry.turnId)
13181
13285
  skipped.delete(key);
@@ -13369,8 +13473,10 @@ var settledThreadOf = (payload) => {
13369
13473
  function startLeadCheckinRuntime(ctx, state, goals) {
13370
13474
  const check = async (threadId) => {
13371
13475
  const projects = await state.get();
13476
+ const runnable = homeGate(ctx);
13372
13477
  for (const [projectId, project2] of Object.entries(projects)) {
13373
13478
  if (!isLeadThread(project2, threadId)) continue;
13479
+ if (!await runnable(projectId)) continue;
13374
13480
  const goal = await goals.ofThread(projectId, threadId);
13375
13481
  if (goal === null) continue;
13376
13482
  if (isThreadGated(project2, threadId)) continue;
@@ -13622,25 +13728,42 @@ ${asked.length}`
13622
13728
  ]
13623
13729
  });
13624
13730
  };
13731
+ const membersOf = (projectGoals) => new Map(
13732
+ projectGoals.flatMap((goal) => {
13733
+ const execution = goalExecution(goal);
13734
+ return execution.members.filter((member) => member.memberId !== execution.leadMemberId).map((member) => [recipientKey(member), member]);
13735
+ })
13736
+ );
13737
+ const assigneeOf = (wake, item, member, members) => member.startsWith(MEMBER_PREFIX) ? executorOf(wake[item.projectId], item.workItemId, member.slice(MEMBER_PREFIX.length)) : members.get(member);
13625
13738
  const tick = async () => {
13626
13739
  const started = Object.values(await progress.get()).filter((item) => item.started);
13627
13740
  const at = Date.parse(await now3());
13628
13741
  mountedAt = Date.parse(await mounted);
13629
13742
  const wake = await wakes.get();
13630
13743
  summaries.clear();
13744
+ const verdictOf = projectHomeVerdicts(ctx);
13745
+ const unsampled = /* @__PURE__ */ new Set();
13631
13746
  for (const projectId of new Set(started.map((item) => item.projectId))) {
13747
+ const verdict = await verdictOf(projectId);
13748
+ if (verdict !== "here") {
13749
+ if (verdict === "unknown") {
13750
+ const members2 = membersOf(await goals.allOf(projectId));
13751
+ for (const item of started)
13752
+ if (item.projectId === projectId)
13753
+ for (const member of Object.keys(item.members)) {
13754
+ const who = assigneeOf(wake, item, member, members2);
13755
+ if (who !== void 0 && "threadId" in who) unsampled.add(who.threadId);
13756
+ }
13757
+ }
13758
+ continue;
13759
+ }
13632
13760
  const projectGoals = await goals.allOf(projectId);
13633
13761
  if (projectGoals.length === 0) continue;
13634
- const members = new Map(
13635
- projectGoals.flatMap((goal) => {
13636
- const execution = goalExecution(goal);
13637
- return execution.members.filter((member) => member.memberId !== execution.leadMemberId).map((member) => [recipientKey(member), member]);
13638
- })
13639
- );
13762
+ const members = membersOf(projectGoals);
13640
13763
  for (const item of started) {
13641
13764
  if (item.projectId !== projectId) continue;
13642
13765
  for (const [member, clock] of Object.entries(item.members)) {
13643
- const who = member.startsWith(MEMBER_PREFIX) ? executorOf(wake[projectId], item.workItemId, member.slice(MEMBER_PREFIX.length)) : members.get(member) ?? void 0;
13766
+ const who = assigneeOf(wake, item, member, members);
13644
13767
  if (who === void 0) continue;
13645
13768
  const gatedProject = wake[projectId];
13646
13769
  if (gatedProject !== void 0 && isRecipientGated(gatedProject, who, gatedProject.items[item.workItemId]?.workLineId))
@@ -13657,7 +13780,7 @@ ${asked.length}`
13657
13780
  }
13658
13781
  }
13659
13782
  }
13660
- capacity.prune(new Set(summaries.keys()));
13783
+ capacity.prune(/* @__PURE__ */ new Set([...summaries.keys(), ...unsampled]));
13661
13784
  };
13662
13785
  ctx.interval({ name: "team-progress-checkin", everyMs: TICK_MS, handle: tick });
13663
13786
  }
@@ -14100,13 +14223,14 @@ function startHandbookRuntime(ctx, worktrees) {
14100
14223
  "changed" in result2 && result2.changed === true
14101
14224
  );
14102
14225
  };
14103
- const remind = async () => {
14226
+ const remind = async (runnable = homeGate(ctx)) => {
14104
14227
  const snapshot = await state.get();
14105
14228
  const pendingAny = Object.keys(snapshot.pendingReminders).length > 0;
14106
14229
  const wakeState = pendingAny ? await worktrees.lane.state.get() : void 0;
14107
14230
  const isReady2 = !pendingAny || worktrees.readiness === void 0 ? () => true : await worktrees.readiness();
14108
14231
  for (const [key, reminder] of Object.entries(snapshot.pendingReminders)) {
14109
14232
  const { projectId, release, member } = reminder;
14233
+ if (!await runnable(projectId)) continue;
14110
14234
  const project2 = readFact(snapshot.projects, projectId) ?? emptyHandbookProject();
14111
14235
  const seat = currentSeat(project2, member.memberId, wakeState?.[projectId]);
14112
14236
  if (seat === void 0) continue;
@@ -14150,7 +14274,9 @@ function startHandbookRuntime(ctx, worktrees) {
14150
14274
  }
14151
14275
  };
14152
14276
  const execute = async () => {
14277
+ const runnable = homeGate(ctx);
14153
14278
  for (const intent of Object.values((await state.get()).pendingPublications)) {
14279
+ if (!await runnable(intent.projectId)) continue;
14154
14280
  try {
14155
14281
  await reconcile(intent);
14156
14282
  } catch (error) {
@@ -14161,13 +14287,14 @@ function startHandbookRuntime(ctx, worktrees) {
14161
14287
  }
14162
14288
  }
14163
14289
  for (const ack of Object.values((await state.get()).pendingAcknowledgements)) {
14290
+ if (!await runnable(ack.projectId)) continue;
14164
14291
  try {
14165
14292
  await acknowledge(ack.projectId, ack.release, ack.memberId);
14166
14293
  } catch (error) {
14167
14294
  ctx.log.warn("team handbook publisher acknowledgement failed", { ...ack, error });
14168
14295
  }
14169
14296
  }
14170
- await remind();
14297
+ await remind(runnable);
14171
14298
  };
14172
14299
  const flush = () => serial(execute);
14173
14300
  ctx.reactor({
@@ -14339,13 +14466,14 @@ var currentSeat = (project2, memberId, wake) => {
14339
14466
  var decodeAcknowledgement = decodeUnknownSync(AcknowledgeInput);
14340
14467
  var decodePublish = decodeUnknownSync(PublishInput);
14341
14468
  var decodeRevert = decodeUnknownSync(RevertInput);
14342
- var decodeRead3 = decodeUnknownSync(ReadHandbookInput);
14469
+ var decodeRead4 = decodeUnknownSync(ReadHandbookInput);
14343
14470
  function registerHandbook(ctx, runtime) {
14344
14471
  ctx.toolkit({
14345
14472
  name: "handbook",
14346
14473
  tools: [
14347
14474
  {
14348
14475
  name: "acknowledge_handbook",
14476
+ homeOnly: true,
14349
14477
  remoteAvailable: true,
14350
14478
  description: handbookMessage("ackTool"),
14351
14479
  inputSchema: toolSchema(AcknowledgeInput),
@@ -14353,6 +14481,7 @@ function registerHandbook(ctx, runtime) {
14353
14481
  },
14354
14482
  {
14355
14483
  name: "publish_handbook",
14484
+ homeOnly: true,
14356
14485
  description: handbookMessage("publishTool"),
14357
14486
  inputSchema: toolSchema(PublishInput),
14358
14487
  handle: (input, invocation) => runTool(
@@ -14361,6 +14490,7 @@ function registerHandbook(ctx, runtime) {
14361
14490
  },
14362
14491
  {
14363
14492
  name: "revert_handbook",
14493
+ homeOnly: true,
14364
14494
  description: handbookMessage("revertTool"),
14365
14495
  inputSchema: toolSchema(RevertInput),
14366
14496
  handle: (input, invocation) => runTool(
@@ -14372,8 +14502,9 @@ function registerHandbook(ctx, runtime) {
14372
14502
  ctx.command({
14373
14503
  name: "handbook",
14374
14504
  scope: "read",
14505
+ homeOnly: true,
14375
14506
  payloadSchema: payloadSchemaOf(ReadHandbookInput),
14376
- handle: (input) => runtime.read(decodeRead3(input).projectId)
14507
+ handle: (input) => runtime.read(decodeRead4(input).projectId)
14377
14508
  });
14378
14509
  ctx.operations.guard({ operations: ["work.start"], check: runtime.startCheck });
14379
14510
  }
@@ -14408,6 +14539,7 @@ function registerHandbookPanel(ctx, runtime) {
14408
14539
  ctx.command({
14409
14540
  name: "handbookPanel",
14410
14541
  scope: "read",
14542
+ homeOnly: true,
14411
14543
  payloadSchema: payloadSchemaOf(ReadPanelInput),
14412
14544
  handle: async (payload, invocation) => {
14413
14545
  const input = decodePanel(payload);
@@ -14421,6 +14553,7 @@ function registerHandbookPanel(ctx, runtime) {
14421
14553
  ctx.command({
14422
14554
  name: "handbookReleases",
14423
14555
  scope: "read",
14556
+ homeOnly: true,
14424
14557
  payloadSchema: payloadSchemaOf(ReadReleasesInput),
14425
14558
  handle: async (payload) => {
14426
14559
  const input = decodeList(payload);
@@ -14479,12 +14612,14 @@ function registerHandbookPanel(ctx, runtime) {
14479
14612
  ctx.command({
14480
14613
  name: "publishHandbook",
14481
14614
  scope: "operate",
14615
+ homeOnly: true,
14482
14616
  payloadSchema: payloadSchemaOf(PublishPanelInput),
14483
14617
  handle: (payload, invocation) => write({ ...decodePublish2(payload), operation: "publish" }, invocation)
14484
14618
  });
14485
14619
  ctx.command({
14486
14620
  name: "revertHandbook",
14487
14621
  scope: "operate",
14622
+ homeOnly: true,
14488
14623
  payloadSchema: payloadSchemaOf(RevertPanelInput),
14489
14624
  handle: (payload, invocation) => write({ ...decodeRevert2(payload), operation: "revert" }, invocation)
14490
14625
  });
@@ -14693,7 +14828,9 @@ function createArchiveMirror(ctx, deps) {
14693
14828
  };
14694
14829
  const reconcile = async (threadId) => {
14695
14830
  const wakes = await deps.wakes.get();
14831
+ const runnable = homeGate(ctx);
14696
14832
  for (const [projectId, project2] of Object.entries(wakes)) {
14833
+ if (!await runnable(projectId)) continue;
14697
14834
  for (const [workLineId, scope2] of Object.entries(project2.lineScopes ?? {})) {
14698
14835
  const leadThreadId = roomOf(scope2);
14699
14836
  if (leadThreadId === void 0) continue;
@@ -14946,8 +15083,10 @@ function createLineChangeRunner(ctx, deps) {
14946
15083
  },
14947
15084
  /** 挂载对账:意图落了、结局没落的这一种改动,用记着的输入接着做。 */
14948
15085
  async reconcile(op, run2) {
15086
+ const runnable = homeGate(ctx);
14949
15087
  for (const record2 of Object.values(await deps.changes.get())) {
14950
15088
  if (record2.completed !== void 0 || record2.intent.op !== op) continue;
15089
+ if (!await runnable(record2.intent.projectId)) continue;
14951
15090
  await finish(record2.intent, run2).catch((error) => {
14952
15091
  if (!(error instanceof TeamRuleError))
14953
15092
  ctx.log.warn("team change could not be finished", {
@@ -15043,7 +15182,10 @@ function startLineNameMirror(ctx, queue) {
15043
15182
  const renamed = decodeRenamed(event.payload);
15044
15183
  if (isNone2(renamed)) return Promise.resolve();
15045
15184
  const { projectId, workLineId } = renamed.value;
15046
- return queue.run(() => syncLineTitle(ctx, projectId, workLineId)).catch(
15185
+ const runnable = homeGate(ctx);
15186
+ return queue.run(async () => {
15187
+ if (await runnable(projectId)) await syncLineTitle(ctx, projectId, workLineId);
15188
+ }).catch(
15047
15189
  (error) => ctx.log.warn("team could not mirror the line name to its conversation title", {
15048
15190
  workLineId,
15049
15191
  error
@@ -15632,12 +15774,14 @@ function registerTeamTools(ctx, deps, queue) {
15632
15774
  tools: [
15633
15775
  {
15634
15776
  name: "open",
15777
+ homeOnly: true,
15635
15778
  description: teamMessage("openTool"),
15636
15779
  inputSchema: toolSchema(TeamOpenInput),
15637
15780
  handle: (input, invocation) => runTool(() => serial(() => opener.open(input, invocation)))
15638
15781
  },
15639
15782
  {
15640
15783
  name: "set_members",
15784
+ homeOnly: true,
15641
15785
  remoteAvailable: true,
15642
15786
  description: teamMessage("setMembersTool"),
15643
15787
  inputSchema: toolSchema(TeamSetMembersInput),
@@ -15645,6 +15789,7 @@ function registerTeamTools(ctx, deps, queue) {
15645
15789
  },
15646
15790
  {
15647
15791
  name: "set_lead",
15792
+ homeOnly: true,
15648
15793
  remoteAvailable: true,
15649
15794
  description: teamMessage("setLeadTool"),
15650
15795
  inputSchema: toolSchema(TeamSetLeadInput),
@@ -15652,6 +15797,7 @@ function registerTeamTools(ctx, deps, queue) {
15652
15797
  },
15653
15798
  {
15654
15799
  name: "roster_overview",
15800
+ homeOnly: true,
15655
15801
  remoteAvailable: true,
15656
15802
  description: teamMessage("rosterOverviewTool"),
15657
15803
  inputSchema: { type: "object", properties: {}, additionalProperties: false },
@@ -15672,17 +15818,19 @@ function registerTeamTools(ctx, deps, queue) {
15672
15818
  }
15673
15819
 
15674
15820
  // src/runtime/followUp.ts
15675
- var SWEEP_MS = 12e4;
15821
+ var SWEEP_MS2 = 12e4;
15676
15822
  var LOG_EVERY_FAILURES = 15;
15677
15823
  function startFollowUp(ctx, options) {
15678
15824
  const queue = createSerial(`${options.name}-closed`);
15679
15825
  ctx.onDispose(queue.close);
15680
15826
  const failures = /* @__PURE__ */ new Map();
15681
15827
  const execute = async (trigger) => {
15828
+ const runnable = homeGate(ctx);
15682
15829
  for (const row of await options.pending(trigger === "sweep" ? void 0 : trigger.through)) {
15683
15830
  const key = options.keyOf(row);
15684
15831
  if (trigger !== "sweep" && trigger.project !== void 0 && trigger.project !== options.projectOf(row))
15685
15832
  continue;
15833
+ if (!await runnable(options.projectOf(row))) continue;
15686
15834
  try {
15687
15835
  if (await options.settle(row) === "settled") failures.delete(key);
15688
15836
  } catch (error) {
@@ -15703,7 +15851,7 @@ function startFollowUp(ctx, options) {
15703
15851
  events: options.events,
15704
15852
  handle: (event) => options.accepts !== void 0 && !options.accepts(event) ? Promise.resolve() : flush({ project: event.aggregateKind === "project" ? event.aggregateId : void 0 })
15705
15853
  });
15706
- ctx.interval({ name: options.name, everyMs: SWEEP_MS, handle: () => flush("sweep") });
15854
+ ctx.interval({ name: options.name, everyMs: SWEEP_MS2, handle: () => flush("sweep") });
15707
15855
  const ready = flush();
15708
15856
  void ready.catch(
15709
15857
  (error) => ctx.log.warn(`${options.name} follow-up catch-up failed`, { error })
@@ -16059,6 +16207,7 @@ function registerLineMemberCommands(ctx, deps) {
16059
16207
  ctx.command({
16060
16208
  name: "lineMembers",
16061
16209
  scope: "read",
16210
+ homeOnly: true,
16062
16211
  payloadSchema: payloadSchemaOf(LineRef),
16063
16212
  handle: async (payload) => {
16064
16213
  const { projectId, workLineId } = decodeRef3(payload);
@@ -16107,6 +16256,7 @@ function registerLineMemberCommands(ctx, deps) {
16107
16256
  ctx.command({
16108
16257
  name,
16109
16258
  scope: "operate",
16259
+ homeOnly: true,
16110
16260
  payloadSchema: payloadSchemaOf(LineMemberInput),
16111
16261
  handle: handler(kind)
16112
16262
  });
@@ -16162,24 +16312,28 @@ function registerPauseCommands(ctx, deps) {
16162
16312
  ctx.command({
16163
16313
  name: "pauseLine",
16164
16314
  scope: "operate",
16315
+ homeOnly: true,
16165
16316
  payloadSchema: payloadSchemaOf(LinePauseInput),
16166
16317
  handle: handler("paused", false)
16167
16318
  });
16168
16319
  ctx.command({
16169
16320
  name: "resumeLine",
16170
16321
  scope: "operate",
16322
+ homeOnly: true,
16171
16323
  payloadSchema: payloadSchemaOf(LinePauseInput),
16172
16324
  handle: handler("resumed", false)
16173
16325
  });
16174
16326
  ctx.command({
16175
16327
  name: "pauseLineMember",
16176
16328
  scope: "operate",
16329
+ homeOnly: true,
16177
16330
  payloadSchema: payloadSchemaOf(LineMemberPauseInput),
16178
16331
  handle: handler("paused", true)
16179
16332
  });
16180
16333
  ctx.command({
16181
16334
  name: "resumeLineMember",
16182
16335
  scope: "operate",
16336
+ homeOnly: true,
16183
16337
  payloadSchema: payloadSchemaOf(LineMemberPauseInput),
16184
16338
  handle: handler("resumed", true)
16185
16339
  });
@@ -16188,7 +16342,10 @@ function registerPauseCommands(ctx, deps) {
16188
16342
  events: ["work.line-restored"],
16189
16343
  handle: (event) => match(decodeRestored(event.payload), {
16190
16344
  onNone: () => Promise.resolve(),
16191
- onSome: ({ projectId, workLineId }) => deps.queue.run(() => backfillLine(ctx, deps.wakes, projectId, workLineId))
16345
+ onSome: ({ projectId, workLineId }) => deps.queue.run(async () => {
16346
+ if (await homeGate(ctx)(projectId))
16347
+ await backfillLine(ctx, deps.wakes, projectId, workLineId);
16348
+ })
16192
16349
  })
16193
16350
  });
16194
16351
  const ready = deps.queue.run(() => backfillLegacyPauses(ctx, deps.wakes));
@@ -16222,7 +16379,9 @@ async function backfillLine(ctx, wakes, projectId, workLineId) {
16222
16379
  }
16223
16380
  async function backfillLegacyPauses(ctx, wakes) {
16224
16381
  const state = await wakes.get();
16382
+ const runnable = homeGate(ctx);
16225
16383
  for (const [projectId, project2] of Object.entries(state)) {
16384
+ if (!await runnable(projectId)) continue;
16226
16385
  const lineIds = /* @__PURE__ */ new Set([
16227
16386
  ...Object.keys(project2.linePauses ?? {}),
16228
16387
  ...Object.keys(project2.pausedMembers ?? {})
@@ -16288,7 +16447,12 @@ var SCAN_PAGES = 5;
16288
16447
  var LINE_MAX = 800;
16289
16448
  var PAGE_SIZE2 = 100;
16290
16449
  var Watermark = Struct({ messageId: String4, createdAt: String4 });
16291
- var RecordWatermark = Struct({ recordId: String4, createdAt: String4 });
16450
+ var RecordWatermark = Struct({
16451
+ recordId: String4,
16452
+ createdAt: String4,
16453
+ // 全局事件序号:合并视图按它排序,水位按它停;没有它的旧水位退回记录号 + 时间戳。
16454
+ sequence: optionalKey2(Number5)
16455
+ });
16292
16456
  var GroupDigestFact = Union2([
16293
16457
  Struct({
16294
16458
  version: Literal2(1),
@@ -16309,10 +16473,58 @@ var GroupDigestFact = Union2([
16309
16473
  projectId: String4,
16310
16474
  threadId: String4,
16311
16475
  digestId: String4
16476
+ }),
16477
+ Struct({
16478
+ version: Literal2(1),
16479
+ status: Literal2("bound"),
16480
+ projectId: String4,
16481
+ threadId: String4,
16482
+ digestId: String4,
16483
+ workItemId: String4,
16484
+ memberId: String4
16312
16485
  })
16313
16486
  ]);
16487
+ var handoverOf = (prepared) => ({
16488
+ digestId: prepared.digestId,
16489
+ projectId: prepared.projectId,
16490
+ ...prepared.upTo === void 0 ? {} : { upTo: prepared.upTo },
16491
+ ...prepared.recordsUpTo === void 0 ? {} : { recordsUpTo: prepared.recordsUpTo }
16492
+ });
16493
+ var handoverKey = (workItemId, memberId) => `${workItemId}
16494
+ ${memberId}`;
16314
16495
  var decode3 = decodeUnknownOption2(factEnvelope("group-digest", GroupDigestFact));
16496
+ var decodeDispatched2 = decodeUnknownOption2(
16497
+ Struct({
16498
+ projectId: String4,
16499
+ workItemId: String4,
16500
+ memberId: String4,
16501
+ threadId: String4
16502
+ })
16503
+ );
16504
+ var withHandovers = (base, bound, dispatched) => ({
16505
+ watermark: base.watermark,
16506
+ recordsWatermark: base.recordsWatermark,
16507
+ prepared: base.prepared,
16508
+ ...bound === void 0 || Object.keys(bound).length === 0 ? {} : { bound },
16509
+ ...dispatched === void 0 || Object.keys(dispatched).length === 0 ? {} : { dispatched }
16510
+ });
16315
16511
  function foldGroupDigests(state, event) {
16512
+ if (event.type === "work.item-dispatched") {
16513
+ const dispatched = decodeDispatched2(event.payload);
16514
+ if (isNone2(dispatched)) return state;
16515
+ const { workItemId, memberId, threadId } = dispatched.value;
16516
+ const known2 = readFact(state, threadId);
16517
+ const id = handoverKey(workItemId, memberId);
16518
+ const handover2 = known2?.bound === void 0 ? null : readFact(known2.bound, id);
16519
+ if (known2 === null || handover2 === null) return state;
16520
+ return {
16521
+ ...state,
16522
+ [threadId]: withHandovers(known2, without(known2.bound, id), {
16523
+ ...known2.dispatched,
16524
+ [handover2.digestId]: handover2
16525
+ })
16526
+ };
16527
+ }
16316
16528
  if (event.type !== "plugin.event-appended") return state;
16317
16529
  const decoded = decode3(event.payload);
16318
16530
  if (isNone2(decoded)) return state;
@@ -16324,20 +16536,40 @@ function foldGroupDigests(state, event) {
16324
16536
  };
16325
16537
  if (fact.status === "prepared")
16326
16538
  return { ...state, [fact.threadId]: { ...known, prepared: fact } };
16327
- if (known.prepared?.digestId !== fact.digestId) return state;
16539
+ if (fact.status === "bound") {
16540
+ if (known.prepared?.digestId !== fact.digestId) return state;
16541
+ return {
16542
+ ...state,
16543
+ [fact.threadId]: {
16544
+ ...known,
16545
+ bound: {
16546
+ ...known.bound,
16547
+ [handoverKey(fact.workItemId, fact.memberId)]: handoverOf(known.prepared)
16548
+ }
16549
+ }
16550
+ };
16551
+ }
16552
+ const handover = known.prepared?.digestId === fact.digestId ? known.prepared : known.dispatched === void 0 ? null : readFact(known.dispatched, fact.digestId);
16553
+ if (handover === null) return state;
16328
16554
  return {
16329
16555
  ...state,
16330
- [fact.threadId]: {
16331
- watermark: known.prepared.upTo ?? known.watermark,
16332
- recordsWatermark: known.prepared.recordsUpTo ?? known.recordsWatermark,
16333
- prepared: null
16334
- }
16556
+ [fact.threadId]: withHandovers(
16557
+ {
16558
+ watermark: handover.upTo ?? known.watermark,
16559
+ recordsWatermark: handover.recordsUpTo ?? known.recordsWatermark,
16560
+ prepared: known.prepared?.digestId === fact.digestId ? null : known.prepared
16561
+ },
16562
+ known.bound === void 0 ? void 0 : Object.fromEntries(
16563
+ Object.entries(known.bound).filter(([, bound]) => bound.digestId !== fact.digestId)
16564
+ ),
16565
+ known.dispatched === void 0 ? void 0 : without(known.dispatched, fact.digestId)
16566
+ )
16335
16567
  };
16336
16568
  }
16337
16569
  var groupDigestStateDefinition = {
16338
16570
  key: "group-digests",
16339
- version: 1,
16340
- events: ["plugin.event-appended"],
16571
+ version: 3,
16572
+ events: ["plugin.event-appended", "work.item-dispatched"],
16341
16573
  init: () => ({}),
16342
16574
  apply: foldGroupDigests
16343
16575
  };
@@ -16388,31 +16620,38 @@ async function scanRecords(ctx, projectId, groupThreadId, watermark, nameOfThrea
16388
16620
  const ids = /* @__PURE__ */ new Set();
16389
16621
  let upTo = null;
16390
16622
  let cursor = null;
16391
- const speakerOf2 = async (from) => {
16392
- if (from.displayName !== void 0) return from.displayName;
16393
- if (from.kind === "thread" && from.threadId !== void 0)
16394
- return await nameOfThread(from.threadId) ?? (from.threadId === groupThreadId ? "Lead" : "Member");
16395
- return "Member";
16396
- };
16623
+ const nameOf2 = async (threadId) => threadId === void 0 ? "Member" : await nameOfThread(threadId) ?? (threadId === groupThreadId ? "Lead" : "Member");
16397
16624
  try {
16398
16625
  for (let page = 0; page < SCAN_PAGES; page++) {
16399
- const result2 = await ctx.records.list({
16626
+ const result2 = await ctx.posts.list({
16400
16627
  projectId,
16401
16628
  groupThreadId,
16402
16629
  limit: PAGE_SIZE2,
16403
16630
  ...cursor === null ? {} : { cursor }
16404
16631
  });
16405
- for (const record2 of result2.items) {
16406
- if (watermark !== null && (record2.recordId === watermark.recordId || record2.createdAt < watermark.createdAt))
16632
+ for (const item of result2.items) {
16633
+ if (item.kind === "comment") continue;
16634
+ const entry = item.kind === "post" ? {
16635
+ recordId: `post:${item.post.postId}`,
16636
+ createdAt: item.post.createdAt,
16637
+ textPreview: item.post.textPreview,
16638
+ speaker: async () => item.post.authorName ?? (item.post.author.kind === "agent" ? await nameOf2(item.post.author.threadId) : item.post.author.kind === "human" ? "Person" : "Member")
16639
+ } : {
16640
+ recordId: item.record.recordId,
16641
+ createdAt: item.record.createdAt,
16642
+ textPreview: item.record.textPreview,
16643
+ speaker: async () => "displayName" in item.record.from ? item.record.from.displayName : item.record.from.kind === "thread" ? await nameOf2(item.record.from.threadId) : "Member"
16644
+ };
16645
+ if (watermark !== null && (watermark.sequence === void 0 ? entry.recordId === watermark.recordId || entry.createdAt < watermark.createdAt : item.sequence <= watermark.sequence))
16407
16646
  return { lines, upTo, more: false, ids };
16408
- ids.add(record2.recordId);
16409
- upTo ??= { recordId: record2.recordId, createdAt: record2.createdAt };
16647
+ ids.add(entry.recordId);
16648
+ upTo ??= { recordId: entry.recordId, createdAt: entry.createdAt, sequence: item.sequence };
16410
16649
  if (lines.length >= DIGEST_LIMIT) return { lines, upTo, more: true, ids };
16411
- const text = record2.textPreview?.trim();
16650
+ const text = entry.textPreview?.trim();
16412
16651
  if (text === void 0 || text === "") continue;
16413
16652
  lines.push({
16414
- at: record2.createdAt,
16415
- text: `${stamp(record2.createdAt)} ${await speakerOf2(record2.from)}: ${text.length > LINE_MAX ? `${text.slice(0, LINE_MAX)}\u2026` : text}`
16653
+ at: entry.createdAt,
16654
+ text: `${stamp(entry.createdAt)} ${await entry.speaker()}: ${text.length > LINE_MAX ? `${text.slice(0, LINE_MAX)}\u2026` : text}`
16416
16655
  });
16417
16656
  }
16418
16657
  cursor = result2.nextCursor;
@@ -16486,16 +16725,40 @@ function createGroupDigest(ctx, state) {
16486
16725
  return { digestId, key, body };
16487
16726
  },
16488
16727
  /**
16489
- * 引擎叫醒了这条会话(看板交件):随那次叫醒补充出去的那一份算已投递,水位前进。没有装配好的就什么也不做。
16728
+ * 这份摘要要随引擎的这一次看板叫醒(件 + 成员)补充出去:叫醒送出之前先记下这层绑定,之后引擎记下的交件
16729
+ * (`work.item-dispatched`,带同一对件与成员)才认得出是哪一份。同一次叫醒重试装配出同一号,命令号相同不重复记。
16490
16730
  */
16491
- async confirmPrepared(projectId, threadId) {
16492
- const prepared = readFact(await state.get(), threadId)?.prepared;
16493
- if (prepared == null) return;
16494
- await this.confirm(projectId, {
16495
- digestId: prepared.digestId,
16496
- key: threadId,
16497
- body: prepared.body
16731
+ async bind(projectId, digest, wake) {
16732
+ const receipt = await ctx.events.append({
16733
+ commandId: `team-group-digest-bound:${digest.digestId}`,
16734
+ name: "group-digest",
16735
+ aggregate: { kind: "project", id: projectId },
16736
+ data: {
16737
+ version: 1,
16738
+ status: "bound",
16739
+ projectId,
16740
+ threadId: digest.key,
16741
+ digestId: digest.digestId,
16742
+ workItemId: wake.workItemId,
16743
+ memberId: wake.memberId
16744
+ }
16498
16745
  });
16746
+ await state.get({ throughSequence: receipt.sequence });
16747
+ },
16748
+ /**
16749
+ * 引擎叫醒了这些会话(看板交件):随那次叫醒补充出去的那一份算已投递,水位前进。待确认的从持久状态里找(装配时
16750
+ * 绑定了这次叫醒、之后看板交过这件、还没确认的),不依赖交件事件被处理那一刻的现场,也不按「同会话最近一次装配」推断;
16751
+ * 家不在本机的项目(`runnable` 为假)留着不确认,读不出家的这一轮也留着,下一轮再来。`throughSequence` 给了就先追到那条事件。
16752
+ */
16753
+ async confirmDispatched(runnable, throughSequence) {
16754
+ const snapshot = await state.get(
16755
+ throughSequence === void 0 ? void 0 : { throughSequence }
16756
+ );
16757
+ for (const [key, member] of Object.entries(snapshot))
16758
+ for (const handover of Object.values(member.dispatched ?? {})) {
16759
+ if (!await runnable(handover.projectId)) continue;
16760
+ await this.confirm(handover.projectId, { digestId: handover.digestId, key });
16761
+ }
16499
16762
  },
16500
16763
  /** 叫醒已被宿主受理:水位前进。同一份只落一次。 */
16501
16764
  async confirm(projectId, digest) {
@@ -16955,6 +17218,18 @@ var zh_CN_default = {
16955
17218
  trial_started: "\u5F00\u59CB\u8BD5\u8DD1",
16956
17219
  trial_done: "\u5B8C\u6210\u8BD5\u8DD1",
16957
17220
  retry_trial: "\u91CD\u8BD5\u8BD5\u8DD1"
17221
+ },
17222
+ runtime: {
17223
+ status: {
17224
+ working: "\u5728\u5E72\u6D3B",
17225
+ attention: "\u7B49\u4F60\u5904\u7406",
17226
+ failed: "\u51FA\u9519",
17227
+ idle: "\u7A7A\u95F2",
17228
+ stopped: "\u5DF2\u505C\u6B62"
17229
+ },
17230
+ none: "\u8FD8\u6CA1\u6536\u5230\u72B6\u6001",
17231
+ offline: "\u79BB\u7EBF\uFF0C\u6700\u540E\u89C1\u4E8E {{time}}",
17232
+ stale: "\u72B6\u6001\u5DF2\u8FC7\u671F"
16958
17233
  }
16959
17234
  };
16960
17235
 
@@ -17005,6 +17280,7 @@ function registerTrial(ctx, runtime) {
17005
17280
  tools: [
17006
17281
  {
17007
17282
  name: "trial_started",
17283
+ homeOnly: true,
17008
17284
  remoteAvailable: true,
17009
17285
  description: trialMessage("startedTool"),
17010
17286
  inputSchema: toolSchema(TrialStartedInput),
@@ -17012,6 +17288,7 @@ function registerTrial(ctx, runtime) {
17012
17288
  },
17013
17289
  {
17014
17290
  name: "trial_done",
17291
+ homeOnly: true,
17015
17292
  remoteAvailable: true,
17016
17293
  description: trialMessage("doneTool"),
17017
17294
  inputSchema: toolSchema(TrialDoneInput),
@@ -17022,6 +17299,7 @@ function registerTrial(ctx, runtime) {
17022
17299
  },
17023
17300
  {
17024
17301
  name: "retry_trial",
17302
+ homeOnly: true,
17025
17303
  remoteAvailable: true,
17026
17304
  description: trialMessage("retryTool"),
17027
17305
  inputSchema: toolSchema(RetryTrialToolInput),
@@ -17033,12 +17311,14 @@ function registerTrial(ctx, runtime) {
17033
17311
  ctx.command({
17034
17312
  name: "retryTrial",
17035
17313
  scope: "operate",
17314
+ homeOnly: true,
17036
17315
  payloadSchema: payloadSchemaOf(RetryTrialInput),
17037
17316
  handle: (payload, invocation) => runtime.commands.retry(payload, invocation)
17038
17317
  });
17039
17318
  ctx.command({
17040
17319
  name: "skipTrial",
17041
17320
  scope: "operate",
17321
+ homeOnly: true,
17042
17322
  payloadSchema: payloadSchemaOf(SkipTrialInput),
17043
17323
  handle: (payload, invocation) => runtime.commands.skip(payload, invocation)
17044
17324
  });
@@ -17096,7 +17376,9 @@ function startTrialMirror(ctx, deps) {
17096
17376
  });
17097
17377
  projects.set(record2.projectId, rows);
17098
17378
  }
17379
+ const runnable = homeGate(ctx);
17099
17380
  for (const [projectId, rows] of projects) {
17381
+ if (!await runnable(projectId)) continue;
17100
17382
  try {
17101
17383
  const members = await readPages(
17102
17384
  MEMBER_LIMIT2,
@@ -17333,6 +17615,48 @@ async function closeSession(env, session, interrupt2) {
17333
17615
  return true;
17334
17616
  }
17335
17617
 
17618
+ // src/trial/occupancy.ts
17619
+ var IN_FLIGHT_INTENTS = /* @__PURE__ */ new Set(["preparing", "dispatching", "running", "reconciling"]);
17620
+ var stillOccupies = (execution) => execution.providerProcessLive || execution.session !== null && (execution.session.activeTurnId !== null || execution.session.status === "running" || execution.session.status === "starting") || execution.turnIntents.some(
17621
+ (intent) => IN_FLIGHT_INTENTS.has(intent.status) || intent.status === "queued" && execution.archivedAt === null
17622
+ );
17623
+ async function occupiedSessions(ctx, state, verdictOf, released) {
17624
+ const stale = new Map(staleSessions(state).map((row) => [row.threadId, row]));
17625
+ let occupied = 0;
17626
+ for (const [threadId, { projectId }] of Object.entries(state.sessions)) {
17627
+ if (await verdictOf(projectId) !== "elsewhere") {
17628
+ const row = stale.get(threadId);
17629
+ if (row === void 0 || row.finishing) occupied += 1;
17630
+ continue;
17631
+ }
17632
+ if (released.has(threadId)) continue;
17633
+ const execution = await ctx.projections.getThreadExecution(threadId).catch(() => void 0);
17634
+ if (execution === void 0 || execution !== null && stillOccupies(execution)) occupied += 1;
17635
+ else released.add(threadId);
17636
+ }
17637
+ return occupied;
17638
+ }
17639
+ async function tearDownAwaySessions(ctx, state, verdictOf, done2) {
17640
+ for (const [threadId, { projectId }] of Object.entries(state.sessions)) {
17641
+ if (done2.has(threadId) || await verdictOf(projectId) !== "elsewhere") continue;
17642
+ try {
17643
+ const execution = await ctx.projections.getThreadExecution(threadId);
17644
+ if (execution === null || execution.archivedAt !== null && !execution.providerProcessLive) {
17645
+ done2.add(threadId);
17646
+ continue;
17647
+ }
17648
+ if (execution.archivedAt !== null) continue;
17649
+ await ctx.threads.session.stop({ threadId }).catch(() => void 0);
17650
+ await ctx.threads.archive({
17651
+ threadId,
17652
+ requestId: `team-trial-archive:${stableHash(threadId)}`
17653
+ });
17654
+ } catch (error) {
17655
+ ctx.log.warn("team trial session away from home could not be closed", { threadId, error });
17656
+ }
17657
+ }
17658
+ }
17659
+
17336
17660
  // src/trial/notices.ts
17337
17661
  var nameOf = async (env, record2) => (await findMember(env.ctx, record2.projectId, record2.memberId, { textLimit: 2 }))?.name ?? record2.memberId;
17338
17662
  var leadRow = (goal) => goal.threads.find((row) => row.memberId === goal.leadMemberId);
@@ -17438,8 +17762,9 @@ function waitingWording(machine) {
17438
17762
  machine: machine.name
17439
17763
  };
17440
17764
  }
17441
- async function tellWaiting(env, waiting, ledger) {
17442
- for (const fact of ledger.unrecorded.values()) await recordTold(env, ledger, fact);
17765
+ async function tellWaiting(env, waiting, ledger, runnable) {
17766
+ for (const fact of ledger.unrecorded.values())
17767
+ if (await runnable(fact.projectId)) await recordTold(env, ledger, fact);
17443
17768
  const { settled } = ledger;
17444
17769
  const groups = /* @__PURE__ */ new Map();
17445
17770
  for (const row of waiting) {
@@ -17584,6 +17909,8 @@ function startTrialRuntime(ctx, deps, options = {}) {
17584
17909
  const failureTold = /* @__PURE__ */ new Set();
17585
17910
  const waitingSettled = waitingLedger();
17586
17911
  const readyTold = /* @__PURE__ */ new Set();
17912
+ const awayClosed = /* @__PURE__ */ new Set();
17913
+ const awayReleased = /* @__PURE__ */ new Set();
17587
17914
  const append2 = async (name, key, data) => {
17588
17915
  const project2 = data.projectId;
17589
17916
  const receipt = await ctx.events.append({
@@ -17612,6 +17939,17 @@ function startTrialRuntime(ctx, deps, options = {}) {
17612
17939
  };
17613
17940
  const clock = async () => Date.parse(await now3());
17614
17941
  const env = { ctx, deps, append: append2, fail: fail6, stumble, clock };
17942
+ const failIfSessionErrored = async (record2) => {
17943
+ if (record2.route !== "local" || record2.threadId === void 0) return "clear";
17944
+ const session = (await ctx.projections.getThreadExecution(record2.threadId))?.session;
17945
+ if (session?.status !== "error") return "clear";
17946
+ await fail6(
17947
+ record2,
17948
+ session.failureCategory ?? "unknown",
17949
+ summarizeError(session.lastError ?? "", "")
17950
+ );
17951
+ return "failed";
17952
+ };
17615
17953
  let mountedAt;
17616
17954
  const resumedAt = /* @__PURE__ */ new Map();
17617
17955
  const pausedNow = /* @__PURE__ */ new Set();
@@ -17623,8 +17961,9 @@ function startTrialRuntime(ctx, deps, options = {}) {
17623
17961
  if (pausedNow.delete(projectId)) resumedAt.set(projectId, at);
17624
17962
  return false;
17625
17963
  };
17626
- const sweep = async (snapshot, at, mounted, gone) => {
17964
+ const sweep = async (snapshot, at, mounted, gone, runnable, undecided) => {
17627
17965
  for (const record2 of runningTrials(snapshot)) {
17966
+ if (!await runnable(record2.projectId)) continue;
17628
17967
  if (await pausedProject(record2.projectId, at, gone)) continue;
17629
17968
  const since = record2.route === "remote" ? record2.phase === "started" ? record2.startedAt : void 0 : record2.dispatchedAt;
17630
17969
  const limit = record2.route === "remote" ? remoteTimeout : localTimeout;
@@ -17639,6 +17978,7 @@ function startTrialRuntime(ctx, deps, options = {}) {
17639
17978
  queuedFor = capacity.waitedWithin(record2.threadId, start, at);
17640
17979
  }
17641
17980
  if (since !== void 0 && at - start - queuedFor > limit) {
17981
+ if (undecided.has(trialIdOfRecord(record2)) && at - start - queuedFor <= 2 * limit) continue;
17642
17982
  const trouble = ensured.has(trialIdOfRecord(record2)) ? void 0 : stuck.get(trialIdOfRecord(record2));
17643
17983
  await (trouble === void 0 ? fail6(record2, "timeout", "") : fail6(record2, "start-failed", trouble.reason)).catch(
17644
17984
  (error) => ctx.log.warn("team trial timeout could not be recorded", { error })
@@ -17653,15 +17993,18 @@ function startTrialRuntime(ctx, deps, options = {}) {
17653
17993
  mountedAt ??= at;
17654
17994
  tickAt = at;
17655
17995
  const gone = projectGone(ctx);
17996
+ const verdictOf = projectHomeVerdicts(ctx);
17997
+ const runnable = async (projectId) => await verdictOf(projectId) === "here";
17656
17998
  let snapshot = await state.get();
17657
17999
  for (const record2 of Object.values(snapshot.members)) {
17658
- if (record2.removed) continue;
18000
+ if (record2.removed || !await runnable(record2.projectId)) continue;
17659
18001
  if (record2.phase === "failed")
17660
18002
  await tellFailure(env, record2, failureTold).catch(guard("notice"));
17661
18003
  else if (isReady(record2))
17662
18004
  await tellReady(env, record2, readyTold).catch(guard("ready notice"));
17663
18005
  }
17664
18006
  for (const session of staleSessions(snapshot)) {
18007
+ if (!await runnable(session.projectId)) continue;
17665
18008
  const since = finishingSince.get(session.threadId) ?? at;
17666
18009
  if (session.finishing) finishingSince.set(session.threadId, since);
17667
18010
  const closed = await closeSession(env, session, at - since >= closeGrace).catch(
@@ -17669,10 +18012,21 @@ function startTrialRuntime(ctx, deps, options = {}) {
17669
18012
  );
17670
18013
  if (closed === true) finishingSince.delete(session.threadId);
17671
18014
  }
18015
+ await tearDownAwaySessions(ctx, snapshot, verdictOf, awayClosed);
18016
+ snapshot = await state.get();
18017
+ const undecided = /* @__PURE__ */ new Set();
18018
+ for (const record2 of runningTrials(snapshot)) {
18019
+ if (!await runnable(record2.projectId)) continue;
18020
+ await failIfSessionErrored(record2).catch((error) => {
18021
+ guard("session error check")(error);
18022
+ undecided.add(trialIdOfRecord(record2));
18023
+ });
18024
+ }
17672
18025
  snapshot = await state.get();
17673
- await sweep(snapshot, at, mountedAt, gone);
18026
+ await sweep(snapshot, at, mountedAt, gone, runnable, undecided);
17674
18027
  snapshot = await state.get();
17675
18028
  for (const record2 of runningTrials(snapshot)) {
18029
+ if (!await runnable(record2.projectId)) continue;
17676
18030
  if (await pausedProject(record2.projectId, at, gone)) continue;
17677
18031
  await ensureSession(env, record2, ensured).catch((error) => {
17678
18032
  guard("send")(error);
@@ -17680,8 +18034,11 @@ function startTrialRuntime(ctx, deps, options = {}) {
17680
18034
  });
17681
18035
  }
17682
18036
  snapshot = await state.get();
17683
- const slots = { local: concurrency - occupiedSessions(snapshot) };
18037
+ const slots = {
18038
+ local: concurrency - await occupiedSessions(ctx, snapshot, verdictOf, awayReleased)
18039
+ };
17684
18040
  for (const record2 of pendingTrials(snapshot)) {
18041
+ if (!await runnable(record2.projectId)) continue;
17685
18042
  if (await pausedProject(record2.projectId, at, gone)) continue;
17686
18043
  const outcome = await dispatchTrial(env, record2, slots, ensured).catch((error) => {
17687
18044
  guard("dispatch")(error);
@@ -17697,13 +18054,19 @@ function startTrialRuntime(ctx, deps, options = {}) {
17697
18054
  );
17698
18055
  for (const record2 of [...pendingTrials(snapshot), ...unsent]) {
17699
18056
  const id = trialIdOfRecord(record2);
18057
+ if (!await runnable(record2.projectId)) {
18058
+ stuck.delete(id);
18059
+ continue;
18060
+ }
17700
18061
  if (await pausedProject(record2.projectId, at, gone)) {
17701
18062
  stuck.delete(id);
17702
18063
  continue;
17703
18064
  }
17704
18065
  const trouble = stuck.get(id);
17705
- if (trouble !== void 0 && at - trouble.since > pendingLimit)
18066
+ if (trouble !== void 0 && at - trouble.since > pendingLimit) {
18067
+ if (undecided.has(id) && at - trouble.since <= 2 * pendingLimit) continue;
17706
18068
  await fail6(record2, "start-failed", trouble.reason).catch(guard("pending timeout"));
18069
+ }
17707
18070
  }
17708
18071
  const open = new Set(
17709
18072
  [...pendingTrials(snapshot), ...runningTrials(snapshot)].map(trialIdOfRecord)
@@ -17714,10 +18077,11 @@ function startTrialRuntime(ctx, deps, options = {}) {
17714
18077
  const since = ensured.get(trialIdOfRecord(record2));
17715
18078
  if (record2.route !== "remote" || record2.phase !== "dispatched" || since === void 0)
17716
18079
  continue;
18080
+ if (!await runnable(record2.projectId)) continue;
17717
18081
  if (at - since >= waitingNotice)
17718
18082
  waiting.push({ record: record2, minutes: Math.floor((at - since) / 6e4) });
17719
18083
  }
17720
- await tellWaiting(env, waiting, waitingSettled).catch(guard("waiting notice"));
18084
+ await tellWaiting(env, waiting, waitingSettled, runnable).catch(guard("waiting notice"));
17721
18085
  };
17722
18086
  const flush = () => serial(execute);
17723
18087
  const failOnSessionError = (event) => serial(async () => {
@@ -17725,7 +18089,8 @@ function startTrialRuntime(ctx, deps, options = {}) {
17725
18089
  if (isNone2(decoded) || decoded.value.session.status !== "error") return;
17726
18090
  const { threadId, session } = decoded.value;
17727
18091
  const record2 = runningTrials(await state.get()).find((row) => row.threadId === threadId);
17728
- if (record2 === void 0) return;
18092
+ if (record2 === void 0 || await projectHomeVerdicts(ctx)(record2.projectId) !== "here")
18093
+ return;
17729
18094
  await fail6(
17730
18095
  record2,
17731
18096
  session.failureCategory ?? "unknown",
@@ -17888,6 +18253,7 @@ var index_default = definePlugin({
17888
18253
  const memberQueue = createSerial("team-members-closed");
17889
18254
  ctx.onDispose(memberQueue.close);
17890
18255
  registerMemberCommands(ctx, rosters, createMemberWriter(ctx, rosters, memberQueue), trialState);
18256
+ registerMemberRuntimeStream(ctx);
17891
18257
  const goals = createGoalService(ctx, rosters, {
17892
18258
  memberTrial: async (projectId, memberId) => {
17893
18259
  const record2 = recordOf(await trialState.get(), projectId, memberId);