@capybara-hq/kernel 0.1.0-rc.109 → 0.1.0-rc.110

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.
Files changed (51) hide show
  1. package/dist/admin/admin.schemas.d.ts +3 -0
  2. package/dist/background/wake-rules.js +2 -0
  3. package/dist/conversations/conversations.service.js +4 -2
  4. package/dist/conversations/event-log.js +11 -1
  5. package/dist/conversations/events.d.ts +5 -0
  6. package/dist/conversations/events.js +11 -2
  7. package/dist/conversations/prompt-suggestion-store.d.ts +3 -1
  8. package/dist/conversations/prompt-suggestion-store.js +5 -1
  9. package/dist/db/kernel-schema.d.ts +7 -0
  10. package/dist/identity/accounts.d.ts +8 -9
  11. package/dist/identity/accounts.js +18 -3
  12. package/dist/identity/me.controller.d.ts +4 -2
  13. package/dist/identity/me.controller.js +4 -2
  14. package/dist/identity/me.schemas.d.ts +3 -0
  15. package/dist/identity/me.schemas.js +5 -0
  16. package/dist/identity/settings.d.ts +15 -0
  17. package/dist/identity/settings.js +12 -0
  18. package/dist/infra/outbox/registry.d.ts +14 -0
  19. package/dist/infra/outbox/registry.js +14 -0
  20. package/dist/orgs/settings.service.d.ts +6 -0
  21. package/dist/platform/ops/org-settings.ops.js +1 -1
  22. package/dist/platform/ops/platform.ops.js +9 -3
  23. package/dist/push/recipients.js +4 -2
  24. package/dist/runtime/abort.d.ts +22 -3
  25. package/dist/runtime/abort.js +37 -17
  26. package/dist/runtime/compaction.service.d.ts +43 -12
  27. package/dist/runtime/compaction.service.js +60 -16
  28. package/dist/runtime/context/idle-compaction-rules.d.ts +94 -0
  29. package/dist/runtime/context/idle-compaction-rules.js +84 -0
  30. package/dist/runtime/idle-arm.d.ts +38 -0
  31. package/dist/runtime/idle-arm.js +269 -0
  32. package/dist/runtime/idle-compaction-jobs.d.ts +25 -0
  33. package/dist/runtime/idle-compaction-jobs.js +21 -0
  34. package/dist/runtime/idle-compaction.d.ts +43 -0
  35. package/dist/runtime/idle-compaction.js +316 -0
  36. package/dist/runtime/idle-return.d.ts +62 -0
  37. package/dist/runtime/idle-return.js +170 -0
  38. package/dist/runtime/maintenance.d.ts +5 -2
  39. package/dist/runtime/maintenance.js +14 -4
  40. package/dist/runtime/model-call.d.ts +113 -5
  41. package/dist/runtime/model-call.js +119 -71
  42. package/dist/runtime/run-finish.d.ts +16 -1
  43. package/dist/runtime/run-finish.js +27 -4
  44. package/dist/runtime/run-queue.d.ts +56 -2
  45. package/dist/runtime/run-queue.js +257 -8
  46. package/dist/runtime/run-worker.d.ts +22 -8
  47. package/dist/runtime/run-worker.js +75 -28
  48. package/dist/runtime/runtime.module.js +11 -0
  49. package/dist/runtime/waits.js +1 -1
  50. package/package.json +1 -1
  51. package/src/migrations/0195_idle_compaction.sql +7 -0
@@ -841,50 +841,14 @@ async function inContextSummary(deps, input, events, ref, info, tools, settings,
841
841
  }
842
842
  }
843
843
  /**
844
- * Compaction: summarize the earlier conversation with the main model (consumed non-streaming) when
845
- * the calibrated estimate crosses the trigger (context compaction spec §4.1). The hard line
846
- * (`estimate + output > window`) ignores `enabled: false` and the failure backoff; the proactive
847
- * trigger respects both. Accepted → `compaction_summary`; too short or an error →
848
- * `compaction_failed` (attempt from 1, consecutive failures increment), and the step continues
849
- * unchanged. When the main model cannot be resolved right now, compaction is skipped and the
850
- * fallback ladder handles the step.
851
- *
852
- * `opts.force` (the reactive path, spec §4.4, and a manual compact run, spec §4.7) bypasses the
853
- * trigger, `enabled` and the backoff, and `opts.ref` makes it summarise with the rung's model rather
854
- * than the agent's main model.
855
- *
856
- * The one execution both paths run: the automatic step path through {@link maybeCompact} and a
857
- * manual compact run through `CompactionService.force`.
844
+ * The preparation of one compaction (idle compaction spec §4.3): resolve the model, load the media,
845
+ * build the next step's request and calibrate its estimate, apply the trigger and the backoff (unless
846
+ * `opts.force`), plan, and build the in-context summary request ({@link inContextSummary}). It writes
847
+ * nothing and sends no model call; the outcomes a manual compaction records (`compaction_skipped`,
848
+ * `compaction_failed` for an unavailable model) are {@link runCompaction}'s. `hooks.planned` runs once
849
+ * the plan exists, before the in-context build reads the live snapshot.
858
850
  */
859
- export async function runCompaction(deps, input, events, runtime, compaction, tools, opts = {}) {
860
- /** Nothing was written (the compaction was skipped): the step's own path just continues. */
861
- const skipped = (evs) => ({
862
- events: evs,
863
- summarySeq: null,
864
- failed: false,
865
- });
866
- /**
867
- * A manual compact run's early end that the automatic paths keep silent: recorded as its
868
- * outcome (`compaction_failed` with a fixed reason), else just skipped.
869
- */
870
- const unavailable = async (reason) => {
871
- if (opts.manual !== true)
872
- return skipped(events);
873
- const written = await appendCounted(deps, input, [
874
- {
875
- type: "compaction_failed",
876
- runId: input.runId,
877
- idemKey: idem.compactionFailed(input.runId, input.step, compactionOrdinal(events, input.runId, input.step)),
878
- payload: {
879
- attempt: consecutiveCompactionFailures(events) + 1,
880
- step: input.step,
881
- reason,
882
- },
883
- },
884
- ]);
885
- const merged = await mergeWritten(deps.eventLog, input.conversationId, events, written);
886
- return { events: merged, summarySeq: null, failed: true };
887
- };
851
+ export async function prepareCompaction(deps, input, events, runtime, compaction, tools, opts = {}, hooks = {}) {
888
852
  const modelRef = opts.ref ?? input.agent.model;
889
853
  let provider;
890
854
  let info;
@@ -893,7 +857,7 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
893
857
  }
894
858
  catch (err) {
895
859
  deps.log.warn("compaction skipped: model unavailable", { model: modelRef, err });
896
- return unavailable("the model is unavailable");
860
+ return { skipped: "unavailable", reason: "the model is unavailable" };
897
861
  }
898
862
  const limits = mediaLimits(deps);
899
863
  try {
@@ -908,7 +872,7 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
908
872
  conversationId: input.conversationId,
909
873
  err,
910
874
  });
911
- return unavailable("attachment storage is unavailable");
875
+ return { skipped: "unavailable", reason: "attachment storage is unavailable" };
912
876
  }
913
877
  const { request: built, estimate: raw } = buildRequest(limits, events, input, info, attemptParams(input.agent, info, opts.fallback === true).value, runtime, tools, false);
914
878
  const estimate = calibrate(raw, lastActual(events));
@@ -922,9 +886,9 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
922
886
  // (`force`) ignores the trigger entirely (spec §4.4).
923
887
  if (!opts.force) {
924
888
  if (estimate + bounds.output <= info.contextWindow && compactionBackoff(events))
925
- return skipped(events);
889
+ return { skipped: "backoff" };
926
890
  if (!shouldCompact(estimate, info.contextWindow, { ...compaction, maxOutputTokens: output })) {
927
- return skipped(events);
891
+ return { skipped: "trigger" };
928
892
  }
929
893
  }
930
894
  // the input room left for the kept tail: the planning target `W - O_p - R_p`, minus the system
@@ -940,8 +904,102 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
940
904
  manual: true,
941
905
  })
942
906
  : compactionPlan(events, compaction, tailBudget);
943
- if (!plan) {
944
- if (!manual)
907
+ if (!plan)
908
+ return { skipped: "no_plan", estimate, window: info.contextWindow };
909
+ hooks.planned?.();
910
+ // the summary call's output cap: the org's effective setting, never above the model's own cap
911
+ // (context compaction spec §4.8)
912
+ const summaryCap = Math.min(compaction.maxOutputTokens, info.maxOutputTokens);
913
+ // idle compaction spec §9.4: an automatic compaction tries the summary from the conversation's
914
+ // last request first (its cached prefix); a skip (always for a manual one, ruling R13)
915
+ // summarizes the transcript exactly as before, or ends an idle one (`requireInContext`)
916
+ const inContext = await inContextSummary(deps, input, events, modelRef, info, tools, { reserveTokens: compaction.reserveTokens, summaryCap }, plan, opts);
917
+ return {
918
+ provider,
919
+ info,
920
+ ref: modelRef,
921
+ estimate,
922
+ window: info.contextWindow,
923
+ growthTokens: textTokens(plan.transcript),
924
+ plan,
925
+ manual,
926
+ summaryCap,
927
+ inContext,
928
+ };
929
+ }
930
+ /**
931
+ * Compaction: summarize the earlier conversation with the main model (consumed non-streaming) when
932
+ * the calibrated estimate crosses the trigger (context compaction spec §4.1). The hard line
933
+ * (`estimate + output > window`) ignores `enabled: false` and the failure backoff; the proactive
934
+ * trigger respects both. Accepted → `compaction_summary`; too short or an error →
935
+ * `compaction_failed` (attempt from 1, consecutive failures increment), and the step continues
936
+ * unchanged. When the main model cannot be resolved right now, compaction is skipped and the
937
+ * fallback ladder handles the step.
938
+ *
939
+ * `opts.force` (the reactive path, spec §4.4, and a manual compact run, spec §4.7) bypasses the
940
+ * trigger, `enabled` and the backoff, and `opts.ref` makes it summarise with the rung's model rather
941
+ * than the agent's main model. `opts.requireInContext` (the idle compact run, idle compaction spec
942
+ * §4.3) ends the compaction with nothing written when the in-context summary does not apply.
943
+ *
944
+ * The one execution every path runs: the automatic step path through {@link maybeCompact} and a
945
+ * compact run (manual or idle) through `CompactionService.force`. The preparation is
946
+ * {@link prepareCompaction}; this adds the outcomes a manual run records and the call part.
947
+ */
948
+ export async function runCompaction(deps, input, events, runtime, compaction, tools, opts = {}) {
949
+ /** Nothing was written (the compaction was skipped): the step's own path just continues. */
950
+ const skipped = (evs) => ({
951
+ events: evs,
952
+ summarySeq: null,
953
+ failed: false,
954
+ });
955
+ /**
956
+ * A manual compact run's early end that the automatic paths keep silent: recorded as its
957
+ * outcome (`compaction_failed` with a fixed reason), else just skipped.
958
+ */
959
+ const unavailable = async (reason) => {
960
+ if (opts.manual !== true)
961
+ return skipped(events);
962
+ const written = await appendCounted(deps, input, [
963
+ {
964
+ type: "compaction_failed",
965
+ runId: input.runId,
966
+ idemKey: idem.compactionFailed(input.runId, input.step, compactionOrdinal(events, input.runId, input.step)),
967
+ payload: {
968
+ attempt: consecutiveCompactionFailures(events) + 1,
969
+ step: input.step,
970
+ reason,
971
+ },
972
+ },
973
+ ]);
974
+ const merged = await mergeWritten(deps.eventLog, input.conversationId, events, written);
975
+ return { events: merged, summarySeq: null, failed: true };
976
+ };
977
+ // §4.6 progress: from the plan on the compaction is certain, so the conversation may show a row.
978
+ // It is display-only (Redis + a bus message, never the log); a lost update costs nothing. An idle
979
+ // compaction is certain only once its in-context request exists, so it shows the row after it.
980
+ let startedAt = 0;
981
+ const progressOf = (progress) => {
982
+ deps.compactionProgress?.update({
983
+ runId: input.runId,
984
+ conversationId: input.conversationId,
985
+ ...(input.agentId !== undefined && { agentId: input.agentId }),
986
+ progress,
987
+ });
988
+ };
989
+ const preparing = () => {
990
+ startedAt = Date.now();
991
+ progressOf({ phase: "preparing", step: input.step, startedAt });
992
+ };
993
+ const prepared = await prepareCompaction(deps, input, events, runtime, compaction, tools, opts, {
994
+ planned: () => {
995
+ if (opts.requireInContext !== true)
996
+ preparing();
997
+ },
998
+ });
999
+ if ("skipped" in prepared) {
1000
+ if (prepared.skipped === "unavailable")
1001
+ return unavailable(prepared.reason);
1002
+ if (prepared.skipped !== "no_plan" || opts.manual !== true)
945
1003
  return skipped(events);
946
1004
  // a manual compaction that finds nothing to summarize says so (display only, never
947
1005
  // model-visible): nothing precedes the kept tail
@@ -963,35 +1021,25 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
963
1021
  failed: false,
964
1022
  };
965
1023
  }
966
- const { runId, step, signal, conversationId } = input;
967
- const ref = modelRef;
968
- // §4.6 progress: from here the compaction is certain, so the conversation may show a row. It is
969
- // display-only (Redis + a bus message, never the log); a lost update costs nothing.
970
- const startedAt = Date.now();
971
- const progressOf = (progress) => {
972
- deps.compactionProgress?.update({
973
- runId,
974
- conversationId,
975
- ...(input.agentId !== undefined && { agentId: input.agentId }),
976
- progress,
977
- });
978
- };
979
- progressOf({ phase: "preparing", step, startedAt });
980
- // the summary call's output cap: the org's effective setting, never above the model's own cap
981
- // (context compaction spec §4.8)
982
- const summaryCap = Math.min(compaction.maxOutputTokens, info.maxOutputTokens);
983
- // idle compaction spec §9.4: an automatic compaction tries the summary from the conversation's
984
- // last request first (its cached prefix); a skip (always for a manual one, ruling R13)
985
- // summarizes the transcript exactly as before
986
- const inContext = await inContextSummary(deps, input, events, modelRef, info, tools, { reserveTokens: compaction.reserveTokens, summaryCap }, plan, opts);
1024
+ const { provider, info, plan, manual, summaryCap, inContext } = prepared;
1025
+ const modelRef = prepared.ref;
987
1026
  const ic = "skip" in inContext ? null : inContext;
988
1027
  if ("skip" in inContext) {
989
1028
  deps.log.debug?.("in-context summary skipped", {
990
1029
  context: "Compaction",
991
- conversationId,
1030
+ conversationId: input.conversationId,
992
1031
  reason: inContext.skip,
993
1032
  });
1033
+ // the idle compact run never falls back to the transcript request (idle compaction spec
1034
+ // §4.3 check 9): it ends with nothing written
1035
+ if (opts.requireInContext === true)
1036
+ return skipped(events);
994
1037
  }
1038
+ else if (opts.requireInContext === true) {
1039
+ preparing();
1040
+ }
1041
+ const { runId, step, signal, conversationId } = input;
1042
+ const ref = modelRef;
995
1043
  // review M6: the preparation awaited the snapshot read; an abort meanwhile sends no call
996
1044
  if (signal.aborted) {
997
1045
  deps.compactionProgress?.clear(runId);
@@ -20,6 +20,20 @@ export interface FinishRunArgs {
20
20
  * 超时(max_duration)传 false:loop 没吸收的消息没有被回复,必须留给下一轮(R34)。
21
21
  */
22
22
  floorToTrigger?: boolean;
23
+ /**
24
+ * The idle compaction intent of a chat run that passed the arm decision (idle compaction spec
25
+ * §4.2, S4): computed by the run worker before the finish, outside any transaction
26
+ * (`IdleArm.decide`). The `idle-compaction` job is owed only when this call writes the terminal
27
+ * event, with `armedSeq` = that event's seq.
28
+ */
29
+ idleCompaction?: IdleCompactionIntent;
30
+ }
31
+ /** What {@link FinishRunArgs.idleCompaction} carries (`runAt` and `expiresAt` in epoch ms). */
32
+ export interface IdleCompactionIntent {
33
+ orgId: string;
34
+ cacheCallSeq: number;
35
+ expiresAt: number;
36
+ runAt: number;
23
37
  }
24
38
  /**
25
39
  * Writes runs' terminal states (one instance; the run worker, the run queue's orphan abort, the
@@ -52,7 +66,8 @@ export declare class RunFinish {
52
66
  questions: Pick<QuestionsService, "cancelPendingIn">);
53
67
  /**
54
68
  * 在调用方的事务内写运行的终态:会话行锁 → 运行仍未结束才写终态事件、推进 `consumed_seq`、更新 `runs.status`。
55
- * It also owes the conversation's ensure-run backstop under the terminal event's seq.
69
+ * It also owes the conversation's ensure-run backstop under the terminal event's seq, and the
70
+ * `idle-compaction` job when the caller passed an armed intent (`idleCompaction`).
56
71
  *
57
72
  * A finished run waits on nothing: its pending approvals and input requests (one asked just
58
73
  * before the run failed, while it was still `running`) are cancelled before its terminal event
@@ -21,6 +21,7 @@ import { Transactional } from "../infra/database/transactional.decorator.js";
21
21
  import { OutboxService } from "../infra/outbox/outbox.service.js";
22
22
  import { ApprovalsService } from "../tools/approvals.service.js";
23
23
  import { QuestionsService } from "../tools/questions.service.js";
24
+ import { oweIdleCompaction } from "./idle-compaction-jobs.js";
24
25
  import { ACTIVE_RUN_STATUSES, lockWaitRowsIn, oweEnsureRun, TERMINAL_STATUSES, } from "./run-jobs.js";
25
26
  import { isLive } from "./run-liveness.js";
26
27
  import { pairStoppedForks } from "./subagents/skill-fork.js";
@@ -60,7 +61,8 @@ let RunFinish = class RunFinish {
60
61
  }
61
62
  /**
62
63
  * 在调用方的事务内写运行的终态:会话行锁 → 运行仍未结束才写终态事件、推进 `consumed_seq`、更新 `runs.status`。
63
- * It also owes the conversation's ensure-run backstop under the terminal event's seq.
64
+ * It also owes the conversation's ensure-run backstop under the terminal event's seq, and the
65
+ * `idle-compaction` job when the caller passed an armed intent (`idleCompaction`).
64
66
  *
65
67
  * A finished run waits on nothing: its pending approvals and input requests (one asked just
66
68
  * before the run failed, while it was still `running`) are cancelled before its terminal event
@@ -111,7 +113,7 @@ let RunFinish = class RunFinish {
111
113
  const pending = await lockWaitRowsIn(t, a.runId);
112
114
  const run = await t
113
115
  .selectFrom("runs")
114
- .select(["status", "agent_version", "trigger_account_id", "compact"])
116
+ .select(["status", "agent_version", "trigger_account_id", "compact", "compact_origin"])
115
117
  .where("id", "=", a.runId)
116
118
  .forUpdate()
117
119
  .executeTakeFirst();
@@ -162,9 +164,13 @@ let RunFinish = class RunFinish {
162
164
  }
163
165
  // the terminal status is committed first, then the tickets go (the one place runs end)
164
166
  afterCommit(() => this.gitRunEnd.onRunFinished(a.runId));
165
- // a failed or stopped run pauses the queued messages until the person resumes (spec §5.7)
166
- if (a.status !== "completed")
167
+ // a failed or stopped run pauses the queued messages until the person resumes (spec §5.7);
168
+ // an idle compact run never does (idle compaction spec §5.2, S3): preempted by input, that
169
+ // input (a queued message among them) goes out next; failed or stopped, its end is not in the
170
+ // timeline, so a pause would have no visible cause
171
+ if (a.status !== "completed" && run.compact_origin !== "idle") {
167
172
  await pauseQueueIn(t, a.conversationId);
173
+ }
168
174
  const seq = ev.seq;
169
175
  // what arrived during the run starts the next one after the commit (the run worker's post-job
170
176
  // ensureRun); owed here too, for when that never happens (an eval's hidden conversation never
@@ -174,6 +180,23 @@ let RunFinish = class RunFinish {
174
180
  (conv.kind === "chat" || conv.kind === "subagent")) {
175
181
  await oweEnsureRun(this.outbox, a.conversationId, seq, conv.org_id);
176
182
  }
183
+ // the idle compaction job armed for this run's end (idle compaction spec §4.2, S4): due before
184
+ // the prompt cache expires, stale as soon as anything but a run-less side-call usage follows
185
+ if (a.idleCompaction !== undefined &&
186
+ conv?.org_live &&
187
+ isLive(conv.deleted_at) &&
188
+ conv.kind === "chat" &&
189
+ a.idleCompaction.orgId === conv.org_id) {
190
+ const { orgId, cacheCallSeq, expiresAt, runAt } = a.idleCompaction;
191
+ await oweIdleCompaction(this.outbox, {
192
+ orgId,
193
+ conversationId: a.conversationId,
194
+ runId: a.runId,
195
+ armedSeq: seq,
196
+ cacheCallSeq,
197
+ expiresAt,
198
+ }, runAt);
199
+ }
177
200
  if (conv?.org_live)
178
201
  await this.oweTreeWork(a, conv.kind, conv.org_id);
179
202
  return seq;
@@ -3,7 +3,7 @@ import { EventLog } from "../conversations/event-log.js";
3
3
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
4
4
  import { KernelDb } from "../infra/database/kernel-db.js";
5
5
  import { TransactionHost } from "../infra/database/transaction-host.js";
6
- import type { RunAbortDetail } from "./abort.js";
6
+ import { RunAbort, type RunAbortDetail } from "./abort.js";
7
7
  import { KyselyCheckpointSaver } from "./checkpointer.js";
8
8
  import { ConversationLock } from "./conversation-lock.js";
9
9
  import { RunFinish } from "./run-finish.js";
@@ -31,10 +31,14 @@ export declare class RunQueue {
31
31
  private readonly log;
32
32
  readonly txHost: TransactionHost;
33
33
  private readonly config;
34
+ /** Preemption of an idle compact run: the cross-replica stop its worker watches. */
35
+ private readonly abort;
34
36
  private readonly ensureFails;
35
37
  constructor(kdb: KernelDb, eventLog: EventLog, lock: Pick<ConversationLock, "holder">, jobs: RunJobs, finisher: Pick<RunFinish, "finishIn">,
36
38
  /** An orphan aborted directly loses its checkpoint thread (thread_id = runId). */
37
- checkpoints: Pick<KyselyCheckpointSaver, "deleteThread">, log: Pick<Logger, "error" | "warn">, txHost: TransactionHost, config: KernelConfigService, ensureFails?: () => boolean);
39
+ checkpoints: Pick<KyselyCheckpointSaver, "deleteThread">, log: Pick<Logger, "error" | "warn">, txHost: TransactionHost, config: KernelConfigService,
40
+ /** Preemption of an idle compact run: the cross-replica stop its worker watches. */
41
+ abort: Pick<RunAbort, "requestIfAbsent">, ensureFails?: () => boolean);
38
42
  private get db();
39
43
  /**
40
44
  * 有未消费的用户消息(最新 user_message 的 seq > `consumed_seq`)、会话锁无人持有、
@@ -54,6 +58,12 @@ export declare class RunQueue {
54
58
  * never call it.
55
59
  *
56
60
  * A conversation whose agent is soft-deleted starts no run.
61
+ *
62
+ * Pending input (an unconsumed message, a queue head that goes out, a wake) preempts an active
63
+ * idle compact run (idle compaction spec §5.2): one nobody claimed yet is ended in this call's
64
+ * transaction and the input's run is created in its place; one a worker runs (the conversation
65
+ * lock is held, so this call returns before its transaction) hears a `superseded` stop through
66
+ * {@link RunAbort} after the commit, and its finish starts the input's run.
57
67
  */
58
68
  ensureRun(conversationId: string,
59
69
  /** From the `bg-wake` job: it fired `wakeRetry - 1` times before its window ended. */
@@ -74,8 +84,52 @@ export declare class RunQueue {
74
84
  startCompaction(conversationId: string, accountId: string): Promise<string>;
75
85
  /** {@link startCompaction}'s transaction: the active-run check, the run row and its owed job. */
76
86
  private startCompactionIn;
87
+ /**
88
+ * Starts an idle compact run (idle compaction spec §5.1), or returns null and never throws: the
89
+ * idle job calls it at fire time, and a refusal or a failure only means no idle compaction now
90
+ * (the next run's finish arms again). Under the conversation row lock (the one `ensureRun` and
91
+ * {@link startCompaction} take) it re-checks that the conversation, its org and its agent are
92
+ * live, that its owner can still use it (active, the agent visible to them), that nothing but a run-less side-call `usage` (`isIdleNeutralEvent`, S1) was written
93
+ * after `armedSeq`, and that the conversation is not busy: no active run (queued, running or
94
+ * waiting), no unconsumed message, no queue head. The run is a `compact` run with
95
+ * `compact_origin = 'idle'`, run as the conversation's owner, its boundary the current
96
+ * `consumed_seq`, exactly as a manual one.
97
+ */
98
+ startIdleCompaction(conversationId: string, armedSeq: number): Promise<string | null>;
99
+ /** {@link startIdleCompaction}'s transaction: the re-checks, the run row and its owed job. */
100
+ private startIdleCompactionIn;
77
101
  /** {@link ensureRun}'s transaction: what it decided goes back through `st`. */
78
102
  private ensureRunIn;
103
+ /**
104
+ * {@link ensureRun}'s check while a worker holds the conversation (idle compaction spec §5.2,
105
+ * S2): the id of the active idle compact run when input is pending, else null. Reads only (no row
106
+ * lock): a run that ends meanwhile gets a stop it never hears, and its finish's own `ensureRun`
107
+ * starts the input's run. Any active status counts: a queued one is claimed by the lock holder,
108
+ * whose watch reads the stored stop when it starts the compaction.
109
+ */
110
+ private preemptIdleIn;
111
+ /**
112
+ * Whether input waits for a chat conversation (idle compaction spec §5.2): an unconsumed message,
113
+ * a queue head that would go out (queue not paused, its author can still send), or a wake-eligible
114
+ * finished background task or delivery outside its wake window. Reads only: a wake inside its
115
+ * window owes nothing here (the idle run's finish re-derives it).
116
+ */
117
+ private inputPendingIn;
118
+ /**
119
+ * Ends a `queued` idle compact run no worker started yet (no `run_started`), in
120
+ * {@link ensureRunIn}'s transaction under the conversation row lock: `run_aborted { byAccountId:
121
+ * null, reason: "superseded" }`, which pauses nothing (S3). True when it did; false when a worker
122
+ * already started it (or it is past `queued`): the caller sends the stop after the commit. A
123
+ * worker that read it as queued re-checks it under the row locks before its `run_started`
124
+ * ({@link abortQueuedIn}'s rule).
125
+ */
126
+ private endQueuedIdleIn;
127
+ /**
128
+ * Sends the `superseded` stop of an idle compact run, after the commit that decided it. A stop
129
+ * already requested (a person's, racing the input) is left as it is: it is never relabelled
130
+ * (SET NX on the marker, {@link RunAbort.requestIfAbsent}).
131
+ */
132
+ private supersede;
79
133
  /**
80
134
  * The job id of a new run for `seq` (in {@link ensureRunIn}'s transaction, read from PG only):
81
135
  * the trigger's `runJobId` for its first run; a later run of the same trigger (a run that hit its