local-thread-goal-store.test.ts 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243
  1. /**
  2. * `SqliteThreadGoalStore` — MR-1 accounting + MR-2 tokenBudget /
  3. * BudgetLimited coverage.
  4. *
  5. * Pins:
  6. * - `create` returns tokensUsed=0 / timeUsedSeconds=0 for a fresh goal,
  7. * and `tokenBudget` round-trips through DB (null vs positive integer)
  8. * - `bumpBoundUsage` adds non-negative deltas, bumps the decision epoch when
  9. * it actually decides something (and keeps it on a stale, decision-free
  10. * charge), and no-ops on a 0+0 delta (avoids spurious SSE re-renders)
  11. * - `bumpBoundUsage` on an unknown goalId returns typed `missing_goal`
  12. * - `bumpBoundUsage` auto-transitions `active` → `budget_limited` once
  13. * `tokensUsed >= tokenBudget` and reports `transitioned`
  14. * - the transition does NOT fire when `tokenBudget` is null, when the
  15. * goal is already in a terminal state, or on the second bump after
  16. * the first transition (we still flip a second time on `active`-only)
  17. * - `patch` leaves accounting columns untouched, accepts tokenBudget,
  18. * and `patch(... tokenBudget: null)` clears the cap
  19. * - Round-trip through a fresh store instance proves both v14 and v15
  20. * ALTER columns are durable on disk
  21. */
  22. import { mkdtemp, rm } from "node:fs/promises";
  23. import { tmpdir } from "node:os";
  24. import { join } from "node:path";
  25. import { describe, expect, it } from "vitest";
  26. import {
  27. digestThreadGoalObjective,
  28. type GoalTurnBinding,
  29. type LastVerificationV1,
  30. } from "@mavis/goal";
  31. import { closeLocalRuntimeDb, openLocalRuntimeDb } from "../../src/persistence/db.js";
  32. import { SqliteThreadGoalStore } from "../../src/thread-goal/store.js";
  33. async function withDataDir(fn: (dir: string) => Promise<void>): Promise<void> {
  34. const dataDir = await mkdtemp(join(tmpdir(), "goal-accounting-"));
  35. try {
  36. await fn(dataDir);
  37. } finally {
  38. closeLocalRuntimeDb(dataDir);
  39. await rm(dataDir, { recursive: true, force: true });
  40. }
  41. }
  42. const TEST_LIMITS = {
  43. tokens: 10_000,
  44. mainTurns: 10,
  45. activeSeconds: 1_000,
  46. } as const;
  47. function bindingFor(
  48. goal: {
  49. readonly goalId: string;
  50. readonly updatedAt: number;
  51. readonly objective: string;
  52. },
  53. overrides: Partial<GoalTurnBinding> = {},
  54. ): GoalTurnBinding {
  55. return {
  56. goalId: goal.goalId,
  57. admittedGoalUpdatedAt: goal.updatedAt,
  58. objectiveDigest: digestThreadGoalObjective(goal.objective),
  59. turnId: "turn-bound",
  60. ...overrides,
  61. };
  62. }
  63. function verificationResult(
  64. goal: { readonly objective: string },
  65. overrides: Partial<LastVerificationV1> = {},
  66. ): LastVerificationV1 {
  67. return {
  68. v: 1,
  69. backend: "evaluator",
  70. verdict: "not_met",
  71. reason: "More evidence is required.",
  72. missing: ["test evidence"],
  73. notMetStreak: 0,
  74. turnId: "turn-verifier",
  75. objectiveDigest: digestThreadGoalObjective(goal.objective),
  76. at: 1_700_000_000_000,
  77. ...overrides,
  78. };
  79. }
  80. describe("SqliteThreadGoalStore — accounting + budget", () => {
  81. it.each([false, true])("idempotently upgrades a pre-v31 database without persisting Goal verification policy (historical indexing marker: %s)", async (hasHistoricalIndexingMarker) => {
  82. await withDataDir(async (dataDir) => {
  83. const db = openLocalRuntimeDb(dataDir);
  84. if (hasHistoricalIndexingMarker) {
  85. db.prepare("INSERT INTO local_runtime_schema_migrations (version, applied_at_ms) VALUES (?, ?)").run(28, 1);
  86. }
  87. db.exec(`
  88. DROP TABLE local_runtime_thread_goals;
  89. CREATE TABLE local_runtime_thread_goals (
  90. goal_id TEXT PRIMARY KEY,
  91. session_id TEXT NOT NULL UNIQUE,
  92. objective TEXT NOT NULL,
  93. status TEXT NOT NULL,
  94. created_at_ms INTEGER NOT NULL,
  95. updated_at_ms INTEGER NOT NULL
  96. );
  97. INSERT INTO local_runtime_thread_goals (
  98. goal_id, session_id, objective, status, created_at_ms, updated_at_ms
  99. ) VALUES ('goal-old', 'session-old', 'old goal', 'active', 1, 1);
  100. DELETE FROM local_runtime_schema_migrations WHERE version IN (27, 29, 30, 31);
  101. `);
  102. closeLocalRuntimeDb(dataDir);
  103. const upgraded = openLocalRuntimeDb(dataDir);
  104. const columns = upgraded
  105. .prepare("PRAGMA table_info(local_runtime_thread_goals)")
  106. .all()
  107. .map((row) => String((row as { name?: unknown }).name));
  108. const migrationVersions = upgraded
  109. .prepare(
  110. "SELECT version FROM local_runtime_schema_migrations WHERE version IN (26, 27, 28, 29, 30, 31) ORDER BY version",
  111. )
  112. .all()
  113. .map((row) => Number((row as { version?: unknown }).version));
  114. const legacyGoal = upgraded
  115. .prepare(
  116. `SELECT kickoff_attachments_json, kickoff_state, turns_used, reply_fingerprint,
  117. no_progress_streak, last_verification, last_worker_proposal, status_reason,
  118. execution_wait_reason, execution_wait_since_ms, execution_wait_epoch
  119. FROM local_runtime_thread_goals WHERE goal_id = ?`,
  120. )
  121. .get("goal-old") as
  122. | {
  123. kickoff_attachments_json: string;
  124. kickoff_state: string;
  125. turns_used: number;
  126. reply_fingerprint: string | null;
  127. no_progress_streak: number;
  128. last_verification: string | null;
  129. last_worker_proposal: string | null;
  130. status_reason: string | null;
  131. execution_wait_reason: string | null;
  132. execution_wait_since_ms: number | null;
  133. execution_wait_epoch: number | null;
  134. }
  135. | undefined;
  136. expect(columns).toEqual(
  137. expect.arrayContaining([
  138. "kickoff_attachments_json",
  139. "kickoff_state",
  140. "turns_used",
  141. "reply_fingerprint",
  142. "no_progress_streak",
  143. "last_verification",
  144. "last_worker_proposal",
  145. "status_reason",
  146. "execution_wait_reason",
  147. "execution_wait_since_ms",
  148. "execution_wait_epoch",
  149. ]),
  150. );
  151. // Version 28 belongs to retired workspace indexing; a fresh public DB
  152. // must not recreate its marker. Goal migrations still run and retain data.
  153. expect(migrationVersions).toEqual(
  154. hasHistoricalIndexingMarker ? [26, 27, 28, 29, 30, 31] : [26, 27, 29, 30, 31],
  155. );
  156. expect(legacyGoal).toEqual({
  157. kickoff_attachments_json: "[]",
  158. kickoff_state: "consumed",
  159. turns_used: 0,
  160. reply_fingerprint: null,
  161. no_progress_streak: 0,
  162. last_verification: null,
  163. last_worker_proposal: null,
  164. status_reason: null,
  165. execution_wait_reason: null,
  166. execution_wait_since_ms: null,
  167. execution_wait_epoch: null,
  168. });
  169. closeLocalRuntimeDb(dataDir);
  170. const reopened = openLocalRuntimeDb(dataDir);
  171. expect(
  172. reopened
  173. .prepare("PRAGMA table_info(local_runtime_thread_goals)")
  174. .all()
  175. .filter(
  176. (row) =>
  177. String((row as { name?: unknown }).name) === "verification",
  178. ),
  179. ).toHaveLength(0);
  180. });
  181. });
  182. it("records migration 27 without replaying Goal ALTERs on a collided version-26 database", async () => {
  183. await withDataDir(async (dataDir) => {
  184. const db = openLocalRuntimeDb(dataDir);
  185. db.prepare(
  186. "DELETE FROM local_runtime_schema_migrations WHERE version = 27",
  187. ).run();
  188. closeLocalRuntimeDb(dataDir);
  189. const upgraded = openLocalRuntimeDb(dataDir);
  190. const marker = upgraded
  191. .prepare(
  192. "SELECT version FROM local_runtime_schema_migrations WHERE version = 27",
  193. )
  194. .get() as { version?: unknown } | undefined;
  195. const indexes = upgraded
  196. .prepare("PRAGMA index_list(local_runtime_thread_goals)")
  197. .all()
  198. .map((row) => String((row as { name?: unknown }).name));
  199. expect(marker?.version).toBe(27);
  200. expect(indexes).toContain("idx_local_runtime_thread_goals_kickoff_state");
  201. });
  202. });
  203. it("persists Goal-owned kickoff attachments in pending state until Queue materialization", async () => {
  204. await withDataDir(async (dataDir) => {
  205. const store = new SqliteThreadGoalStore(dataDir, () => 1_700_000_000_000);
  206. const created = await store.create({
  207. sessionId: "sess_attachment",
  208. objective: "Read the brief",
  209. kickoffAttachments: [
  210. {
  211. type: "file",
  212. filePath: "/tmp/brief.pdf",
  213. fileName: "brief.pdf",
  214. mimeType: "application/pdf",
  215. assetId: "asset-1",
  216. },
  217. ],
  218. });
  219. expect(created).toMatchObject({
  220. kickoffState: "pending",
  221. kickoffAttachments: [
  222. {
  223. type: "file",
  224. filePath: "/tmp/brief.pdf",
  225. fileName: "brief.pdf",
  226. mimeType: "application/pdf",
  227. assetId: "asset-1",
  228. },
  229. ],
  230. });
  231. const fresh = new SqliteThreadGoalStore(dataDir);
  232. expect(await fresh.getById(created.goalId)).toMatchObject({
  233. kickoffState: "pending",
  234. kickoffAttachments: created.kickoffAttachments,
  235. });
  236. });
  237. });
  238. it("lists recoverable kickoffs and advances their state with compare-and-set semantics", async () => {
  239. await withDataDir(async (dataDir) => {
  240. const store = new SqliteThreadGoalStore(dataDir, () => 1_700_000_000_000);
  241. const created = await store.create({
  242. sessionId: "sess_recoverable",
  243. objective: "Recover me",
  244. });
  245. expect(await store.listRecoverableKickoffs()).toEqual([created]);
  246. await expect(
  247. store.transitionKickoffState(created.goalId, "pending", "enqueued"),
  248. ).resolves.toMatchObject({ kickoffState: "enqueued" });
  249. await expect(
  250. store.transitionKickoffState(created.goalId, "pending", "consumed"),
  251. ).resolves.toBeUndefined();
  252. await expect(
  253. store.transitionKickoffState(created.goalId, "enqueued", "consumed"),
  254. ).resolves.toMatchObject({ kickoffState: "consumed" });
  255. expect(await store.listRecoverableKickoffs()).toEqual([]);
  256. expect(await store.listRecoverableActiveGoals()).toEqual([
  257. expect.objectContaining({ goalId: created.goalId, status: "active" }),
  258. ]);
  259. await store.patch(created.goalId, { status: "paused" });
  260. expect(await store.listRecoverableActiveGoals()).toEqual([]);
  261. });
  262. });
  263. it("lists every durable budget-limited Goal as a recoverable summary candidate", async () => {
  264. await withDataDir(async (dataDir) => {
  265. let now = 1_700_000_000_000;
  266. const store = new SqliteThreadGoalStore(dataDir, () => now);
  267. const created = await store.create({
  268. sessionId: "sess_budget_summary_recovery",
  269. objective: "Stop at the limit",
  270. tokenBudget: 1,
  271. });
  272. await store.transitionKickoffState(created.goalId, "pending", "consumed");
  273. now += 1;
  274. const limited = await store.bumpBoundUsage(
  275. bindingFor(created),
  276. { tokens: 1, activeSeconds: 0, mainTurns: 1 },
  277. { ...TEST_LIMITS, tokens: 1 },
  278. );
  279. expect(limited?.goal.status).toBe("budget_limited");
  280. expect(await store.listRecoverableBudgetLimitSummaries()).toEqual([
  281. limited?.goal,
  282. ]);
  283. });
  284. });
  285. it("creates a goal with accounting columns initialized to 0 and tokenBudget=null when omitted", async () => {
  286. await withDataDir(async (dataDir) => {
  287. const now = 1_700_000_000_000;
  288. const store = new SqliteThreadGoalStore(dataDir, () => now);
  289. const goal = await store.create({
  290. sessionId: "sess_a",
  291. objective: "audit",
  292. });
  293. expect(goal.tokensUsed).toBe(0);
  294. expect(goal.turnsUsed).toBe(0);
  295. expect(goal.timeUsedSeconds).toBe(0);
  296. expect(goal.tokenBudget).toBeNull();
  297. expect(goal.replyFingerprint).toBeNull();
  298. expect(goal.noProgressStreak).toBe(0);
  299. expect(goal.lastVerification).toBeUndefined();
  300. expect(goal.statusReason).toBeNull();
  301. expect(goal.createdAt).toBe(now);
  302. expect(goal.updatedAt).toBe(now);
  303. });
  304. });
  305. it("creates a goal with the given tokenBudget when supplied", async () => {
  306. await withDataDir(async (dataDir) => {
  307. const store = new SqliteThreadGoalStore(dataDir, () => 1_700_000_000_000);
  308. const goal = await store.create({
  309. sessionId: "sess_a2",
  310. objective: "audit",
  311. tokenBudget: 5_000,
  312. });
  313. expect(goal.tokenBudget).toBe(5_000);
  314. });
  315. });
  316. it("projects an execution wait with epoch CAS while keeping its time and Goal epoch stable", async () => {
  317. await withDataDir(async (dataDir) => {
  318. let now = 1_700_000_000_000;
  319. const store = new SqliteThreadGoalStore(dataDir, () => now);
  320. const created = await store.create({
  321. sessionId: "sess_wait",
  322. objective: "wait safely",
  323. });
  324. now += 100;
  325. await expect(
  326. store.setExecutionWaitAtEpoch({
  327. goalId: created.goalId,
  328. expectedUpdatedAt: created.updatedAt,
  329. reason: "permission",
  330. }),
  331. ).resolves.toMatchObject({
  332. updatedAt: created.updatedAt,
  333. executionWait: { reason: "permission", sinceMs: now },
  334. });
  335. now += 100;
  336. await expect(
  337. store.setExecutionWaitAtEpoch({
  338. goalId: created.goalId,
  339. expectedUpdatedAt: created.updatedAt,
  340. reason: "permission",
  341. }),
  342. ).resolves.toBeUndefined();
  343. await expect(store.getById(created.goalId)).resolves.toMatchObject({
  344. updatedAt: created.updatedAt,
  345. executionWait: { reason: "permission", sinceMs: now - 100 },
  346. });
  347. await expect(
  348. store.setExecutionWaitAtEpoch({
  349. goalId: created.goalId,
  350. expectedUpdatedAt: created.updatedAt + 1,
  351. reason: "plan",
  352. }),
  353. ).resolves.toBeUndefined();
  354. await expect(
  355. store.clearExecutionWaitAtEpoch({
  356. goalId: created.goalId,
  357. expectedUpdatedAt: created.updatedAt,
  358. }),
  359. ).resolves.toMatchObject({
  360. updatedAt: created.updatedAt,
  361. executionWait: null,
  362. });
  363. });
  364. });
  365. it("retires the previous execution wait whenever a lifecycle write advances the epoch", async () => {
  366. await withDataDir(async (dataDir) => {
  367. let now = 1_700_000_000_000;
  368. const store = new SqliteThreadGoalStore(dataDir, () => now);
  369. const created = await store.create({
  370. sessionId: "sess_wait_reset",
  371. objective: "resume cleanly",
  372. });
  373. now += 1;
  374. await store.setExecutionWaitAtEpoch({
  375. goalId: created.goalId,
  376. expectedUpdatedAt: created.updatedAt,
  377. reason: "required_background",
  378. });
  379. now += 1;
  380. const paused = await store.patch(created.goalId, {
  381. status: "paused",
  382. statusReason: "paused(user_requested)",
  383. });
  384. expect(paused.executionWait).toBeNull();
  385. now += 1;
  386. const resumed = await store.patch(created.goalId, { status: "active" });
  387. // The resumed Goal is `active` again, so only the epoch stamp keeps the
  388. // superseded reason from resurfacing. `patch` never touches the wait
  389. // columns — that is the point: no epoch writer has to remember to.
  390. expect(resumed.executionWait).toBeNull();
  391. await expect(store.getById(created.goalId)).resolves.toMatchObject({
  392. status: "active",
  393. executionWait: null,
  394. });
  395. const raw = openLocalRuntimeDb(dataDir)
  396. .prepare(
  397. `SELECT execution_wait_reason, execution_wait_epoch, updated_at_ms
  398. FROM local_runtime_thread_goals WHERE goal_id = ?`,
  399. )
  400. .get(created.goalId) as {
  401. execution_wait_reason: string | null;
  402. execution_wait_epoch: number | null;
  403. updated_at_ms: number;
  404. };
  405. expect(raw.execution_wait_reason).toBe("required_background");
  406. expect(raw.execution_wait_epoch).not.toBe(raw.updated_at_ms);
  407. });
  408. });
  409. it("rewrites a wait whose reason is unchanged but whose epoch was superseded", async () => {
  410. await withDataDir(async (dataDir) => {
  411. let now = 1_700_000_000_000;
  412. const store = new SqliteThreadGoalStore(dataDir, () => now);
  413. const created = await store.create({
  414. sessionId: "sess_wait_reepoch",
  415. objective: "wait across epochs",
  416. });
  417. now += 1;
  418. await store.setExecutionWaitAtEpoch({
  419. goalId: created.goalId,
  420. expectedUpdatedAt: created.updatedAt,
  421. reason: "required_background",
  422. });
  423. now += 1;
  424. const repatched = await store.patch(created.goalId, {
  425. objective: "wait again",
  426. });
  427. expect(repatched.executionWait).toBeNull();
  428. // Same reason, new epoch. Deduplicating on the reason alone would leave
  429. // the row invisible to readers forever, so this must write.
  430. now += 1;
  431. await expect(
  432. store.setExecutionWaitAtEpoch({
  433. goalId: created.goalId,
  434. expectedUpdatedAt: repatched.updatedAt,
  435. reason: "required_background",
  436. }),
  437. ).resolves.toMatchObject({
  438. updatedAt: repatched.updatedAt,
  439. executionWait: { reason: "required_background", sinceMs: now },
  440. });
  441. });
  442. });
  443. it("reads unknown status and verification-result JSON fail-closed", async () => {
  444. await withDataDir(async (dataDir) => {
  445. const store = new SqliteThreadGoalStore(dataDir, () => 1_700_000_000_000);
  446. const created = await store.create({
  447. sessionId: "sess_unknown_policy",
  448. objective: "audit",
  449. });
  450. openLocalRuntimeDb(dataDir)
  451. .prepare(
  452. `UPDATE local_runtime_thread_goals
  453. SET status = 'future_status', last_verification = '{"v":2}'
  454. WHERE goal_id = ?`,
  455. )
  456. .run(created.goalId);
  457. expect(await store.getById(created.goalId)).toMatchObject({
  458. status: "paused",
  459. lastVerification: undefined,
  460. });
  461. await expect(
  462. store.patch(created.goalId, { status: "active" }),
  463. ).rejects.toMatchObject({
  464. currentStatus: "paused",
  465. });
  466. });
  467. });
  468. it("rejects budget_limited rearm but resets breaker streak on usage_limited rearm", async () => {
  469. await withDataDir(async (dataDir) => {
  470. const store = new SqliteThreadGoalStore(dataDir, () => 1_700_000_000_000);
  471. const budgeted = await store.create({
  472. sessionId: "sess_budget_rearm",
  473. objective: "audit",
  474. tokenBudget: 1,
  475. });
  476. await store.bumpBoundUsage(
  477. bindingFor(budgeted),
  478. { tokens: 1, activeSeconds: 1, mainTurns: 1 },
  479. { ...TEST_LIMITS, tokens: 1 },
  480. );
  481. await expect(
  482. store.patch(budgeted.goalId, { status: "active" }),
  483. ).rejects.toMatchObject({
  484. code: "GOAL_BUDGET_LIMITED",
  485. });
  486. const recoverable = await store.create({
  487. sessionId: "sess_usage_rearm",
  488. objective: "audit",
  489. });
  490. await store.patch(recoverable.goalId, {
  491. status: "usage_limited",
  492. statusReason: "usage_limited(rate_limit)",
  493. });
  494. openLocalRuntimeDb(dataDir)
  495. .prepare(
  496. `UPDATE local_runtime_thread_goals
  497. SET reply_fingerprint = 'same', no_progress_streak = 2, no_tool_streak = 2
  498. WHERE goal_id = ?`,
  499. )
  500. .run(recoverable.goalId);
  501. expect(
  502. await store.patch(recoverable.goalId, { status: "active" }),
  503. ).toMatchObject({
  504. status: "active",
  505. tokensUsed: 0,
  506. replyFingerprint: null,
  507. noProgressStreak: 0,
  508. noToolStreak: 0,
  509. });
  510. });
  511. });
  512. describe("no-tool breaker", () => {
  513. const breakerInput = (
  514. expectedEpoch: number,
  515. toolActivity: "used" | "absent" | "unknown",
  516. fingerprint: string | null = null,
  517. limit = 3,
  518. ) => ({ expectedEpoch, fingerprint, toolActivity, limit });
  519. it("pauses on the third consecutive tool-less Turn and keeps both counters apart", async () => {
  520. await withDataDir(async (dataDir) => {
  521. let now = 1_700_000_000_000;
  522. const store = new SqliteThreadGoalStore(dataDir, () => (now += 1));
  523. const created = await store.create({
  524. sessionId: "sess_no_tool",
  525. objective: "audit",
  526. });
  527. // Every reply differs, so only the no-tool condition can act here.
  528. const first = await store.updateBreaker(
  529. created.goalId,
  530. breakerInput(created.updatedAt, "absent", "fp-a"),
  531. );
  532. expect(first).toMatchObject({ action: "none" });
  533. if (first.action === "stale") throw new Error("unexpected stale");
  534. expect(first.goal).toMatchObject({
  535. noToolStreak: 1,
  536. noProgressStreak: 0,
  537. });
  538. const second = await store.updateBreaker(
  539. created.goalId,
  540. breakerInput(first.goal.updatedAt, "absent", "fp-b"),
  541. );
  542. if (second.action === "stale") throw new Error("unexpected stale");
  543. expect(second).toMatchObject({ action: "nudge", cause: "no_tool" });
  544. expect(second.goal).toMatchObject({
  545. noToolStreak: 2,
  546. noProgressStreak: 0,
  547. status: "active",
  548. });
  549. const third = await store.updateBreaker(
  550. created.goalId,
  551. breakerInput(second.goal.updatedAt, "absent", "fp-c"),
  552. );
  553. if (third.action === "stale") throw new Error("unexpected stale");
  554. expect(third).toMatchObject({ action: "pause", cause: "no_tool" });
  555. expect(third.goal).toMatchObject({
  556. status: "paused",
  557. statusReason: "paused(no_progress)",
  558. noToolStreak: 3,
  559. // The repeated-reply counter never absorbed the tool-less turns.
  560. noProgressStreak: 0,
  561. });
  562. });
  563. });
  564. it("clears the streak on a real tool call and on an unobservable Turn", async () => {
  565. await withDataDir(async (dataDir) => {
  566. let now = 1_700_000_000_000;
  567. const store = new SqliteThreadGoalStore(dataDir, () => (now += 1));
  568. const created = await store.create({
  569. sessionId: "sess_no_tool_reset",
  570. objective: "audit",
  571. });
  572. const first = await store.updateBreaker(
  573. created.goalId,
  574. breakerInput(created.updatedAt, "absent", "fp-a"),
  575. );
  576. if (first.action === "stale") throw new Error("unexpected stale");
  577. expect(first.goal.noToolStreak).toBe(1);
  578. const worked = await store.updateBreaker(
  579. created.goalId,
  580. breakerInput(first.goal.updatedAt, "used", "fp-b"),
  581. );
  582. if (worked.action === "stale") throw new Error("unexpected stale");
  583. expect(worked.goal.noToolStreak).toBe(0);
  584. const absentAgain = await store.updateBreaker(
  585. created.goalId,
  586. breakerInput(worked.goal.updatedAt, "absent", "fp-c"),
  587. );
  588. if (absentAgain.action === "stale") throw new Error("unexpected stale");
  589. expect(absentAgain.goal.noToolStreak).toBe(1);
  590. // An unobservable Turn is an observation gap, not a trustworthy zero:
  591. // it may not be stitched into the consecutive run.
  592. const gap = await store.updateBreaker(
  593. created.goalId,
  594. breakerInput(absentAgain.goal.updatedAt, "unknown", "fp-d"),
  595. );
  596. if (gap.action === "stale") throw new Error("unexpected stale");
  597. expect(gap.goal).toMatchObject({ noToolStreak: 0, status: "active" });
  598. });
  599. });
  600. it("scores the no-tool condition even when the Turn produced no reply text", async () => {
  601. await withDataDir(async (dataDir) => {
  602. let now = 1_700_000_000_000;
  603. const store = new SqliteThreadGoalStore(dataDir, () => (now += 1));
  604. const created = await store.create({
  605. sessionId: "sess_no_tool_empty",
  606. objective: "audit",
  607. });
  608. await store.updateBreaker(
  609. created.goalId,
  610. breakerInput(created.updatedAt, "used", "fp-a"),
  611. );
  612. const seeded = await store.getById(created.goalId);
  613. if (!seeded) throw new Error("expected goal");
  614. let epoch = seeded.updatedAt;
  615. for (let i = 0; i < 3; i += 1) {
  616. const result = await store.updateBreaker(
  617. created.goalId,
  618. // fingerprint null == empty reply: the fingerprint branch is
  619. // skipped but the no-tool branch still scores.
  620. breakerInput(epoch, "absent", null),
  621. );
  622. if (result.action === "stale") throw new Error("unexpected stale");
  623. epoch = result.goal.updatedAt;
  624. expect(result.goal.noToolStreak).toBe(i + 1);
  625. // The stored fingerprint from the earlier reply survives untouched.
  626. expect(result.goal.replyFingerprint).toBe("fp-a");
  627. }
  628. const final = await store.getById(created.goalId);
  629. expect(final).toMatchObject({
  630. status: "paused",
  631. statusReason: "paused(no_progress)",
  632. });
  633. });
  634. });
  635. it("shares one configured limit with the repeated-reply condition", async () => {
  636. await withDataDir(async (dataDir) => {
  637. let now = 1_700_000_000_000;
  638. const store = new SqliteThreadGoalStore(dataDir, () => (now += 1));
  639. const created = await store.create({
  640. sessionId: "sess_no_tool_limit",
  641. objective: "audit",
  642. });
  643. let epoch = created.updatedAt;
  644. for (let i = 0; i < 3; i += 1) {
  645. const result = await store.updateBreaker(
  646. created.goalId,
  647. breakerInput(epoch, "absent", `fp-${i}`, 4),
  648. );
  649. if (result.action === "stale") throw new Error("unexpected stale");
  650. epoch = result.goal.updatedAt;
  651. expect(result.goal.status).toBe("active");
  652. }
  653. const fourth = await store.updateBreaker(
  654. created.goalId,
  655. breakerInput(epoch, "absent", "fp-3", 4),
  656. );
  657. if (fourth.action === "stale") throw new Error("unexpected stale");
  658. expect(fourth).toMatchObject({ action: "pause", cause: "no_tool" });
  659. expect(fourth.goal).toMatchObject({
  660. noToolStreak: 4,
  661. status: "paused",
  662. });
  663. });
  664. });
  665. // Combination guard: the explicit-user-Turn reset and the no-tool counter
  666. // arrived in two separate changesets, so no single-source test could cover
  667. // that one `resetBreakerAtEpoch` has to clear BOTH breaker conditions. A
  668. // reset that cleared only the reply fingerprint would let a Goal the user
  669. // just intervened on pause again after a single further tool-less Turn.
  670. it("clears the no-tool streak together with the reply streak on an explicit user reset", async () => {
  671. await withDataDir(async (dataDir) => {
  672. let now = 1_700_000_000_000;
  673. const store = new SqliteThreadGoalStore(dataDir, () => (now += 1));
  674. const created = await store.create({
  675. sessionId: "sess_reset_both",
  676. objective: "audit",
  677. });
  678. const first = await store.updateBreaker(
  679. created.goalId,
  680. breakerInput(created.updatedAt, "absent", "same"),
  681. );
  682. if (first.action === "stale") throw new Error("unexpected stale");
  683. const second = await store.updateBreaker(
  684. created.goalId,
  685. breakerInput(first.goal.updatedAt, "absent", "same"),
  686. );
  687. if (second.action === "stale") throw new Error("unexpected stale");
  688. // Both conditions are one Turn away from pausing.
  689. expect(second.goal).toMatchObject({
  690. noToolStreak: 2,
  691. noProgressStreak: 1,
  692. });
  693. const reset = await store.resetBreakerAtEpoch(
  694. created.goalId,
  695. second.goal.updatedAt,
  696. );
  697. expect(reset).toMatchObject({
  698. replyFingerprint: null,
  699. noProgressStreak: 0,
  700. noToolStreak: 0,
  701. });
  702. // The very next tool-less Turn restarts from 1 rather than pausing.
  703. const afterReset = await store.updateBreaker(
  704. created.goalId,
  705. breakerInput(reset!.updatedAt, "absent", "same"),
  706. );
  707. if (afterReset.action === "stale") throw new Error("unexpected stale");
  708. expect(afterReset).toMatchObject({ action: "none" });
  709. expect(afterReset.goal).toMatchObject({
  710. noToolStreak: 1,
  711. status: "active",
  712. });
  713. });
  714. });
  715. it("rejects a stale epoch without touching the no-tool streak", async () => {
  716. await withDataDir(async (dataDir) => {
  717. let now = 1_700_000_000_000;
  718. const store = new SqliteThreadGoalStore(dataDir, () => (now += 1));
  719. const created = await store.create({
  720. sessionId: "sess_no_tool_cas",
  721. objective: "audit",
  722. });
  723. const first = await store.updateBreaker(
  724. created.goalId,
  725. breakerInput(created.updatedAt, "absent", "fp-a"),
  726. );
  727. if (first.action === "stale") throw new Error("unexpected stale");
  728. const stale = await store.updateBreaker(
  729. created.goalId,
  730. breakerInput(created.updatedAt, "absent", "fp-b"),
  731. );
  732. expect(stale).toMatchObject({
  733. action: "stale",
  734. staleReason: "goal_epoch",
  735. });
  736. expect(await store.getById(created.goalId)).toMatchObject({
  737. noToolStreak: 1,
  738. });
  739. });
  740. });
  741. it("still enforces the epoch CAS when the decision changes nothing", async () => {
  742. await withDataDir(async (dataDir) => {
  743. let now = 1_700_000_000_000;
  744. const store = new SqliteThreadGoalStore(dataDir, () => (now += 1));
  745. const created = await store.create({
  746. sessionId: "sess_no_tool_noop_cas",
  747. objective: "audit",
  748. });
  749. // A concurrent user PATCH advances the epoch without leaving `active`.
  750. const patched = await store.patch(created.goalId, {
  751. tokenBudget: 1000,
  752. });
  753. expect(patched.updatedAt).not.toBe(created.updatedAt);
  754. // Tool used, no reply text, both counters already zero: nothing to
  755. // write. The breaker must still refuse the superseded epoch instead of
  756. // handing the settled Turn the post-PATCH epoch.
  757. const result = await store.updateBreaker(
  758. created.goalId,
  759. breakerInput(created.updatedAt, "used", null),
  760. );
  761. expect(result).toMatchObject({
  762. action: "stale",
  763. staleReason: "goal_epoch",
  764. });
  765. });
  766. });
  767. });
  768. it("atomically raises or clears a token cap and rearms only token-limited goals", async () => {
  769. await withDataDir(async (dataDir) => {
  770. const store = new SqliteThreadGoalStore(dataDir, () => 1_700_000_000_000);
  771. const created = await store.create({
  772. sessionId: "sess_token_budget_rearm",
  773. objective: "audit",
  774. tokenBudget: 10,
  775. });
  776. const limited = await store.bumpBoundUsage(
  777. bindingFor(created),
  778. { tokens: 10, activeSeconds: 1, mainTurns: 1 },
  779. { ...TEST_LIMITS, tokens: 10 },
  780. );
  781. if (!limited.goal) throw new Error("expected persisted goal");
  782. const raised = await store.patch(created.goalId, {
  783. status: "active",
  784. statusReason: null,
  785. tokenBudget: 20,
  786. rejectIfUpdatedAtChangedFrom: limited.goal.updatedAt,
  787. });
  788. expect(raised).toMatchObject({
  789. status: "active",
  790. statusReason: null,
  791. tokensUsed: 10,
  792. tokenBudget: 20,
  793. });
  794. await store.patch(created.goalId, {
  795. status: "budget_limited",
  796. statusReason: "budget_limited(token)",
  797. });
  798. const current = await store.getById(created.goalId);
  799. if (!current) throw new Error("expected persisted goal");
  800. await expect(
  801. store.patch(created.goalId, {
  802. status: "active",
  803. statusReason: null,
  804. tokenBudget: null,
  805. rejectIfUpdatedAtChangedFrom: current.updatedAt,
  806. }),
  807. ).resolves.toMatchObject({ status: "active", tokenBudget: null });
  808. });
  809. });
  810. it("rejects stale, already-exhausted, and non-token budget recovery writes", async () => {
  811. await withDataDir(async (dataDir) => {
  812. const store = new SqliteThreadGoalStore(dataDir, () => 1_700_000_000_000);
  813. const created = await store.create({
  814. sessionId: "sess_budget_guards",
  815. objective: "audit",
  816. });
  817. const accounted = await store.bumpBoundUsage(
  818. bindingFor(created),
  819. { tokens: 10, activeSeconds: 1, mainTurns: 1 },
  820. TEST_LIMITS,
  821. );
  822. if (!accounted.goal) throw new Error("expected persisted goal");
  823. await expect(
  824. store.patch(created.goalId, {
  825. tokenBudget: 10,
  826. rejectIfUpdatedAtChangedFrom: accounted.goal.updatedAt,
  827. }),
  828. ).rejects.toMatchObject({ code: "GOAL_TOKEN_BUDGET_EXHAUSTED" });
  829. await expect(
  830. store.patch(created.goalId, {
  831. tokenBudget: 20,
  832. rejectIfUpdatedAtChangedFrom: created.updatedAt,
  833. }),
  834. ).rejects.toMatchObject({ code: "GOAL_EPOCH_CONFLICT" });
  835. const mainTurnLimited = await store.patch(created.goalId, {
  836. status: "budget_limited",
  837. statusReason: "budget_limited(main_turn)",
  838. });
  839. await expect(
  840. store.patch(created.goalId, {
  841. status: "active",
  842. statusReason: null,
  843. tokenBudget: 100,
  844. rejectIfUpdatedAtChangedFrom: mainTurnLimited.updatedAt,
  845. }),
  846. ).rejects.toMatchObject({ code: "GOAL_BUDGET_LIMITED" });
  847. });
  848. });
  849. it("persists repeated replies and pauses on the third identical reply", async () => {
  850. await withDataDir(async (dataDir) => {
  851. const store = new SqliteThreadGoalStore(dataDir, () => 1_700_000_000_000);
  852. const created = await store.create({
  853. sessionId: "sess_breaker",
  854. objective: "audit",
  855. });
  856. const first = await store.updateBreaker(created.goalId, {
  857. expectedEpoch: created.updatedAt,
  858. fingerprint: "fingerprint-a",
  859. limit: 3,
  860. });
  861. expect(first).toMatchObject({
  862. action: "none",
  863. goal: { noProgressStreak: 0, status: "active" },
  864. });
  865. if (first.action === "stale")
  866. throw new Error("unexpected stale breaker result");
  867. const repeat1 = await store.updateBreaker(created.goalId, {
  868. expectedEpoch: first.epoch,
  869. fingerprint: "fingerprint-a",
  870. limit: 3,
  871. });
  872. expect(repeat1).toMatchObject({
  873. action: "nudge",
  874. goal: { noProgressStreak: 1, status: "active" },
  875. });
  876. if (repeat1.action === "stale")
  877. throw new Error("unexpected stale breaker result");
  878. const repeat2 = await store.updateBreaker(created.goalId, {
  879. expectedEpoch: repeat1.epoch,
  880. fingerprint: "fingerprint-a",
  881. limit: 3,
  882. });
  883. expect(repeat2).toMatchObject({
  884. action: "pause",
  885. goal: {
  886. noProgressStreak: 2,
  887. status: "paused",
  888. statusReason: "paused(no_progress)",
  889. },
  890. });
  891. const reopened = new SqliteThreadGoalStore(dataDir);
  892. expect(await reopened.getById(created.goalId)).toMatchObject({
  893. replyFingerprint: "fingerprint-a",
  894. noProgressStreak: 2,
  895. status: "paused",
  896. statusReason: "paused(no_progress)",
  897. });
  898. });
  899. });
  900. it("persists the host-selected reason when no progress overrides a completion claim", async () => {
  901. await withDataDir(async (dataDir) => {
  902. const store = new SqliteThreadGoalStore(dataDir, () => 1_700_000_000_000);
  903. const created = await store.create({
  904. sessionId: "sess_completion_breaker",
  905. objective: "audit",
  906. });
  907. const first = await store.updateBreaker(created.goalId, {
  908. expectedEpoch: created.updatedAt,
  909. fingerprint: "same-completion-claim",
  910. limit: 1,
  911. });
  912. if (first.action === "stale")
  913. throw new Error("unexpected stale breaker result");
  914. const repeated = await store.updateBreaker(created.goalId, {
  915. expectedEpoch: first.epoch,
  916. fingerprint: "same-completion-claim",
  917. limit: 1,
  918. pauseReason: "paused(no_progress_after_completion_claim)",
  919. });
  920. expect(repeated).toMatchObject({
  921. action: "pause",
  922. goal: {
  923. status: "paused",
  924. statusReason: "paused(no_progress_after_completion_claim)",
  925. },
  926. });
  927. expect(await store.getById(created.goalId)).toMatchObject({
  928. status: "paused",
  929. statusReason: "paused(no_progress_after_completion_claim)",
  930. });
  931. });
  932. });
  933. it("resets the repeated-reply streak when the fingerprint changes", async () => {
  934. await withDataDir(async (dataDir) => {
  935. const store = new SqliteThreadGoalStore(dataDir, () => 1_700_000_000_000);
  936. const created = await store.create({
  937. sessionId: "sess_breaker_change",
  938. objective: "audit",
  939. });
  940. const first = await store.updateBreaker(created.goalId, {
  941. expectedEpoch: created.updatedAt,
  942. fingerprint: "fingerprint-a",
  943. limit: 3,
  944. });
  945. if (first.action === "stale")
  946. throw new Error("unexpected stale breaker result");
  947. const repeated = await store.updateBreaker(created.goalId, {
  948. expectedEpoch: first.epoch,
  949. fingerprint: "fingerprint-a",
  950. limit: 3,
  951. });
  952. if (repeated.action === "stale")
  953. throw new Error("unexpected stale breaker result");
  954. await expect(
  955. store.updateBreaker(created.goalId, {
  956. expectedEpoch: repeated.epoch,
  957. fingerprint: "fingerprint-b",
  958. limit: 3,
  959. }),
  960. ).resolves.toMatchObject({
  961. action: "none",
  962. goal: { replyFingerprint: "fingerprint-b", noProgressStreak: 0 },
  963. });
  964. });
  965. });
  966. it("returns typed stale results without mutating a newer Goal epoch", async () => {
  967. await withDataDir(async (dataDir) => {
  968. let now = 1_700_000_000_000;
  969. const store = new SqliteThreadGoalStore(dataDir, () => now);
  970. const created = await store.create({
  971. sessionId: "sess_breaker_stale",
  972. objective: "audit",
  973. });
  974. const observed = await store.updateBreaker(created.goalId, {
  975. expectedEpoch: created.updatedAt,
  976. fingerprint: "previous-fingerprint",
  977. limit: 3,
  978. });
  979. if (observed.action === "stale")
  980. throw new Error("unexpected stale breaker result");
  981. now += 1;
  982. const edited = await store.patch(created.goalId, {
  983. objective: "new objective",
  984. });
  985. await expect(
  986. store.updateBreaker(created.goalId, {
  987. expectedEpoch: observed.epoch,
  988. fingerprint: "stale-fingerprint",
  989. limit: 3,
  990. }),
  991. ).resolves.toMatchObject({
  992. action: "stale",
  993. staleReason: "goal_epoch",
  994. goal: { updatedAt: edited.updatedAt, objective: "new objective" },
  995. });
  996. expect(await store.getById(created.goalId)).toMatchObject({
  997. replyFingerprint: null,
  998. noProgressStreak: 0,
  999. });
  1000. await expect(
  1001. store.updateBreaker("missing-goal", {
  1002. expectedEpoch: 1,
  1003. fingerprint: "fingerprint",
  1004. limit: 3,
  1005. }),
  1006. ).resolves.toEqual({ action: "stale", staleReason: "missing_goal" });
  1007. });
  1008. });
  1009. it("resets breaker state only for the exact active epoch after explicit user work", async () => {
  1010. await withDataDir(async (dataDir) => {
  1011. let now = 1_700_000_000_000;
  1012. const store = new SqliteThreadGoalStore(dataDir, () => now);
  1013. const created = await store.create({
  1014. sessionId: "sess_user_reset",
  1015. objective: "audit",
  1016. });
  1017. const first = await store.updateBreaker(created.goalId, {
  1018. expectedEpoch: created.updatedAt,
  1019. fingerprint: "same",
  1020. limit: 3,
  1021. });
  1022. if (first.action === "stale")
  1023. throw new Error("unexpected stale breaker result");
  1024. const repeated = await store.updateBreaker(created.goalId, {
  1025. expectedEpoch: first.epoch,
  1026. fingerprint: "same",
  1027. limit: 3,
  1028. });
  1029. if (repeated.action === "stale")
  1030. throw new Error("unexpected stale breaker result");
  1031. now += 1;
  1032. await expect(
  1033. store.resetBreakerAtEpoch(created.goalId, repeated.epoch - 1),
  1034. ).resolves.toBeUndefined();
  1035. const reset = await store.resetBreakerAtEpoch(
  1036. created.goalId,
  1037. repeated.epoch,
  1038. );
  1039. expect(reset).toMatchObject({
  1040. replyFingerprint: null,
  1041. noProgressStreak: 0,
  1042. });
  1043. expect(reset?.updatedAt).toBeGreaterThan(repeated.epoch);
  1044. });
  1045. });
  1046. it("applies a typed final-admission stop only to the exact active epoch", async () => {
  1047. await withDataDir(async (dataDir) => {
  1048. const store = new SqliteThreadGoalStore(dataDir, () => 1_700_000_000_000);
  1049. const created = await store.create({
  1050. sessionId: "sess_final_pause",
  1051. objective: "audit",
  1052. });
  1053. await expect(
  1054. store.transitionActiveAtEpoch(created.goalId, created.updatedAt - 1, {
  1055. status: "budget_limited",
  1056. statusReason: "budget_limited(token)",
  1057. }),
  1058. ).resolves.toBeUndefined();
  1059. await expect(
  1060. store.transitionActiveAtEpoch(created.goalId, created.updatedAt, {
  1061. status: "budget_limited",
  1062. statusReason: "budget_limited(token)",
  1063. }),
  1064. ).resolves.toMatchObject({
  1065. status: "budget_limited",
  1066. statusReason: "budget_limited(token)",
  1067. });
  1068. });
  1069. });
  1070. it("pauseActiveBySession atomically transitions only active goals to paused", async () => {
  1071. await withDataDir(async (dataDir) => {
  1072. let now = 1_700_000_000_000;
  1073. const store = new SqliteThreadGoalStore(dataDir, () => now);
  1074. const created = await store.create({
  1075. sessionId: "sess_abort",
  1076. objective: "audit",
  1077. });
  1078. const paused = await store.pauseActiveBySession(created.sessionId);
  1079. expect(paused).toMatchObject({
  1080. goalId: created.goalId,
  1081. status: "paused",
  1082. statusReason: "paused(user_requested)",
  1083. });
  1084. expect(paused?.updatedAt).toBeGreaterThan(created.updatedAt);
  1085. now += 500;
  1086. expect(
  1087. await store.pauseActiveBySession(created.sessionId),
  1088. ).toBeUndefined();
  1089. expect((await store.getById(created.goalId))?.updatedAt).toBe(
  1090. paused?.updatedAt,
  1091. );
  1092. });
  1093. });
  1094. it.each([
  1095. "paused",
  1096. "blocked",
  1097. "complete",
  1098. "budget_limited",
  1099. "usage_limited",
  1100. ] as const)(
  1101. "pauseActiveBySession does not overwrite a %s goal",
  1102. async (status) => {
  1103. await withDataDir(async (dataDir) => {
  1104. const store = new SqliteThreadGoalStore(
  1105. dataDir,
  1106. () => 1_700_000_000_000,
  1107. );
  1108. const created = await store.create({
  1109. sessionId: `sess_abort_${status}`,
  1110. objective: "audit",
  1111. });
  1112. await store.patch(created.goalId, { status });
  1113. expect(
  1114. await store.pauseActiveBySession(created.sessionId),
  1115. ).toBeUndefined();
  1116. expect((await store.getById(created.goalId))?.status).toBe(status);
  1117. });
  1118. },
  1119. );
  1120. it("atomically rejects a model status write when the goal is paused", async () => {
  1121. await withDataDir(async (dataDir) => {
  1122. const store = new SqliteThreadGoalStore(dataDir, () => 1_700_000_000_000);
  1123. const created = await store.create({
  1124. sessionId: "sess_model_race",
  1125. objective: "audit",
  1126. });
  1127. await store.patch(created.goalId, { status: "paused" });
  1128. await expect(
  1129. store.patch(created.goalId, {
  1130. status: "complete",
  1131. rejectIfCurrentStatus: "paused",
  1132. }),
  1133. ).rejects.toMatchObject({ currentStatus: "paused" });
  1134. expect((await store.getById(created.goalId))?.status).toBe("paused");
  1135. });
  1136. });
  1137. it("atomically rejects a model status write when the captured objective was edited", async () => {
  1138. await withDataDir(async (dataDir) => {
  1139. const store = new SqliteThreadGoalStore(dataDir, () => 1_700_000_000_000);
  1140. const created = await store.create({
  1141. sessionId: "sess_objective_race",
  1142. objective: "old objective",
  1143. });
  1144. await store.patch(created.goalId, { objective: "new objective" });
  1145. await expect(
  1146. store.patch(created.goalId, {
  1147. status: "complete",
  1148. rejectIfObjectiveChangedFrom: "old objective",
  1149. }),
  1150. ).rejects.toMatchObject({ currentObjective: "new objective" });
  1151. expect(await store.getById(created.goalId)).toMatchObject({
  1152. objective: "new objective",
  1153. status: "active",
  1154. });
  1155. });
  1156. });
  1157. it("bumpBoundUsage adds deltas atomically and chains its decision epoch", async () => {
  1158. await withDataDir(async (dataDir) => {
  1159. let now = 1_700_000_000_000;
  1160. const store = new SqliteThreadGoalStore(dataDir, () => now);
  1161. const created = await store.create({
  1162. sessionId: "sess_b",
  1163. objective: "audit",
  1164. });
  1165. now = 1_700_000_000_500;
  1166. const after1 = await store.bumpBoundUsage(
  1167. bindingFor(created),
  1168. { tokens: 1_500, activeSeconds: 12, mainTurns: 1 },
  1169. TEST_LIMITS,
  1170. );
  1171. expect(after1?.goal.tokensUsed).toBe(1_500);
  1172. expect(after1?.goal.timeUsedSeconds).toBe(12);
  1173. expect(after1?.goal.turnsUsed).toBe(1);
  1174. expect(after1?.goal.updatedAt).toBe(now);
  1175. expect(after1?.transitioned).toBeNull();
  1176. now = 1_700_000_001_000;
  1177. const after2 = await store.bumpBoundUsage(
  1178. bindingFor(after1.goal!, {
  1179. admittedGoalUpdatedAt: after1.decisionEpoch,
  1180. turnId: "turn-bound-2",
  1181. }),
  1182. { tokens: 3_200, activeSeconds: 8, mainTurns: 1 },
  1183. TEST_LIMITS,
  1184. );
  1185. expect(after2?.goal.tokensUsed).toBe(4_700);
  1186. expect(after2?.goal.timeUsedSeconds).toBe(20);
  1187. expect(after2?.goal.turnsUsed).toBe(2);
  1188. expect(after2?.goal.updatedAt).toBe(now);
  1189. expect(after2?.transitioned).toBeNull();
  1190. });
  1191. });
  1192. it("bumpBoundUsage no-ops a zero summary delta but still returns the current epoch", async () => {
  1193. await withDataDir(async (dataDir) => {
  1194. let now = 1_700_000_000_000;
  1195. const store = new SqliteThreadGoalStore(dataDir, () => now);
  1196. const created = await store.create({
  1197. sessionId: "sess_c",
  1198. objective: "audit",
  1199. });
  1200. now = 1_700_000_000_900;
  1201. const result = await store.bumpBoundUsage(
  1202. bindingFor(created),
  1203. { tokens: 0, activeSeconds: 0, mainTurns: 0 },
  1204. TEST_LIMITS,
  1205. );
  1206. expect(result?.goal.tokensUsed).toBe(0);
  1207. expect(result?.goal.timeUsedSeconds).toBe(0);
  1208. expect(result?.goal.updatedAt).toBe(created.updatedAt);
  1209. expect(result?.transitioned).toBeNull();
  1210. });
  1211. });
  1212. it("bumpBoundUsage clamps negative inputs to 0 (defence-in-depth)", async () => {
  1213. await withDataDir(async (dataDir) => {
  1214. const store = new SqliteThreadGoalStore(dataDir, () => 1_700_000_000_000);
  1215. const created = await store.create({
  1216. sessionId: "sess_d",
  1217. objective: "audit",
  1218. });
  1219. const result = await store.bumpBoundUsage(
  1220. bindingFor(created),
  1221. { tokens: -5, activeSeconds: -10, mainTurns: 0 },
  1222. TEST_LIMITS,
  1223. );
  1224. expect(result?.goal.tokensUsed).toBe(0);
  1225. expect(result?.goal.timeUsedSeconds).toBe(0);
  1226. });
  1227. });
  1228. it("bumpBoundUsage returns typed missing_goal when the binding no longer exists", async () => {
  1229. await withDataDir(async (dataDir) => {
  1230. const store = new SqliteThreadGoalStore(dataDir);
  1231. const result = await store.bumpBoundUsage(
  1232. {
  1233. goalId: "tg_nonexistent",
  1234. admittedGoalUpdatedAt: 1,
  1235. objectiveDigest: digestThreadGoalObjective("missing"),
  1236. turnId: "turn-missing",
  1237. },
  1238. { tokens: 100, activeSeconds: 1, mainTurns: 1 },
  1239. TEST_LIMITS,
  1240. );
  1241. expect(result).toEqual({ staleReason: "missing_goal" });
  1242. });
  1243. });
  1244. it("bumpBoundUsage flips status at the effective token limit", async () => {
  1245. await withDataDir(async (dataDir) => {
  1246. const store = new SqliteThreadGoalStore(dataDir, () => 1_700_000_000_000);
  1247. const created = await store.create({
  1248. sessionId: "sess_budget",
  1249. objective: "audit",
  1250. tokenBudget: 1_000,
  1251. });
  1252. // 600 < 1000 — still active
  1253. const r1 = await store.bumpBoundUsage(
  1254. bindingFor(created),
  1255. { tokens: 600, activeSeconds: 5, mainTurns: 1 },
  1256. { tokens: 1_000, mainTurns: 10, activeSeconds: 1_000 },
  1257. );
  1258. expect(r1?.goal.status).toBe("active");
  1259. expect(r1?.transitioned).toBeNull();
  1260. // 600 + 400 = 1000 — `>= tokenBudget` triggers the transition
  1261. const r2 = await store.bumpBoundUsage(
  1262. bindingFor(r1.goal!, {
  1263. admittedGoalUpdatedAt: r1.decisionEpoch,
  1264. turnId: "turn-budget-2",
  1265. }),
  1266. { tokens: 400, activeSeconds: 3, mainTurns: 1 },
  1267. { tokens: 1_000, mainTurns: 10, activeSeconds: 1_000 },
  1268. );
  1269. expect(r2?.goal.status).toBe("budget_limited");
  1270. expect(r2?.transitioned).toBe("token");
  1271. });
  1272. });
  1273. it("bumpBoundUsage records summary overrun without transitioning or advancing its stable epoch", async () => {
  1274. await withDataDir(async (dataDir) => {
  1275. const store = new SqliteThreadGoalStore(dataDir, () => 1_700_000_000_000);
  1276. const created = await store.create({
  1277. sessionId: "sess_double",
  1278. objective: "audit",
  1279. tokenBudget: 100,
  1280. });
  1281. const limited = await store.bumpBoundUsage(
  1282. bindingFor(created),
  1283. { tokens: 200, activeSeconds: 1, mainTurns: 1 },
  1284. { tokens: 100, mainTurns: 10, activeSeconds: 1_000 },
  1285. );
  1286. const r2 = await store.bumpBoundUsage(
  1287. bindingFor(limited.goal!, {
  1288. admittedGoalUpdatedAt: limited.decisionEpoch,
  1289. turnId: "turn-budget-summary",
  1290. }),
  1291. { tokens: 50, activeSeconds: 1, mainTurns: 0 },
  1292. { tokens: 100, mainTurns: 10, activeSeconds: 1_000 },
  1293. );
  1294. expect(r2?.goal.status).toBe("budget_limited");
  1295. expect(r2?.transitioned).toBeNull();
  1296. expect(r2.decisionEpoch).toBe(limited.decisionEpoch);
  1297. expect(r2.goal?.turnsUsed).toBe(1);
  1298. });
  1299. });
  1300. /*
  1301. * The invariant this trio pins: a write that only records what was already
  1302. * spent is a fact *about* the Goal, while the decision epoch is the token
  1303. * saying *who owns its next step*. A stale charge — the late subagent
  1304. * verifier being the only producer today — must therefore never retire the
  1305. * execution binding the Goal has since admitted, unless the charge itself
  1306. * makes a lifecycle decision by crossing a budget.
  1307. */
  1308. it("bumpBoundUsage records a stale charge without invalidating the current execution binding", async () => {
  1309. await withDataDir(async (dataDir) => {
  1310. let now = 1_700_000_000_000;
  1311. const store = new SqliteThreadGoalStore(dataDir, () => now);
  1312. const created = await store.create({
  1313. sessionId: "sess_stale_epoch",
  1314. objective: "audit",
  1315. });
  1316. now = 1_700_000_000_500;
  1317. const mainTurn = await store.bumpBoundUsage(
  1318. bindingFor(created),
  1319. { tokens: 1_752, activeSeconds: 108, mainTurns: 1 },
  1320. TEST_LIMITS,
  1321. );
  1322. const ea = mainTurn.decisionEpoch;
  1323. if (ea === undefined)
  1324. throw new Error("expected the main Turn charge to land");
  1325. // The explicit user Turn's breaker reset, not a `patch`: an objective
  1326. // edit would add `objective_digest` to the staleness reason and stop
  1327. // testing the epoch dimension on its own.
  1328. now = 1_700_000_000_800;
  1329. const afterReset = await store.resetBreakerAtEpoch(created.goalId, ea);
  1330. const e1 = afterReset?.updatedAt;
  1331. if (e1 === undefined)
  1332. throw new Error("expected the breaker reset to advance the epoch");
  1333. expect(e1).toBeGreaterThan(ea);
  1334. // The verifier dispatched at `ea` finishes afterwards and is charged.
  1335. now = 1_700_000_001_200;
  1336. const staleCharge = await store.bumpBoundUsage(
  1337. bindingFor(created, {
  1338. admittedGoalUpdatedAt: ea,
  1339. turnId: "turn-verifier",
  1340. }),
  1341. { tokens: 1_887, activeSeconds: 0, mainTurns: 0 },
  1342. TEST_LIMITS,
  1343. );
  1344. expect(staleCharge.staleReason).toBe("goal_epoch");
  1345. // Accounting is unconditional: the tokens were really spent.
  1346. expect(staleCharge.goal?.tokensUsed).toBe(1_752 + 1_887);
  1347. expect(staleCharge.goal?.turnsUsed).toBe(1);
  1348. // And the Turn admitted at `e1` keeps its binding.
  1349. expect(staleCharge.goal?.updatedAt).toBe(e1);
  1350. expect(staleCharge.decisionEpoch).toBe(e1);
  1351. expect((await store.getById(created.goalId))?.updatedAt).toBe(e1);
  1352. });
  1353. });
  1354. it("bumpBoundUsage still transitions and advances the epoch when a stale charge crosses the budget", async () => {
  1355. await withDataDir(async (dataDir) => {
  1356. let now = 1_700_000_000_000;
  1357. const store = new SqliteThreadGoalStore(dataDir, () => now);
  1358. const created = await store.create({
  1359. sessionId: "sess_stale_overrun",
  1360. objective: "audit",
  1361. tokenBudget: 2_000,
  1362. });
  1363. const limits = {
  1364. tokens: 2_000,
  1365. mainTurns: 10,
  1366. activeSeconds: 1_000,
  1367. } as const;
  1368. now = 1_700_000_000_500;
  1369. const mainTurn = await store.bumpBoundUsage(
  1370. bindingFor(created),
  1371. { tokens: 900, activeSeconds: 5, mainTurns: 1 },
  1372. limits,
  1373. );
  1374. const ea = mainTurn.decisionEpoch;
  1375. if (ea === undefined)
  1376. throw new Error("expected the main Turn charge to land");
  1377. now = 1_700_000_000_800;
  1378. const e1 = (await store.resetBreakerAtEpoch(created.goalId, ea))
  1379. ?.updatedAt;
  1380. if (e1 === undefined)
  1381. throw new Error("expected the breaker reset to advance the epoch");
  1382. now = 1_700_000_001_200;
  1383. const staleOverrun = await store.bumpBoundUsage(
  1384. bindingFor(created, {
  1385. admittedGoalUpdatedAt: ea,
  1386. turnId: "turn-verifier",
  1387. }),
  1388. { tokens: 1_500, activeSeconds: 0, mainTurns: 0 },
  1389. limits,
  1390. );
  1391. // A budget crossing *is* a lifecycle decision, so it keeps the right to
  1392. // retire whatever the Goal was running.
  1393. expect(staleOverrun.staleReason).toBe("goal_epoch");
  1394. expect(staleOverrun.transitioned).toBe("token");
  1395. expect(staleOverrun.goal?.status).toBe("budget_limited");
  1396. expect(staleOverrun.goal?.updatedAt).not.toBe(e1);
  1397. expect(staleOverrun.goal?.updatedAt).toBeGreaterThan(e1);
  1398. });
  1399. });
  1400. it("bumpBoundUsage keeps the execution wait consistent across the epoch it publishes", async () => {
  1401. await withDataDir(async (dataDir) => {
  1402. let now = 1_700_000_000_000;
  1403. const store = new SqliteThreadGoalStore(dataDir, () => now);
  1404. const created = await store.create({
  1405. sessionId: "sess_stale_wait",
  1406. objective: "audit",
  1407. });
  1408. now = 1_700_000_000_500;
  1409. const mainTurn = await store.bumpBoundUsage(
  1410. bindingFor(created),
  1411. { tokens: 1_000, activeSeconds: 5, mainTurns: 1 },
  1412. TEST_LIMITS,
  1413. );
  1414. const ea = mainTurn.decisionEpoch;
  1415. if (ea === undefined)
  1416. throw new Error("expected the main Turn charge to land");
  1417. now = 1_700_000_000_800;
  1418. const e1 = (await store.resetBreakerAtEpoch(created.goalId, ea))
  1419. ?.updatedAt;
  1420. if (e1 === undefined)
  1421. throw new Error("expected the breaker reset to advance the epoch");
  1422. await store.setExecutionWaitAtEpoch({
  1423. goalId: created.goalId,
  1424. expectedUpdatedAt: e1,
  1425. reason: "required_background",
  1426. });
  1427. expect((await store.getById(created.goalId))?.executionWait?.reason).toBe(
  1428. "required_background",
  1429. );
  1430. now = 1_700_000_001_200;
  1431. const staleCharge = await store.bumpBoundUsage(
  1432. bindingFor(created, {
  1433. admittedGoalUpdatedAt: ea,
  1434. turnId: "turn-verifier",
  1435. }),
  1436. { tokens: 500, activeSeconds: 0, mainTurns: 0 },
  1437. TEST_LIMITS,
  1438. );
  1439. // The returned goal is published as a `thread_goal.updated` event while
  1440. // the row behind `getById` answers the API, so the two must not diverge.
  1441. expect(staleCharge.goal?.updatedAt).toBe(e1);
  1442. expect(staleCharge.goal?.executionWait?.reason).toBe(
  1443. "required_background",
  1444. );
  1445. expect(staleCharge.goal?.executionWait).toEqual(
  1446. (await store.getById(created.goalId))?.executionWait,
  1447. );
  1448. // The reverse lock: a charge that does advance the epoch retires the
  1449. // wait in both projections, exactly as before.
  1450. now = 1_700_000_001_600;
  1451. const currentCharge = await store.bumpBoundUsage(
  1452. bindingFor(created, {
  1453. admittedGoalUpdatedAt: e1,
  1454. turnId: "turn-current",
  1455. }),
  1456. { tokens: 100, activeSeconds: 1, mainTurns: 1 },
  1457. TEST_LIMITS,
  1458. );
  1459. expect(currentCharge.staleReason).toBeUndefined();
  1460. expect(currentCharge.goal?.updatedAt).toBeGreaterThan(e1);
  1461. expect(currentCharge.goal?.executionWait).toBeNull();
  1462. expect((await store.getById(created.goalId))?.executionWait).toBeNull();
  1463. });
  1464. });
  1465. it("bumpBoundUsage records usage without transitioning when all dimensions are uncapped", async () => {
  1466. await withDataDir(async (dataDir) => {
  1467. const store = new SqliteThreadGoalStore(dataDir, () => 1_700_000_000_000);
  1468. const created = await store.create({
  1469. sessionId: "sess_nobudget",
  1470. objective: "audit",
  1471. });
  1472. const result = await store.bumpBoundUsage(
  1473. bindingFor(created),
  1474. { tokens: 1_000_000, activeSeconds: 1_000_000, mainTurns: 1 },
  1475. { tokens: null, mainTurns: null, activeSeconds: null },
  1476. );
  1477. expect(result?.goal.status).toBe("active");
  1478. expect(result?.goal.tokensUsed).toBe(1_000_000);
  1479. expect(result?.goal.timeUsedSeconds).toBe(1_000_000);
  1480. expect(result?.goal.turnsUsed).toBe(1);
  1481. expect(result?.transitioned).toBeNull();
  1482. });
  1483. });
  1484. it("patch keeps accounting columns untouched and accepts tokenBudget overrides", async () => {
  1485. await withDataDir(async (dataDir) => {
  1486. let now = 1_700_000_000_000;
  1487. const store = new SqliteThreadGoalStore(dataDir, () => now);
  1488. const created = await store.create({
  1489. sessionId: "sess_e",
  1490. objective: "audit",
  1491. tokenBudget: 500,
  1492. });
  1493. now = 1_700_000_000_500;
  1494. await store.bumpBoundUsage(
  1495. bindingFor(created),
  1496. { tokens: 200, activeSeconds: 7, mainTurns: 1 },
  1497. TEST_LIMITS,
  1498. );
  1499. now = 1_700_000_001_000;
  1500. const patched = await store.patch(created.goalId, {
  1501. status: "paused",
  1502. tokenBudget: 2_000,
  1503. });
  1504. expect(patched.status).toBe("paused");
  1505. expect(patched.tokensUsed).toBe(200);
  1506. expect(patched.timeUsedSeconds).toBe(7);
  1507. expect(patched.tokenBudget).toBe(2_000);
  1508. // patch with explicit null clears the cap.
  1509. now = 1_700_000_002_000;
  1510. const cleared = await store.patch(created.goalId, { tokenBudget: null });
  1511. expect(cleared.tokenBudget).toBeNull();
  1512. });
  1513. });
  1514. it("restarts a paused goal via one objective+status patch, keeping budget and usage", async () => {
  1515. await withDataDir(async (dataDir) => {
  1516. let now = 1_700_000_000_000;
  1517. const store = new SqliteThreadGoalStore(dataDir, () => now);
  1518. const created = await store.create({
  1519. sessionId: "sess_restart",
  1520. objective: "audit",
  1521. tokenBudget: 5_000,
  1522. });
  1523. now = 1_700_000_000_500;
  1524. await store.bumpBoundUsage(
  1525. bindingFor(created),
  1526. { tokens: 200, activeSeconds: 7, mainTurns: 1 },
  1527. TEST_LIMITS,
  1528. );
  1529. now = 1_700_000_001_000;
  1530. const paused = await store.patch(created.goalId, { status: "paused" });
  1531. expect(paused.status).toBe("paused");
  1532. now = 1_700_000_002_000;
  1533. const restarted = await store.patch(created.goalId, {
  1534. objective: "audit, but the flaky suite first",
  1535. status: "active",
  1536. });
  1537. expect(restarted.status).toBe("active");
  1538. expect(restarted.objective).toBe("audit, but the flaky suite first");
  1539. // Budget and accounting are inherited; only the run state restarts.
  1540. expect(restarted.tokenBudget).toBe(5_000);
  1541. expect(restarted.tokensUsed).toBe(200);
  1542. expect(restarted.turnsUsed).toBe(1);
  1543. expect(restarted.timeUsedSeconds).toBe(7);
  1544. // Resume semantics: the no-progress breaker starts fresh.
  1545. expect(restarted.noProgressStreak).toBe(0);
  1546. expect(restarted.replyFingerprint).toBeNull();
  1547. });
  1548. });
  1549. it("rowToState reads tokenBudget back from disk (v15 roundtrip via a fresh store instance)", async () => {
  1550. await withDataDir(async (dataDir) => {
  1551. const store = new SqliteThreadGoalStore(dataDir, () => 1_700_000_000_000);
  1552. const created = await store.create({
  1553. sessionId: "sess_legacy",
  1554. objective: "audit",
  1555. tokenBudget: 9_000,
  1556. });
  1557. await store.bumpBoundUsage(
  1558. bindingFor(created),
  1559. { tokens: 4_321, activeSeconds: 17, mainTurns: 1 },
  1560. TEST_LIMITS,
  1561. );
  1562. const fresh = new SqliteThreadGoalStore(dataDir);
  1563. const row = await fresh.getById(created.goalId);
  1564. expect(row?.tokensUsed).toBe(4_321);
  1565. expect(row?.timeUsedSeconds).toBe(17);
  1566. expect(row?.tokenBudget).toBe(9_000);
  1567. });
  1568. });
  1569. });
  1570. describe("SqliteThreadGoalStore — verifier CAS", () => {
  1571. it("persists the completion proposal in the same CAS as a not-met verdict", async () => {
  1572. await withDataDir(async (dataDir) => {
  1573. let now = 1_700_000_000_000;
  1574. const store = new SqliteThreadGoalStore(dataDir, () => now);
  1575. const created = await store.create({
  1576. sessionId: "sess_verifier_proposal",
  1577. objective: "Ship with evidence",
  1578. });
  1579. now += 1;
  1580. const result = await store.recordVerification({
  1581. goalId: created.goalId,
  1582. expectedEpoch: created.updatedAt,
  1583. objectiveDigest: digestThreadGoalObjective(created.objective),
  1584. result: verificationResult(created),
  1585. repeatedNotMetLimit: 5,
  1586. workerProposal: {
  1587. type: "complete",
  1588. turnId: "turn-worker",
  1589. summary: "Implementation is ready for review.",
  1590. },
  1591. });
  1592. expect(result).toMatchObject({
  1593. status: "settled",
  1594. goal: {
  1595. status: "active",
  1596. lastVerification: { verdict: "not_met" },
  1597. lastWorkerProposal: {
  1598. v: 1,
  1599. source: "worker",
  1600. type: "complete",
  1601. turnId: "turn-worker",
  1602. summary: "Implementation is ready for review.",
  1603. at: now,
  1604. },
  1605. },
  1606. });
  1607. });
  1608. });
  1609. it("clears verifier and worker evidence when the objective changes", async () => {
  1610. await withDataDir(async (dataDir) => {
  1611. let now = 1_700_000_000_000;
  1612. const store = new SqliteThreadGoalStore(dataDir, () => now);
  1613. const created = await store.create({
  1614. sessionId: "sess_objective_evidence_reset",
  1615. objective: "Ship the first objective",
  1616. });
  1617. now += 1;
  1618. const recorded = await store.recordVerification({
  1619. goalId: created.goalId,
  1620. expectedEpoch: created.updatedAt,
  1621. objectiveDigest: digestThreadGoalObjective(created.objective),
  1622. result: verificationResult(created),
  1623. repeatedNotMetLimit: 5,
  1624. workerProposal: {
  1625. type: "complete",
  1626. turnId: "turn-first-objective",
  1627. summary: "Evidence for the first objective.",
  1628. },
  1629. });
  1630. if (recorded.status !== "settled")
  1631. throw new Error("expected verification settlement");
  1632. now += 1;
  1633. await expect(
  1634. store.patch(created.goalId, {
  1635. objective: "Ship the replacement objective",
  1636. }),
  1637. ).resolves.toMatchObject({
  1638. objective: "Ship the replacement objective",
  1639. lastVerification: undefined,
  1640. lastWorkerProposal: undefined,
  1641. });
  1642. expect(await store.getById(created.goalId)).toMatchObject({
  1643. lastVerification: undefined,
  1644. lastWorkerProposal: undefined,
  1645. });
  1646. });
  1647. });
  1648. it("normalizes missing gaps and increments only the same consecutive fingerprint", async () => {
  1649. await withDataDir(async (dataDir) => {
  1650. let now = 1_700_000_000_000;
  1651. const store = new SqliteThreadGoalStore(dataDir, () => now);
  1652. const created = await store.create({
  1653. sessionId: "sess_verifier_streak",
  1654. objective: "Ship the verified result",
  1655. });
  1656. now += 1;
  1657. const first = await store.recordVerification({
  1658. goalId: created.goalId,
  1659. expectedEpoch: created.updatedAt,
  1660. objectiveDigest: digestThreadGoalObjective(created.objective),
  1661. result: verificationResult(created, {
  1662. missing: [" beta proof ", "alpha proof", "alpha proof"],
  1663. }),
  1664. repeatedNotMetLimit: 5,
  1665. });
  1666. expect(first).toMatchObject({
  1667. status: "settled",
  1668. goal: {
  1669. status: "active",
  1670. lastVerification: {
  1671. verdict: "not_met",
  1672. missing: ["alpha proof", "beta proof"],
  1673. notMetStreak: 1,
  1674. },
  1675. },
  1676. });
  1677. if (first.status !== "settled")
  1678. throw new Error("expected first verification settlement");
  1679. const fingerprint = first.goal.lastVerification?.missingFingerprint;
  1680. expect(fingerprint).toMatch(/^[a-f0-9]{64}$/);
  1681. now += 1;
  1682. const repeated = await store.recordVerification({
  1683. goalId: created.goalId,
  1684. expectedEpoch: first.decisionEpoch,
  1685. objectiveDigest: digestThreadGoalObjective(created.objective),
  1686. result: verificationResult(created, {
  1687. missing: ["beta proof", " alpha proof "],
  1688. }),
  1689. repeatedNotMetLimit: 5,
  1690. });
  1691. expect(repeated).toMatchObject({
  1692. status: "settled",
  1693. goal: {
  1694. status: "active",
  1695. lastVerification: {
  1696. missingFingerprint: fingerprint,
  1697. notMetStreak: 2,
  1698. },
  1699. },
  1700. });
  1701. if (repeated.status !== "settled")
  1702. throw new Error("expected repeated verification settlement");
  1703. now += 1;
  1704. const progressed = await store.recordVerification({
  1705. goalId: created.goalId,
  1706. expectedEpoch: repeated.decisionEpoch,
  1707. objectiveDigest: digestThreadGoalObjective(created.objective),
  1708. result: verificationResult(created, { missing: ["release evidence"] }),
  1709. repeatedNotMetLimit: 5,
  1710. });
  1711. expect(progressed).toMatchObject({
  1712. status: "settled",
  1713. goal: { status: "active", lastVerification: { notMetStreak: 1 } },
  1714. });
  1715. });
  1716. });
  1717. it("pauses no-progress in the same write that reaches the repeated gap limit", async () => {
  1718. await withDataDir(async (dataDir) => {
  1719. let now = 1_700_000_000_000;
  1720. const store = new SqliteThreadGoalStore(dataDir, () => now);
  1721. const created = await store.create({
  1722. sessionId: "sess_verifier_pause",
  1723. objective: "Close the same gap",
  1724. });
  1725. now += 1;
  1726. const first = await store.recordVerification({
  1727. goalId: created.goalId,
  1728. expectedEpoch: created.updatedAt,
  1729. objectiveDigest: digestThreadGoalObjective(created.objective),
  1730. result: verificationResult(created),
  1731. repeatedNotMetLimit: 2,
  1732. });
  1733. if (first.status !== "settled")
  1734. throw new Error("expected first verification settlement");
  1735. now += 1;
  1736. const stopped = await store.recordVerification({
  1737. goalId: created.goalId,
  1738. expectedEpoch: first.decisionEpoch,
  1739. objectiveDigest: digestThreadGoalObjective(created.objective),
  1740. result: verificationResult(created),
  1741. repeatedNotMetLimit: 2,
  1742. });
  1743. expect(stopped).toMatchObject({
  1744. status: "settled",
  1745. goal: {
  1746. status: "paused",
  1747. statusReason: "paused(no_progress)",
  1748. lastVerification: { notMetStreak: 2 },
  1749. },
  1750. });
  1751. });
  1752. });
  1753. it("commits a verifier terminal decision with the verdict and returns typed stale outcomes", async () => {
  1754. await withDataDir(async (dataDir) => {
  1755. let now = 1_700_000_000_000;
  1756. const store = new SqliteThreadGoalStore(dataDir, () => now);
  1757. const created = await store.create({
  1758. sessionId: "sess_verifier_terminal",
  1759. objective: "Prove completion",
  1760. });
  1761. const objectiveDigest = digestThreadGoalObjective(created.objective);
  1762. await expect(
  1763. store.recordVerification({
  1764. goalId: "missing-goal",
  1765. expectedEpoch: created.updatedAt,
  1766. objectiveDigest,
  1767. result: verificationResult(created),
  1768. repeatedNotMetLimit: 5,
  1769. }),
  1770. ).resolves.toEqual({ status: "stale", staleReason: "missing_goal" });
  1771. await expect(
  1772. store.recordVerification({
  1773. goalId: created.goalId,
  1774. expectedEpoch: created.updatedAt + 1,
  1775. objectiveDigest,
  1776. result: verificationResult(created),
  1777. repeatedNotMetLimit: 5,
  1778. }),
  1779. ).resolves.toMatchObject({ status: "stale", staleReason: "goal_epoch" });
  1780. await expect(
  1781. store.recordVerification({
  1782. goalId: created.goalId,
  1783. expectedEpoch: created.updatedAt,
  1784. objectiveDigest: digestThreadGoalObjective("different objective"),
  1785. result: verificationResult(created),
  1786. repeatedNotMetLimit: 5,
  1787. }),
  1788. ).resolves.toMatchObject({
  1789. status: "stale",
  1790. staleReason: "objective_digest",
  1791. });
  1792. now += 1;
  1793. const completed = await store.recordVerification({
  1794. goalId: created.goalId,
  1795. expectedEpoch: created.updatedAt,
  1796. objectiveDigest,
  1797. result: verificationResult(created, {
  1798. verdict: "met",
  1799. reason: "The current evidence proves every requirement.",
  1800. missing: [],
  1801. }),
  1802. repeatedNotMetLimit: 5,
  1803. decision: {
  1804. status: "complete",
  1805. statusReason: "complete(verifier_met)",
  1806. },
  1807. });
  1808. expect(completed).toMatchObject({
  1809. status: "settled",
  1810. goal: {
  1811. status: "complete",
  1812. statusReason: "complete(verifier_met)",
  1813. lastVerification: { verdict: "met", missing: [], notMetStreak: 0 },
  1814. },
  1815. });
  1816. if (completed.status !== "settled")
  1817. throw new Error("expected terminal settlement");
  1818. await expect(
  1819. store.recordVerification({
  1820. goalId: created.goalId,
  1821. expectedEpoch: completed.decisionEpoch,
  1822. objectiveDigest,
  1823. result: verificationResult(created),
  1824. repeatedNotMetLimit: 5,
  1825. }),
  1826. ).resolves.toMatchObject({ status: "stale", staleReason: "goal_status" });
  1827. });
  1828. });
  1829. });
  1830. describe("SqliteThreadGoalStore — bound settlement", () => {
  1831. it("atomically persists a worker block summary and rejects stale replacement evidence", async () => {
  1832. await withDataDir(async (dataDir) => {
  1833. let now = 1_700_000_000_000;
  1834. const store = new SqliteThreadGoalStore(dataDir, () => now);
  1835. const created = await store.create({
  1836. sessionId: "sess_block_evidence",
  1837. objective: "audit",
  1838. });
  1839. now += 10;
  1840. const settled = await store.settleBoundTurn({
  1841. goalId: created.goalId,
  1842. expectedEpoch: created.updatedAt,
  1843. objectiveDigest: digestThreadGoalObjective(created.objective),
  1844. next: { status: "blocked", statusReason: "blocked(worker_reported)" },
  1845. workerProposal: {
  1846. type: "blocked",
  1847. turnId: "turn-blocked",
  1848. summary: "The same external dependency remained unavailable.",
  1849. },
  1850. });
  1851. expect(settled).toMatchObject({
  1852. status: "settled",
  1853. goal: {
  1854. status: "blocked",
  1855. lastWorkerProposal: {
  1856. source: "worker",
  1857. type: "blocked",
  1858. turnId: "turn-blocked",
  1859. summary: "The same external dependency remained unavailable.",
  1860. at: now,
  1861. },
  1862. },
  1863. });
  1864. now += 10;
  1865. await expect(
  1866. store.settleBoundTurn({
  1867. goalId: created.goalId,
  1868. expectedEpoch: created.updatedAt,
  1869. objectiveDigest: digestThreadGoalObjective(created.objective),
  1870. next: {
  1871. status: "complete",
  1872. statusReason: "complete(worker_proposal)",
  1873. },
  1874. workerProposal: {
  1875. type: "complete",
  1876. turnId: "turn-stale",
  1877. summary:
  1878. "This stale evidence must not replace the accepted blocker.",
  1879. },
  1880. }),
  1881. ).resolves.toMatchObject({ status: "stale" });
  1882. expect(await store.getById(created.goalId)).toMatchObject({
  1883. lastWorkerProposal: {
  1884. type: "blocked",
  1885. turnId: "turn-blocked",
  1886. summary: "The same external dependency remained unavailable.",
  1887. },
  1888. });
  1889. });
  1890. });
  1891. it("returns each typed stale reason and still attributes usage to an existing bound Goal", async () => {
  1892. await withDataDir(async (dataDir) => {
  1893. let now = 1_700_000_000_000;
  1894. const store = new SqliteThreadGoalStore(dataDir, () => now);
  1895. const created = await store.create({
  1896. sessionId: "sess_bound_stale",
  1897. objective: "audit",
  1898. });
  1899. await expect(
  1900. store.bumpBoundUsage(
  1901. { ...bindingFor(created), goalId: "tg_missing" },
  1902. { tokens: 5, activeSeconds: 1, mainTurns: 1 },
  1903. TEST_LIMITS,
  1904. ),
  1905. ).resolves.toEqual({ staleReason: "missing_goal" });
  1906. now += 10;
  1907. const patched = await store.patch(created.goalId, {
  1908. objective: "audit revised",
  1909. });
  1910. now += 10;
  1911. const epochStale = await store.bumpBoundUsage(
  1912. bindingFor(created),
  1913. { tokens: 5, activeSeconds: 2, mainTurns: 1 },
  1914. TEST_LIMITS,
  1915. );
  1916. expect(epochStale).toMatchObject({
  1917. staleReason: "goal_epoch",
  1918. // A stale charge decides nothing, so it records the spend at the epoch
  1919. // the current owner holds instead of retiring that owner.
  1920. decisionEpoch: patched.updatedAt,
  1921. goal: {
  1922. goalId: created.goalId,
  1923. tokensUsed: 5,
  1924. turnsUsed: 1,
  1925. timeUsedSeconds: 2,
  1926. },
  1927. });
  1928. now += 10;
  1929. const digestStale = await store.bumpBoundUsage(
  1930. bindingFor(patched, {
  1931. admittedGoalUpdatedAt: epochStale.decisionEpoch,
  1932. objectiveDigest: digestThreadGoalObjective("wrong objective"),
  1933. turnId: "turn-digest-stale",
  1934. }),
  1935. { tokens: 7, activeSeconds: 3, mainTurns: 0 },
  1936. TEST_LIMITS,
  1937. );
  1938. expect(digestStale).toMatchObject({
  1939. staleReason: "objective_digest",
  1940. decisionEpoch: patched.updatedAt,
  1941. goal: { tokensUsed: 12, turnsUsed: 1, timeUsedSeconds: 5 },
  1942. });
  1943. });
  1944. });
  1945. it.each([
  1946. {
  1947. label: "token",
  1948. limits: { tokens: 10, mainTurns: 1, activeSeconds: 1 },
  1949. delta: { tokens: 10, activeSeconds: 1, mainTurns: 1 as const },
  1950. reason: "budget_limited(token)",
  1951. dimension: "token",
  1952. },
  1953. {
  1954. label: "main turn",
  1955. limits: { tokens: 100, mainTurns: 1, activeSeconds: 1 },
  1956. delta: { tokens: 1, activeSeconds: 1, mainTurns: 1 as const },
  1957. reason: "budget_limited(main_turn)",
  1958. dimension: "main_turn",
  1959. },
  1960. {
  1961. label: "active time",
  1962. limits: { tokens: 100, mainTurns: 10, activeSeconds: 1 },
  1963. delta: { tokens: 1, activeSeconds: 1, mainTurns: 1 as const },
  1964. reason: "budget_limited(active_time)",
  1965. dimension: "active_time",
  1966. },
  1967. ])(
  1968. "atomically stops at the $label limit with deterministic priority",
  1969. async (fixture) => {
  1970. await withDataDir(async (dataDir) => {
  1971. const store = new SqliteThreadGoalStore(
  1972. dataDir,
  1973. () => 1_700_000_000_010,
  1974. );
  1975. const created = await store.create({
  1976. sessionId: `sess_limit_${fixture.dimension}`,
  1977. objective: "audit",
  1978. });
  1979. const result = await store.bumpBoundUsage(
  1980. bindingFor(created),
  1981. fixture.delta,
  1982. fixture.limits,
  1983. );
  1984. expect(result).toMatchObject({
  1985. transitioned: fixture.dimension,
  1986. goal: { status: "budget_limited", statusReason: fixture.reason },
  1987. });
  1988. });
  1989. },
  1990. );
  1991. it("chains accounting epoch into settlement and rejects a later user mutation", async () => {
  1992. await withDataDir(async (dataDir) => {
  1993. let now = 1_700_000_000_000;
  1994. const store = new SqliteThreadGoalStore(dataDir, () => now);
  1995. const created = await store.create({
  1996. sessionId: "sess_epoch_chain",
  1997. objective: "audit",
  1998. });
  1999. now += 10;
  2000. const accounted = await store.bumpBoundUsage(
  2001. bindingFor(created),
  2002. { tokens: 5, activeSeconds: 2, mainTurns: 1 },
  2003. TEST_LIMITS,
  2004. );
  2005. expect(accounted.staleReason).toBeUndefined();
  2006. expect(accounted.decisionEpoch).toBe(now);
  2007. now += 10;
  2008. await store.patch(created.goalId, {
  2009. objective: "user changed objective",
  2010. });
  2011. now += 10;
  2012. await expect(
  2013. store.settleBoundTurn({
  2014. goalId: created.goalId,
  2015. expectedEpoch: accounted.decisionEpoch!,
  2016. objectiveDigest: digestThreadGoalObjective(created.objective),
  2017. next: {
  2018. status: "complete",
  2019. statusReason: "complete(worker_proposal)",
  2020. },
  2021. }),
  2022. ).resolves.toMatchObject({ status: "stale", staleReason: "goal_epoch" });
  2023. expect(await store.getById(created.goalId)).toMatchObject({
  2024. objective: "user changed objective",
  2025. status: "active",
  2026. });
  2027. });
  2028. });
  2029. it("settles an exact active epoch and preserves the budget decision epoch for summary usage", async () => {
  2030. await withDataDir(async (dataDir) => {
  2031. let now = 1_700_000_000_000;
  2032. const store = new SqliteThreadGoalStore(dataDir, () => now);
  2033. const settleGoal = await store.create({
  2034. sessionId: "sess_settle",
  2035. objective: "audit",
  2036. });
  2037. now += 10;
  2038. await expect(
  2039. store.settleBoundTurn({
  2040. goalId: settleGoal.goalId,
  2041. expectedEpoch: settleGoal.updatedAt,
  2042. objectiveDigest: digestThreadGoalObjective(settleGoal.objective),
  2043. next: { status: "paused", statusReason: "paused(infra_retryable)" },
  2044. }),
  2045. ).resolves.toMatchObject({
  2046. status: "settled",
  2047. decisionEpoch: now,
  2048. goal: { status: "paused", statusReason: "paused(infra_retryable)" },
  2049. });
  2050. now += 10;
  2051. const limited = await store.create({
  2052. sessionId: "sess_summary",
  2053. objective: "summarize",
  2054. tokenBudget: 1,
  2055. });
  2056. now += 10;
  2057. const transition = await store.bumpBoundUsage(
  2058. bindingFor(limited),
  2059. { tokens: 1, activeSeconds: 1, mainTurns: 1 },
  2060. { ...TEST_LIMITS, tokens: 1 },
  2061. );
  2062. now += 10;
  2063. const summary = await store.bumpBoundUsage(
  2064. bindingFor(transition.goal!, {
  2065. admittedGoalUpdatedAt: transition.decisionEpoch,
  2066. turnId: "turn-summary",
  2067. }),
  2068. { tokens: 3, activeSeconds: 2, mainTurns: 0 },
  2069. TEST_LIMITS,
  2070. );
  2071. expect(summary).toMatchObject({
  2072. decisionEpoch: transition.decisionEpoch,
  2073. transitioned: null,
  2074. goal: {
  2075. status: "budget_limited",
  2076. tokensUsed: 4,
  2077. turnsUsed: 1,
  2078. timeUsedSeconds: 3,
  2079. updatedAt: transition.decisionEpoch,
  2080. },
  2081. });
  2082. });
  2083. });
  2084. });