@cleocode/cleo 2026.4.82 → 2026.4.83

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js CHANGED
@@ -1760,11 +1760,17 @@ function rowToTask(row) {
1760
1760
  };
1761
1761
  }
1762
1762
  function taskToRow(task) {
1763
+ const status = task.status ?? "pending";
1764
+ let pipelineStage = task.pipelineStage ?? null;
1765
+ if (pipelineStage === null || pipelineStage === void 0) {
1766
+ if (status === "done") pipelineStage = "contribution";
1767
+ else if (status === "cancelled") pipelineStage = "cancelled";
1768
+ }
1763
1769
  return {
1764
1770
  id: task.id,
1765
1771
  title: task.title ?? "",
1766
1772
  description: task.description ?? null,
1767
- status: task.status ?? "pending",
1773
+ status,
1768
1774
  priority: task.priority ?? "medium",
1769
1775
  type: task.type ?? null,
1770
1776
  parentId: task.parentId ?? null,
@@ -1789,7 +1795,7 @@ function taskToRow(task) {
1789
1795
  createdBy: task.provenance?.createdBy ?? null,
1790
1796
  modifiedBy: task.provenance?.modifiedBy ?? null,
1791
1797
  sessionId: task.provenance?.sessionId ?? null,
1792
- pipelineStage: task.pipelineStage ?? null,
1798
+ pipelineStage,
1793
1799
  assignee: task.assignee ?? null
1794
1800
  };
1795
1801
  }
@@ -17403,9 +17409,9 @@ async function readSequenceFromDb(cwd, accessor) {
17403
17409
  return isValidSequenceState(value) ? value : null;
17404
17410
  }
17405
17411
  const { getDb: getDb4 } = await Promise.resolve().then(() => (init_sqlite2(), sqlite_exports));
17406
- const { eq: eq22 } = await import("drizzle-orm");
17412
+ const { eq: eq20 } = await import("drizzle-orm");
17407
17413
  const db = await getDb4(cwd);
17408
- const rows = await db.select().from(schemaMeta).where(eq22(schemaMeta.key, SEQUENCE_META_KEY)).all();
17414
+ const rows = await db.select().from(schemaMeta).where(eq20(schemaMeta.key, SEQUENCE_META_KEY)).all();
17409
17415
  const raw = rows[0]?.value;
17410
17416
  if (!raw) return null;
17411
17417
  try {
@@ -19236,7 +19242,7 @@ async function linkPipelineAdr(projectRoot, taskId) {
19236
19242
  return result;
19237
19243
  }
19238
19244
  const { getDb: getDb4 } = await Promise.resolve().then(() => (init_sqlite2(), sqlite_exports));
19239
- const { and: and17, eq: eq22 } = await import("drizzle-orm");
19245
+ const { and: and16, eq: eq20 } = await import("drizzle-orm");
19240
19246
  const db = await getDb4(projectRoot);
19241
19247
  const now2 = (/* @__PURE__ */ new Date()).toISOString();
19242
19248
  for (const filePath of matchingFiles) {
@@ -19246,7 +19252,7 @@ async function linkPipelineAdr(projectRoot, taskId) {
19246
19252
  const fm = record2.frontmatter;
19247
19253
  const content = readFileSync5(filePath, "utf-8");
19248
19254
  const relativePath = `.cleo/adrs/${filename}`;
19249
- const existing = await db.select({ id: architectureDecisions.id }).from(architectureDecisions).where(eq22(architectureDecisions.id, record2.id)).all();
19255
+ const existing = await db.select({ id: architectureDecisions.id }).from(architectureDecisions).where(eq20(architectureDecisions.id, record2.id)).all();
19250
19256
  const rowBase = {
19251
19257
  id: record2.id,
19252
19258
  title: record2.title,
@@ -19266,19 +19272,19 @@ async function linkPipelineAdr(projectRoot, taskId) {
19266
19272
  updatedAt: now2
19267
19273
  };
19268
19274
  if (existing.length > 0) {
19269
- await db.update(architectureDecisions).set(rowBase).where(eq22(architectureDecisions.id, record2.id));
19275
+ await db.update(architectureDecisions).set(rowBase).where(eq20(architectureDecisions.id, record2.id));
19270
19276
  } else {
19271
19277
  await db.insert(architectureDecisions).values({ ...rowBase, createdAt: now2 });
19272
19278
  }
19273
19279
  result.synced++;
19274
- await db.delete(adrTaskLinks).where(and17(eq22(adrTaskLinks.adrId, record2.id), eq22(adrTaskLinks.taskId, taskId)));
19280
+ await db.delete(adrTaskLinks).where(and16(eq20(adrTaskLinks.adrId, record2.id), eq20(adrTaskLinks.taskId, taskId)));
19275
19281
  await db.insert(adrTaskLinks).values({ adrId: record2.id, taskId, linkType: "implements" });
19276
19282
  result.linked.push({ adrId: record2.id, taskId });
19277
19283
  if (fm["Related ADRs"]) {
19278
19284
  const relatedIds = fm["Related ADRs"].split(",").map((r) => r.trim()).filter((r) => /^ADR-\d+$/.test(r));
19279
19285
  for (const toId of relatedIds) {
19280
19286
  try {
19281
- const targetExists = await db.select({ id: architectureDecisions.id }).from(architectureDecisions).where(eq22(architectureDecisions.id, toId)).all();
19287
+ const targetExists = await db.select({ id: architectureDecisions.id }).from(architectureDecisions).where(eq20(architectureDecisions.id, toId)).all();
19282
19288
  if (targetExists.length > 0) {
19283
19289
  await db.insert(adrRelations).values({ fromAdrId: record2.id, toAdrId: toId, relationType: "related" }).onConflictDoNothing();
19284
19290
  }
@@ -19442,7 +19448,7 @@ async function syncAdrsToDb(projectRoot) {
19442
19448
  return result;
19443
19449
  }
19444
19450
  const { getDb: getDb4 } = await Promise.resolve().then(() => (init_sqlite2(), sqlite_exports));
19445
- const { eq: eq22 } = await import("drizzle-orm");
19451
+ const { eq: eq20 } = await import("drizzle-orm");
19446
19452
  const db = await getDb4(projectRoot);
19447
19453
  const now2 = (/* @__PURE__ */ new Date()).toISOString();
19448
19454
  const allFiles = collectAdrFiles(adrsDir);
@@ -19459,7 +19465,7 @@ async function syncAdrsToDb(projectRoot) {
19459
19465
  let supersededById = fm["Superseded By"] ? extractAdrIdFromRef(fm["Superseded By"]) : null;
19460
19466
  let amendsId = fm.Amends ? extractAdrIdFromRef(fm.Amends) : null;
19461
19467
  if (supersedesId) {
19462
- const exists2 = await db.select({ id: architectureDecisions.id }).from(architectureDecisions).where(eq22(architectureDecisions.id, supersedesId)).all();
19468
+ const exists2 = await db.select({ id: architectureDecisions.id }).from(architectureDecisions).where(eq20(architectureDecisions.id, supersedesId)).all();
19463
19469
  if (exists2.length === 0) {
19464
19470
  result.warnings.push(
19465
19471
  `${record2.id}: supersedes target ${supersedesId} not found in DB, setting to null`
@@ -19468,7 +19474,7 @@ async function syncAdrsToDb(projectRoot) {
19468
19474
  }
19469
19475
  }
19470
19476
  if (supersededById) {
19471
- const exists2 = await db.select({ id: architectureDecisions.id }).from(architectureDecisions).where(eq22(architectureDecisions.id, supersededById)).all();
19477
+ const exists2 = await db.select({ id: architectureDecisions.id }).from(architectureDecisions).where(eq20(architectureDecisions.id, supersededById)).all();
19472
19478
  if (exists2.length === 0) {
19473
19479
  result.warnings.push(
19474
19480
  `${record2.id}: supersededBy target ${supersededById} not found in DB, setting to null`
@@ -19477,7 +19483,7 @@ async function syncAdrsToDb(projectRoot) {
19477
19483
  }
19478
19484
  }
19479
19485
  if (amendsId) {
19480
- const exists2 = await db.select({ id: architectureDecisions.id }).from(architectureDecisions).where(eq22(architectureDecisions.id, amendsId)).all();
19486
+ const exists2 = await db.select({ id: architectureDecisions.id }).from(architectureDecisions).where(eq20(architectureDecisions.id, amendsId)).all();
19481
19487
  if (exists2.length === 0) {
19482
19488
  result.warnings.push(
19483
19489
  `${record2.id}: amends target ${amendsId} not found in DB, setting to null`
@@ -19503,18 +19509,18 @@ async function syncAdrsToDb(projectRoot) {
19503
19509
  topics: fm.Topics ?? null,
19504
19510
  updatedAt: now2
19505
19511
  };
19506
- const existing = await db.select({ id: architectureDecisions.id }).from(architectureDecisions).where(eq22(architectureDecisions.id, record2.id)).all();
19512
+ const existing = await db.select({ id: architectureDecisions.id }).from(architectureDecisions).where(eq20(architectureDecisions.id, record2.id)).all();
19507
19513
  if (existing.length > 0) {
19508
- await db.update(architectureDecisions).set(rowBase).where(eq22(architectureDecisions.id, record2.id));
19514
+ await db.update(architectureDecisions).set(rowBase).where(eq20(architectureDecisions.id, record2.id));
19509
19515
  result.updated++;
19510
19516
  } else {
19511
19517
  await db.insert(architectureDecisions).values({ ...rowBase, createdAt: now2 });
19512
19518
  result.inserted++;
19513
19519
  }
19514
- await db.delete(adrTaskLinks).where(eq22(adrTaskLinks.adrId, record2.id));
19520
+ await db.delete(adrTaskLinks).where(eq20(adrTaskLinks.adrId, record2.id));
19515
19521
  if (fm["Related Tasks"]) {
19516
19522
  for (const taskId of parseTaskIds2(fm["Related Tasks"])) {
19517
- const taskExists2 = await db.select({ id: tasks.id }).from(tasks).where(eq22(tasks.id, taskId)).all();
19523
+ const taskExists2 = await db.select({ id: tasks.id }).from(tasks).where(eq20(tasks.id, taskId)).all();
19518
19524
  if (taskExists2.length === 0) {
19519
19525
  result.warnings.push(
19520
19526
  `${record2.id}: related task ${taskId} not found in DB, skipping link`
@@ -25196,19 +25202,19 @@ async function queryAudit(options) {
25196
25202
  try {
25197
25203
  const { getDb: getDb4 } = await Promise.resolve().then(() => (init_sqlite2(), sqlite_exports));
25198
25204
  const { auditLog: auditLog2 } = await Promise.resolve().then(() => (init_tasks_schema(), tasks_schema_exports));
25199
- const { and: and17, eq: eq22, gte: gte4, or: or8 } = await import("drizzle-orm");
25205
+ const { and: and16, eq: eq20, gte: gte4, or: or7 } = await import("drizzle-orm");
25200
25206
  const db = await getDb4(process.cwd());
25201
25207
  const conditions = [];
25202
- if (options?.sessionId) conditions.push(eq22(auditLog2.sessionId, options.sessionId));
25203
- if (options?.domain) conditions.push(eq22(auditLog2.domain, options.domain));
25208
+ if (options?.sessionId) conditions.push(eq20(auditLog2.sessionId, options.sessionId));
25209
+ if (options?.domain) conditions.push(eq20(auditLog2.domain, options.domain));
25204
25210
  if (options?.operation)
25205
25211
  conditions.push(
25206
- or8(eq22(auditLog2.operation, options.operation), eq22(auditLog2.action, options.operation))
25212
+ or7(eq20(auditLog2.operation, options.operation), eq20(auditLog2.action, options.operation))
25207
25213
  );
25208
- if (options?.taskId) conditions.push(eq22(auditLog2.taskId, options.taskId));
25214
+ if (options?.taskId) conditions.push(eq20(auditLog2.taskId, options.taskId));
25209
25215
  if (options?.since) conditions.push(gte4(auditLog2.timestamp, options.since));
25210
25216
  const limit = options?.limit ?? 1e3;
25211
- const rows = await db.select().from(auditLog2).where(conditions.length > 0 ? and17(...conditions) : void 0).orderBy(auditLog2.timestamp).limit(limit);
25217
+ const rows = await db.select().from(auditLog2).where(conditions.length > 0 ? and16(...conditions) : void 0).orderBy(auditLog2.timestamp).limit(limit);
25212
25218
  return rows.map((row) => ({
25213
25219
  timestamp: row.timestamp,
25214
25220
  sessionId: row.sessionId,
@@ -48510,7 +48516,7 @@ async function backfillRewardSignals(projectRoot, sessionId, lookbackDays = 30)
48510
48516
  const { getDb: getDb4 } = await Promise.resolve().then(() => (init_sqlite2(), sqlite_exports));
48511
48517
  const tasksDb = await getDb4(projectRoot);
48512
48518
  const { tasks: tasks2 } = await Promise.resolve().then(() => (init_tasks_schema(), tasks_schema_exports));
48513
- const { and: and17, eq: eq22, inArray: inArray10, gte: gte4, or: or8, isNotNull: isNotNull3 } = await import("drizzle-orm");
48519
+ const { and: and16, eq: eq20, inArray: inArray8, gte: gte4, or: or7, isNotNull: isNotNull3 } = await import("drizzle-orm");
48514
48520
  const cutoffTs = new Date(Date.now() - lookbackDays * 24 * 60 * 60 * 1e3).toISOString().replace("T", " ").slice(0, 19);
48515
48521
  const rawRows = await tasksDb.select({
48516
48522
  id: tasks2.id,
@@ -48519,12 +48525,12 @@ async function backfillRewardSignals(projectRoot, sessionId, lookbackDays = 30)
48519
48525
  completedAt: tasks2.completedAt,
48520
48526
  cancelledAt: tasks2.cancelledAt
48521
48527
  }).from(tasks2).where(
48522
- and17(
48523
- eq22(tasks2.sessionId, sessionId),
48524
- inArray10(tasks2.status, ["done", "cancelled"]),
48525
- or8(
48526
- and17(isNotNull3(tasks2.completedAt), gte4(tasks2.completedAt, cutoffTs)),
48527
- and17(isNotNull3(tasks2.cancelledAt), gte4(tasks2.cancelledAt, cutoffTs))
48528
+ and16(
48529
+ eq20(tasks2.sessionId, sessionId),
48530
+ inArray8(tasks2.status, ["done", "cancelled"]),
48531
+ or7(
48532
+ and16(isNotNull3(tasks2.completedAt), gte4(tasks2.completedAt, cutoffTs)),
48533
+ and16(isNotNull3(tasks2.cancelledAt), gte4(tasks2.cancelledAt, cutoffTs))
48528
48534
  )
48529
48535
  )
48530
48536
  ).all();
@@ -60037,13 +60043,13 @@ function extractYamlArray(content, field) {
60037
60043
  }
60038
60044
  const lines = content.split("\n");
60039
60045
  const items = [];
60040
- let inArray10 = false;
60046
+ let inArray8 = false;
60041
60047
  for (const line2 of lines) {
60042
60048
  if (line2.match(new RegExp(`^${field}:`))) {
60043
- inArray10 = true;
60049
+ inArray8 = true;
60044
60050
  continue;
60045
60051
  }
60046
- if (inArray10) {
60052
+ if (inArray8) {
60047
60053
  const itemMatch = line2.match(/^\s+-\s+["']?(.+?)["']?\s*$/);
60048
60054
  if (itemMatch) {
60049
60055
  items.push(itemMatch[1].trim());
@@ -62162,12 +62168,12 @@ async function getEnforcementMode(cwd) {
62162
62168
  }
62163
62169
  async function getLifecycleStatus(epicId, cwd) {
62164
62170
  const { getDb: getDb4 } = await Promise.resolve().then(() => (init_sqlite2(), sqlite_exports));
62165
- const { eq: eq22 } = await import("drizzle-orm");
62171
+ const { eq: eq20 } = await import("drizzle-orm");
62166
62172
  const db = await getDb4(cwd);
62167
62173
  const pipelineResult = await db.select({
62168
62174
  pipeline: lifecyclePipelines,
62169
62175
  task: tasks
62170
- }).from(lifecyclePipelines).innerJoin(tasks, eq22(lifecyclePipelines.taskId, tasks.id)).where(eq22(lifecyclePipelines.taskId, epicId)).limit(1);
62176
+ }).from(lifecyclePipelines).innerJoin(tasks, eq20(lifecyclePipelines.taskId, tasks.id)).where(eq20(lifecyclePipelines.taskId, epicId)).limit(1);
62171
62177
  if (pipelineResult.length === 0) {
62172
62178
  return {
62173
62179
  epicId,
@@ -62180,7 +62186,7 @@ async function getLifecycleStatus(epicId, cwd) {
62180
62186
  }
62181
62187
  const task = pipelineResult[0].task;
62182
62188
  const pipelineId = `pipeline-${epicId}`;
62183
- const stageRows = await db.select().from(lifecycleStages).where(eq22(lifecycleStages.pipelineId, pipelineId)).orderBy(lifecycleStages.sequence);
62189
+ const stageRows = await db.select().from(lifecycleStages).where(eq20(lifecycleStages.pipelineId, pipelineId)).orderBy(lifecycleStages.sequence);
62184
62190
  const stageDataMap = /* @__PURE__ */ new Map();
62185
62191
  for (const row of stageRows) {
62186
62192
  let parsedChain;
@@ -62249,10 +62255,10 @@ async function getLifecycleStatus(epicId, cwd) {
62249
62255
  }
62250
62256
  async function getLifecycleHistory(epicId, cwd) {
62251
62257
  const { getDb: getDb4 } = await Promise.resolve().then(() => (init_sqlite2(), sqlite_exports));
62252
- const { eq: eq22 } = await import("drizzle-orm");
62258
+ const { eq: eq20 } = await import("drizzle-orm");
62253
62259
  const db = await getDb4(cwd);
62254
62260
  const pipelineId = `pipeline-${epicId}`;
62255
- const stages = await db.select().from(lifecycleStages).where(eq22(lifecycleStages.pipelineId, pipelineId));
62261
+ const stages = await db.select().from(lifecycleStages).where(eq20(lifecycleStages.pipelineId, pipelineId));
62256
62262
  if (stages.length === 0) {
62257
62263
  return { epicId, history: [] };
62258
62264
  }
@@ -62282,7 +62288,7 @@ async function getLifecycleHistory(epicId, cwd) {
62282
62288
  }
62283
62289
  const stageIds = stages.map((s3) => s3.id);
62284
62290
  if (stageIds.length > 0) {
62285
- const gateResults = await db.select().from(lifecycleGateResults).where(eq22(lifecycleGateResults.stageId, stageIds[0]));
62291
+ const gateResults = await db.select().from(lifecycleGateResults).where(eq20(lifecycleGateResults.stageId, stageIds[0]));
62286
62292
  for (const gate of gateResults) {
62287
62293
  const stageName = stageIdToName.get(gate.stageId);
62288
62294
  if (stageName) {
@@ -62295,7 +62301,7 @@ async function getLifecycleHistory(epicId, cwd) {
62295
62301
  }
62296
62302
  }
62297
62303
  for (let i = 1; i < stageIds.length; i++) {
62298
- const additionalGates = await db.select().from(lifecycleGateResults).where(eq22(lifecycleGateResults.stageId, stageIds[i]));
62304
+ const additionalGates = await db.select().from(lifecycleGateResults).where(eq20(lifecycleGateResults.stageId, stageIds[i]));
62299
62305
  for (const gate of additionalGates) {
62300
62306
  const stageName = stageIdToName.get(gate.stageId);
62301
62307
  if (stageName) {
@@ -62314,16 +62320,16 @@ async function getLifecycleHistory(epicId, cwd) {
62314
62320
  }
62315
62321
  async function getLifecycleGates(epicId, cwd) {
62316
62322
  const { getDb: getDb4 } = await Promise.resolve().then(() => (init_sqlite2(), sqlite_exports));
62317
- const { eq: eq22 } = await import("drizzle-orm");
62323
+ const { eq: eq20 } = await import("drizzle-orm");
62318
62324
  const db = await getDb4(cwd);
62319
62325
  const pipelineId = `pipeline-${epicId}`;
62320
- const stages = await db.select().from(lifecycleStages).where(eq22(lifecycleStages.pipelineId, pipelineId));
62326
+ const stages = await db.select().from(lifecycleStages).where(eq20(lifecycleStages.pipelineId, pipelineId));
62321
62327
  if (stages.length === 0) {
62322
62328
  return {};
62323
62329
  }
62324
62330
  const gates = {};
62325
62331
  for (const stage of stages) {
62326
- const gateRows = await db.select().from(lifecycleGateResults).where(eq22(lifecycleGateResults.stageId, stage.id));
62332
+ const gateRows = await db.select().from(lifecycleGateResults).where(eq20(lifecycleGateResults.stageId, stage.id));
62327
62333
  if (gateRows.length > 0) {
62328
62334
  gates[stage.stageName] = {};
62329
62335
  for (const gateRow of gateRows) {
@@ -62387,7 +62393,7 @@ async function checkStagePrerequisites(epicId, targetStage, cwd) {
62387
62393
  }
62388
62394
  async function ensureLifecycleContext(epicId, stageName, cwd, options) {
62389
62395
  const { getDb: getDb4 } = await Promise.resolve().then(() => (init_sqlite2(), sqlite_exports));
62390
- const { eq: eq22 } = await import("drizzle-orm");
62396
+ const { eq: eq20 } = await import("drizzle-orm");
62391
62397
  const db = await getDb4(cwd);
62392
62398
  const pipelineId = `pipeline-${epicId}`;
62393
62399
  const stageId = `stage-${epicId}-${stageName}`;
@@ -62395,7 +62401,7 @@ async function ensureLifecycleContext(epicId, stageName, cwd, options) {
62395
62401
  getNativeDb3().prepare(
62396
62402
  `INSERT OR IGNORE INTO tasks (id, title, status, priority, created_at) VALUES (?, ?, 'pending', 'medium', datetime('now'))`
62397
62403
  ).run(epicId, `Task ${epicId}`);
62398
- const existingPipeline = await db.select().from(lifecyclePipelines).where(eq22(lifecyclePipelines.id, pipelineId)).limit(1).all();
62404
+ const existingPipeline = await db.select().from(lifecyclePipelines).where(eq20(lifecyclePipelines.id, pipelineId)).limit(1).all();
62399
62405
  if (existingPipeline.length === 0) {
62400
62406
  await db.insert(lifecyclePipelines).values({
62401
62407
  id: pipelineId,
@@ -62405,7 +62411,7 @@ async function ensureLifecycleContext(epicId, stageName, cwd, options) {
62405
62411
  startedAt: options.now
62406
62412
  }).run();
62407
62413
  }
62408
- const existingStage = await db.select().from(lifecycleStages).where(eq22(lifecycleStages.id, stageId)).limit(1).all();
62414
+ const existingStage = await db.select().from(lifecycleStages).where(eq20(lifecycleStages.id, stageId)).limit(1).all();
62409
62415
  if (existingStage.length === 0) {
62410
62416
  const sequence = isValidStage(stageName) ? STAGE_ORDER[stageName] : 0;
62411
62417
  await db.insert(lifecycleStages).values({
@@ -62418,7 +62424,7 @@ async function ensureLifecycleContext(epicId, stageName, cwd, options) {
62418
62424
  }).run();
62419
62425
  }
62420
62426
  if (options.updateCurrentStage) {
62421
- await db.update(lifecyclePipelines).set({ currentStageId: stageId }).where(eq22(lifecyclePipelines.id, pipelineId)).run();
62427
+ await db.update(lifecyclePipelines).set({ currentStageId: stageId }).where(eq20(lifecyclePipelines.id, pipelineId)).run();
62422
62428
  }
62423
62429
  return { db, pipelineId, stageId };
62424
62430
  }
@@ -62433,7 +62439,7 @@ async function recordStageProgress(epicId, stage, status, notes, cwd) {
62433
62439
  `Invalid status: ${status}. Valid: ${validStatuses.join(", ")}`
62434
62440
  );
62435
62441
  }
62436
- const { eq: eq22 } = await import("drizzle-orm");
62442
+ const { eq: eq20 } = await import("drizzle-orm");
62437
62443
  const now2 = (/* @__PURE__ */ new Date()).toISOString();
62438
62444
  const stageName = stage;
62439
62445
  const { db, stageId, pipelineId } = await ensureLifecycleContext(epicId, stage, cwd, {
@@ -62449,7 +62455,7 @@ async function recordStageProgress(epicId, stage, status, notes, cwd) {
62449
62455
  status,
62450
62456
  related: artifact.related
62451
62457
  };
62452
- const existingStage = await db.select().from(lifecycleStages).where(eq22(lifecycleStages.id, stageId)).limit(1).all();
62458
+ const existingStage = await db.select().from(lifecycleStages).where(eq20(lifecycleStages.id, stageId)).limit(1).all();
62453
62459
  const sequence = STAGE_ORDER[stage];
62454
62460
  const stageValues = {
62455
62461
  status,
@@ -62476,7 +62482,7 @@ async function recordStageProgress(epicId, stage, status, notes, cwd) {
62476
62482
  provenanceChainJson: JSON.stringify(provenanceChain)
62477
62483
  }).run();
62478
62484
  } else {
62479
- await db.update(lifecycleStages).set(stageValues).where(eq22(lifecycleStages.id, stageId)).run();
62485
+ await db.update(lifecycleStages).set(stageValues).where(eq20(lifecycleStages.id, stageId)).run();
62480
62486
  }
62481
62487
  if (status === "completed") {
62482
62488
  await linkProvenance(epicId, stageName, artifact.absolutePath, cwd);
@@ -62487,7 +62493,7 @@ async function recordStageProgress(epicId, stage, status, notes, cwd) {
62487
62493
  }
62488
62494
  }
62489
62495
  if (status === "in_progress" || status === "completed") {
62490
- await db.update(tasks).set({ pipelineStage: stage }).where(eq22(tasks.id, epicId)).run();
62496
+ await db.update(tasks).set({ pipelineStage: stage }).where(eq20(tasks.id, epicId)).run();
62491
62497
  }
62492
62498
  return { epicId, stage, status, timestamp: now2 };
62493
62499
  }
@@ -62499,7 +62505,7 @@ async function resetStage(epicId, stage, reason, cwd) {
62499
62505
  if (!PIPELINE_STAGES.includes(stage)) {
62500
62506
  throw new CleoError(2 /* INVALID_INPUT */, `Invalid stage: ${stage}`);
62501
62507
  }
62502
- const { eq: eq22 } = await import("drizzle-orm");
62508
+ const { eq: eq20 } = await import("drizzle-orm");
62503
62509
  const now2 = (/* @__PURE__ */ new Date()).toISOString();
62504
62510
  const { db, stageId } = await ensureLifecycleContext(epicId, stage, cwd, {
62505
62511
  now: now2,
@@ -62512,11 +62518,11 @@ async function resetStage(epicId, stage, reason, cwd) {
62512
62518
  skippedAt: null,
62513
62519
  skipReason: null,
62514
62520
  notesJson: JSON.stringify([`Reset: ${reason}`])
62515
- }).where(eq22(lifecycleStages.id, stageId)).run();
62521
+ }).where(eq20(lifecycleStages.id, stageId)).run();
62516
62522
  return { epicId, stage, reason };
62517
62523
  }
62518
62524
  async function passGate(epicId, gateName, agent, notes, cwd) {
62519
- const { eq: eq22 } = await import("drizzle-orm");
62525
+ const { eq: eq20 } = await import("drizzle-orm");
62520
62526
  const now2 = (/* @__PURE__ */ new Date()).toISOString();
62521
62527
  const stageName = gateName.split("-")[0];
62522
62528
  const gateId = `gate-${epicId}-${stageName}-${gateName}`;
@@ -62525,7 +62531,7 @@ async function passGate(epicId, gateName, agent, notes, cwd) {
62525
62531
  stageStatusOnCreate: "in_progress",
62526
62532
  updateCurrentStage: true
62527
62533
  });
62528
- const existingGate = await db.select().from(lifecycleGateResults).where(eq22(lifecycleGateResults.id, gateId)).limit(1).all();
62534
+ const existingGate = await db.select().from(lifecycleGateResults).where(eq20(lifecycleGateResults.id, gateId)).limit(1).all();
62529
62535
  const gateValues = {
62530
62536
  id: gateId,
62531
62537
  stageId,
@@ -62537,14 +62543,14 @@ async function passGate(epicId, gateName, agent, notes, cwd) {
62537
62543
  reason: null
62538
62544
  };
62539
62545
  if (existingGate.length > 0) {
62540
- await db.update(lifecycleGateResults).set(gateValues).where(eq22(lifecycleGateResults.id, gateId)).run();
62546
+ await db.update(lifecycleGateResults).set(gateValues).where(eq20(lifecycleGateResults.id, gateId)).run();
62541
62547
  } else {
62542
62548
  await db.insert(lifecycleGateResults).values(gateValues).run();
62543
62549
  }
62544
62550
  return { epicId, gateName, timestamp: now2 };
62545
62551
  }
62546
62552
  async function failGate(epicId, gateName, reason, cwd) {
62547
- const { eq: eq22 } = await import("drizzle-orm");
62553
+ const { eq: eq20 } = await import("drizzle-orm");
62548
62554
  const now2 = (/* @__PURE__ */ new Date()).toISOString();
62549
62555
  const stageName = gateName.split("-")[0];
62550
62556
  const gateId = `gate-${epicId}-${stageName}-${gateName}`;
@@ -62553,7 +62559,7 @@ async function failGate(epicId, gateName, reason, cwd) {
62553
62559
  stageStatusOnCreate: "in_progress",
62554
62560
  updateCurrentStage: true
62555
62561
  });
62556
- const existingGate = await db.select().from(lifecycleGateResults).where(eq22(lifecycleGateResults.id, gateId)).limit(1).all();
62562
+ const existingGate = await db.select().from(lifecycleGateResults).where(eq20(lifecycleGateResults.id, gateId)).limit(1).all();
62557
62563
  const gateValues = {
62558
62564
  id: gateId,
62559
62565
  stageId,
@@ -62565,7 +62571,7 @@ async function failGate(epicId, gateName, reason, cwd) {
62565
62571
  reason: reason ?? null
62566
62572
  };
62567
62573
  if (existingGate.length > 0) {
62568
- await db.update(lifecycleGateResults).set(gateValues).where(eq22(lifecycleGateResults.id, gateId)).run();
62574
+ await db.update(lifecycleGateResults).set(gateValues).where(eq20(lifecycleGateResults.id, gateId)).run();
62569
62575
  } else {
62570
62576
  await db.insert(lifecycleGateResults).values(gateValues).run();
62571
62577
  }
@@ -67459,9 +67465,9 @@ async function nexusRegister(projectPath, name2, permissions = "read") {
67459
67465
  const projectHash = generateProjectHash(projectPath);
67460
67466
  await nexusInit();
67461
67467
  const { getNexusDb: getNexusDb2 } = await Promise.resolve().then(() => (init_nexus_sqlite(), nexus_sqlite_exports));
67462
- const { eq: eq22 } = await import("drizzle-orm");
67468
+ const { eq: eq20 } = await import("drizzle-orm");
67463
67469
  const db = await getNexusDb2();
67464
- const existingRows = await db.select().from(projectRegistry).where(eq22(projectRegistry.projectHash, projectHash));
67470
+ const existingRows = await db.select().from(projectRegistry).where(eq20(projectRegistry.projectHash, projectHash));
67465
67471
  const existing = existingRows[0];
67466
67472
  if (existing?.permissions) {
67467
67473
  throw new CleoError(
@@ -67470,7 +67476,7 @@ async function nexusRegister(projectPath, name2, permissions = "read") {
67470
67476
  );
67471
67477
  }
67472
67478
  if (!existing) {
67473
- const nameConflictRows = await db.select().from(projectRegistry).where(eq22(projectRegistry.name, projectName));
67479
+ const nameConflictRows = await db.select().from(projectRegistry).where(eq20(projectRegistry.name, projectName));
67474
67480
  if (nameConflictRows.length > 0) {
67475
67481
  throw new CleoError(
67476
67482
  6 /* VALIDATION_ERROR */,
@@ -67493,7 +67499,7 @@ async function nexusRegister(projectPath, name2, permissions = "read") {
67493
67499
  lastSeen: now2,
67494
67500
  brainDbPath,
67495
67501
  tasksDbPath
67496
- }).where(eq22(projectRegistry.projectHash, projectHash));
67502
+ }).where(eq20(projectRegistry.projectHash, projectHash));
67497
67503
  } else {
67498
67504
  if (!projectId) {
67499
67505
  projectId = randomUUID4();
@@ -67534,9 +67540,9 @@ async function nexusUnregister(nameOrHash) {
67534
67540
  throw new CleoError(4 /* NOT_FOUND */, `Project not found in registry: ${nameOrHash}`);
67535
67541
  }
67536
67542
  const { getNexusDb: getNexusDb2 } = await Promise.resolve().then(() => (init_nexus_sqlite(), nexus_sqlite_exports));
67537
- const { eq: eq22 } = await import("drizzle-orm");
67543
+ const { eq: eq20 } = await import("drizzle-orm");
67538
67544
  const db = await getNexusDb2();
67539
- await db.delete(projectRegistry).where(eq22(projectRegistry.projectHash, project.hash));
67545
+ await db.delete(projectRegistry).where(eq20(projectRegistry.projectHash, project.hash));
67540
67546
  await writeNexusAudit({
67541
67547
  action: "unregister",
67542
67548
  projectHash: project.hash,
@@ -67558,9 +67564,9 @@ async function nexusList() {
67558
67564
  async function nexusGetProject(nameOrHash) {
67559
67565
  try {
67560
67566
  const { getNexusDb: getNexusDb2 } = await Promise.resolve().then(() => (init_nexus_sqlite(), nexus_sqlite_exports));
67561
- const { eq: eq22, or: or8 } = await import("drizzle-orm");
67567
+ const { eq: eq20, or: or7 } = await import("drizzle-orm");
67562
67568
  const db = await getNexusDb2();
67563
- const rows = await db.select().from(projectRegistry).where(or8(eq22(projectRegistry.projectHash, nameOrHash), eq22(projectRegistry.name, nameOrHash)));
67569
+ const rows = await db.select().from(projectRegistry).where(or7(eq20(projectRegistry.projectHash, nameOrHash), eq20(projectRegistry.name, nameOrHash)));
67564
67570
  const row = rows[0];
67565
67571
  if (!row) return null;
67566
67572
  return rowToProject(row);
@@ -67583,14 +67589,14 @@ async function nexusSync(nameOrHash) {
67583
67589
  const meta3 = await readProjectMeta(project.path);
67584
67590
  const now2 = (/* @__PURE__ */ new Date()).toISOString();
67585
67591
  const { getNexusDb: getNexusDb2 } = await Promise.resolve().then(() => (init_nexus_sqlite(), nexus_sqlite_exports));
67586
- const { eq: eq22 } = await import("drizzle-orm");
67592
+ const { eq: eq20 } = await import("drizzle-orm");
67587
67593
  const db = await getNexusDb2();
67588
67594
  await db.update(projectRegistry).set({
67589
67595
  taskCount: meta3.taskCount,
67590
67596
  labelsJson: JSON.stringify(meta3.labels),
67591
67597
  lastSync: now2,
67592
67598
  lastSeen: now2
67593
- }).where(eq22(projectRegistry.projectHash, project.hash));
67599
+ }).where(eq20(projectRegistry.projectHash, project.hash));
67594
67600
  await writeNexusAudit({
67595
67601
  action: "sync",
67596
67602
  projectHash: project.hash,
@@ -67604,7 +67610,7 @@ async function nexusSyncAll() {
67604
67610
  let synced = 0;
67605
67611
  let failed = 0;
67606
67612
  const { getNexusDb: getNexusDb2 } = await Promise.resolve().then(() => (init_nexus_sqlite(), nexus_sqlite_exports));
67607
- const { eq: eq22 } = await import("drizzle-orm");
67613
+ const { eq: eq20 } = await import("drizzle-orm");
67608
67614
  const db = await getNexusDb2();
67609
67615
  for (const project of projects) {
67610
67616
  try {
@@ -67615,7 +67621,7 @@ async function nexusSyncAll() {
67615
67621
  labelsJson: JSON.stringify(meta3.labels),
67616
67622
  lastSync: now2,
67617
67623
  lastSeen: now2
67618
- }).where(eq22(projectRegistry.projectHash, project.hash));
67624
+ }).where(eq20(projectRegistry.projectHash, project.hash));
67619
67625
  synced++;
67620
67626
  } catch {
67621
67627
  failed++;
@@ -67635,9 +67641,9 @@ async function nexusUpdateIndexStats(projectPath, stats2) {
67635
67641
  const now2 = (/* @__PURE__ */ new Date()).toISOString();
67636
67642
  try {
67637
67643
  const { getNexusDb: getNexusDb2 } = await Promise.resolve().then(() => (init_nexus_sqlite(), nexus_sqlite_exports));
67638
- const { eq: eq22 } = await import("drizzle-orm");
67644
+ const { eq: eq20 } = await import("drizzle-orm");
67639
67645
  const db = await getNexusDb2();
67640
- const rows = await db.select().from(projectRegistry).where(eq22(projectRegistry.projectHash, projectHash));
67646
+ const rows = await db.select().from(projectRegistry).where(eq20(projectRegistry.projectHash, projectHash));
67641
67647
  if (rows.length === 0) {
67642
67648
  try {
67643
67649
  await nexusRegister(projectPath);
@@ -67648,7 +67654,7 @@ async function nexusUpdateIndexStats(projectPath, stats2) {
67648
67654
  lastIndexed: now2,
67649
67655
  statsJson: JSON.stringify(stats2),
67650
67656
  lastSeen: now2
67651
- }).where(eq22(projectRegistry.projectHash, projectHash));
67657
+ }).where(eq20(projectRegistry.projectHash, projectHash));
67652
67658
  await writeNexusAudit({
67653
67659
  action: "update-index-stats",
67654
67660
  projectHash,
@@ -67670,9 +67676,9 @@ async function nexusSetPermission(nameOrHash, permission) {
67670
67676
  throw new CleoError(4 /* NOT_FOUND */, `Project not found in registry: ${nameOrHash}`);
67671
67677
  }
67672
67678
  const { getNexusDb: getNexusDb2 } = await Promise.resolve().then(() => (init_nexus_sqlite(), nexus_sqlite_exports));
67673
- const { eq: eq22 } = await import("drizzle-orm");
67679
+ const { eq: eq20 } = await import("drizzle-orm");
67674
67680
  const db = await getNexusDb2();
67675
- await db.update(projectRegistry).set({ permissions: permission }).where(eq22(projectRegistry.projectHash, project.hash));
67681
+ await db.update(projectRegistry).set({ permissions: permission }).where(eq20(projectRegistry.projectHash, project.hash));
67676
67682
  await writeNexusAudit({
67677
67683
  action: "set-permission",
67678
67684
  projectHash: project.hash,
@@ -67688,12 +67694,12 @@ async function nexusReconcile(projectRoot) {
67688
67694
  }
67689
67695
  await nexusInit();
67690
67696
  const { getNexusDb: getNexusDb2 } = await Promise.resolve().then(() => (init_nexus_sqlite(), nexus_sqlite_exports));
67691
- const { eq: eq22 } = await import("drizzle-orm");
67697
+ const { eq: eq20 } = await import("drizzle-orm");
67692
67698
  const db = await getNexusDb2();
67693
67699
  const projectId = await readProjectId(projectRoot);
67694
67700
  const currentHash = generateProjectHash(projectRoot);
67695
67701
  if (projectId) {
67696
- const hashRows2 = await db.select().from(projectRegistry).where(eq22(projectRegistry.projectHash, currentHash));
67702
+ const hashRows2 = await db.select().from(projectRegistry).where(eq20(projectRegistry.projectHash, currentHash));
67697
67703
  const hashMatch2 = hashRows2[0];
67698
67704
  if (hashMatch2 && hashMatch2.projectId !== projectId) {
67699
67705
  await writeNexusAudit({
@@ -67712,12 +67718,12 @@ async function nexusReconcile(projectRoot) {
67712
67718
  }
67713
67719
  }
67714
67720
  if (projectId) {
67715
- const idRows = await db.select().from(projectRegistry).where(eq22(projectRegistry.projectId, projectId));
67721
+ const idRows = await db.select().from(projectRegistry).where(eq20(projectRegistry.projectId, projectId));
67716
67722
  const existing = idRows[0];
67717
67723
  if (existing) {
67718
67724
  const now2 = (/* @__PURE__ */ new Date()).toISOString();
67719
67725
  if (existing.projectPath === projectRoot) {
67720
- await db.update(projectRegistry).set({ lastSeen: now2 }).where(eq22(projectRegistry.projectId, projectId));
67726
+ await db.update(projectRegistry).set({ lastSeen: now2 }).where(eq20(projectRegistry.projectId, projectId));
67721
67727
  await writeNexusAudit({
67722
67728
  action: "reconcile",
67723
67729
  projectHash: currentHash,
@@ -67733,7 +67739,7 @@ async function nexusReconcile(projectRoot) {
67733
67739
  projectPath: projectRoot,
67734
67740
  projectHash: currentHash,
67735
67741
  lastSeen: now2
67736
- }).where(eq22(projectRegistry.projectId, projectId));
67742
+ }).where(eq20(projectRegistry.projectId, projectId));
67737
67743
  await writeNexusAudit({
67738
67744
  action: "reconcile",
67739
67745
  projectHash: currentHash,
@@ -67745,11 +67751,11 @@ async function nexusReconcile(projectRoot) {
67745
67751
  return { status: "path_updated", oldPath, newPath: projectRoot };
67746
67752
  }
67747
67753
  }
67748
- const hashRows = await db.select().from(projectRegistry).where(eq22(projectRegistry.projectHash, currentHash));
67754
+ const hashRows = await db.select().from(projectRegistry).where(eq20(projectRegistry.projectHash, currentHash));
67749
67755
  const hashMatch = hashRows[0];
67750
67756
  if (hashMatch) {
67751
67757
  const now2 = (/* @__PURE__ */ new Date()).toISOString();
67752
- await db.update(projectRegistry).set({ lastSeen: now2 }).where(eq22(projectRegistry.projectHash, currentHash));
67758
+ await db.update(projectRegistry).set({ lastSeen: now2 }).where(eq20(projectRegistry.projectHash, currentHash));
67753
67759
  await writeNexusAudit({
67754
67760
  action: "reconcile",
67755
67761
  projectHash: currentHash,
@@ -79345,7 +79351,7 @@ async function queryTasks(cwd, since) {
79345
79351
  try {
79346
79352
  const { getDb: getDb4 } = await Promise.resolve().then(() => (init_sqlite2(), sqlite_exports));
79347
79353
  const { tasks: tasks2 } = await Promise.resolve().then(() => (init_tasks_schema(), tasks_schema_exports));
79348
- const { and: and17, gte: gte4 } = await import("drizzle-orm");
79354
+ const { and: and16, gte: gte4 } = await import("drizzle-orm");
79349
79355
  const db = await getDb4(cwd);
79350
79356
  const conditions = [];
79351
79357
  if (since) {
@@ -79359,7 +79365,7 @@ async function queryTasks(cwd, since) {
79359
79365
  sessionId: tasks2.sessionId,
79360
79366
  completedAt: tasks2.completedAt,
79361
79367
  createdAt: tasks2.createdAt
79362
- }).from(tasks2).where(conditions.length > 0 ? and17(...conditions) : void 0).all();
79368
+ }).from(tasks2).where(conditions.length > 0 ? and16(...conditions) : void 0).all();
79363
79369
  return rows;
79364
79370
  } catch (err2) {
79365
79371
  log9.warn({ err: err2 }, "Failed to query tasks for workflow telemetry");
@@ -79370,7 +79376,7 @@ async function queryCompletionAuditRows(cwd, since) {
79370
79376
  try {
79371
79377
  const { getDb: getDb4 } = await Promise.resolve().then(() => (init_sqlite2(), sqlite_exports));
79372
79378
  const { auditLog: auditLog2 } = await Promise.resolve().then(() => (init_tasks_schema(), tasks_schema_exports));
79373
- const { and: and17, gte: gte4 } = await import("drizzle-orm");
79379
+ const { and: and16, gte: gte4 } = await import("drizzle-orm");
79374
79380
  const db = await getDb4(cwd);
79375
79381
  const conditions = [];
79376
79382
  if (since) conditions.push(gte4(auditLog2.timestamp, since));
@@ -79382,7 +79388,7 @@ async function queryCompletionAuditRows(cwd, since) {
79382
79388
  afterJson: auditLog2.afterJson,
79383
79389
  operation: auditLog2.operation,
79384
79390
  domain: auditLog2.domain
79385
- }).from(auditLog2).where(conditions.length > 0 ? and17(...conditions) : void 0).orderBy(auditLog2.timestamp).all();
79391
+ }).from(auditLog2).where(conditions.length > 0 ? and16(...conditions) : void 0).orderBy(auditLog2.timestamp).all();
79386
79392
  return allRows.filter((row) => {
79387
79393
  const isComplete = row.action === "task_completed" || row.action === "complete" || row.operation === "complete" && row.domain === "tasks";
79388
79394
  if (!isComplete && row.afterJson) {
@@ -106964,213 +106970,6 @@ var init_types4 = __esm({
106964
106970
  }
106965
106971
  });
106966
106972
 
106967
- // packages/core/src/lifecycle/backfill-pipeline-stage.ts
106968
- import { eq as eq15, inArray as inArray6 } from "drizzle-orm";
106969
- async function backfillPipelineStageFromLifecycle(options = {}, cwd) {
106970
- const { dryRun = false, force = false } = options;
106971
- const db = await getDb(cwd);
106972
- if (!force) {
106973
- const guard = await db.select().from(schemaMeta).where(eq15(schemaMeta.key, BACKFILL_KEY)).limit(1).all();
106974
- if (guard.length > 0) {
106975
- return {
106976
- alreadyRun: true,
106977
- dryRun,
106978
- tasksScanned: 0,
106979
- tasksUpdated: 0,
106980
- changes: []
106981
- };
106982
- }
106983
- }
106984
- const advancingStatuses = [
106985
- "completed",
106986
- "in_progress",
106987
- "skipped"
106988
- ];
106989
- const rows = await db.select({
106990
- taskId: lifecyclePipelines.taskId,
106991
- stageName: lifecycleStages.stageName,
106992
- sequence: lifecycleStages.sequence,
106993
- status: lifecycleStages.status,
106994
- currentPipelineStage: tasks.pipelineStage
106995
- }).from(lifecyclePipelines).innerJoin(
106996
- lifecycleStages,
106997
- eq15(lifecycleStages.pipelineId, lifecyclePipelines.id)
106998
- ).innerJoin(tasks, eq15(tasks.id, lifecyclePipelines.taskId)).where(inArray6(lifecycleStages.status, advancingStatuses)).all();
106999
- const highestPerTask = /* @__PURE__ */ new Map();
107000
- for (const row of rows) {
107001
- const existing = highestPerTask.get(row.taskId);
107002
- if (!existing || row.sequence > existing.sequence) {
107003
- highestPerTask.set(row.taskId, {
107004
- stageName: row.stageName,
107005
- sequence: row.sequence,
107006
- currentPipelineStage: row.currentPipelineStage ?? null
107007
- });
107008
- }
107009
- }
107010
- const changes = [];
107011
- for (const [taskId, { stageName, sequence, currentPipelineStage }] of highestPerTask) {
107012
- const currentOrder = currentPipelineStage ? STAGE_ORDER3[currentPipelineStage] ?? 0 : 0;
107013
- if (sequence > currentOrder) {
107014
- changes.push({
107015
- taskId,
107016
- previousStage: currentPipelineStage,
107017
- newStage: stageName
107018
- });
107019
- }
107020
- }
107021
- const tasksScanned = highestPerTask.size;
107022
- if (!dryRun && changes.length > 0) {
107023
- const now2 = (/* @__PURE__ */ new Date()).toISOString();
107024
- for (const change of changes) {
107025
- await db.update(tasks).set({
107026
- pipelineStage: change.newStage,
107027
- updatedAt: now2
107028
- }).where(eq15(tasks.id, change.taskId)).run();
107029
- }
107030
- }
107031
- if (!dryRun) {
107032
- const guardValue = JSON.stringify({
107033
- ranAt: (/* @__PURE__ */ new Date()).toISOString(),
107034
- tasksUpdated: changes.length,
107035
- task: "T869"
107036
- });
107037
- await db.insert(schemaMeta).values({ key: BACKFILL_KEY, value: guardValue }).onConflictDoUpdate({ target: schemaMeta.key, set: { value: guardValue } }).run();
107038
- }
107039
- return {
107040
- alreadyRun: false,
107041
- dryRun,
107042
- tasksScanned,
107043
- tasksUpdated: changes.length,
107044
- changes
107045
- };
107046
- }
107047
- async function isPipelineStageBackfillDone(cwd) {
107048
- const db = await getDb(cwd);
107049
- const guard = await db.select().from(schemaMeta).where(eq15(schemaMeta.key, BACKFILL_KEY)).limit(1).all();
107050
- return guard.length > 0;
107051
- }
107052
- var BACKFILL_KEY, STAGE_ORDER3;
107053
- var init_backfill_pipeline_stage = __esm({
107054
- "packages/core/src/lifecycle/backfill-pipeline-stage.ts"() {
107055
- "use strict";
107056
- init_sqlite2();
107057
- init_tasks_schema();
107058
- BACKFILL_KEY = "backfill:pipeline-stage-from-lifecycle";
107059
- STAGE_ORDER3 = {
107060
- research: 1,
107061
- consensus: 2,
107062
- architecture_decision: 3,
107063
- specification: 4,
107064
- decomposition: 5,
107065
- implementation: 6,
107066
- validation: 7,
107067
- testing: 8,
107068
- release: 9,
107069
- contribution: 10
107070
- };
107071
- }
107072
- });
107073
-
107074
- // packages/core/src/lifecycle/backfill-terminal-pipeline-stage.ts
107075
- import { and as and13, eq as eq16, inArray as inArray7, isNull as isNull3, or as or5 } from "drizzle-orm";
107076
- async function backfillTerminalPipelineStage(options = {}, cwd) {
107077
- const { dryRun = false, force = false } = options;
107078
- const db = await getDb(cwd);
107079
- if (!force) {
107080
- const guard = await db.select().from(schemaMeta).where(eq16(schemaMeta.key, TERMINAL_BACKFILL_KEY)).limit(1).all();
107081
- if (guard.length > 0) {
107082
- return {
107083
- alreadyRun: true,
107084
- dryRun,
107085
- tasksScanned: 0,
107086
- tasksUpdated: 0,
107087
- changes: []
107088
- };
107089
- }
107090
- }
107091
- const rows = await db.select({
107092
- id: tasks.id,
107093
- status: tasks.status,
107094
- pipelineStage: tasks.pipelineStage
107095
- }).from(tasks).where(inArray7(tasks.status, ["done", "cancelled"])).all();
107096
- const tasksScanned = rows.length;
107097
- const changes = [];
107098
- for (const row of rows) {
107099
- if (row.pipelineStage && TERMINAL_STAGES.includes(row.pipelineStage)) {
107100
- continue;
107101
- }
107102
- const status = row.status;
107103
- const newStage = status === "done" ? "contribution" : "cancelled";
107104
- changes.push({
107105
- taskId: row.id,
107106
- status,
107107
- previousStage: row.pipelineStage ?? null,
107108
- newStage
107109
- });
107110
- }
107111
- if (!dryRun && changes.length > 0) {
107112
- const now2 = (/* @__PURE__ */ new Date()).toISOString();
107113
- for (const change of changes) {
107114
- await db.update(tasks).set({
107115
- pipelineStage: change.newStage,
107116
- updatedAt: now2
107117
- }).where(
107118
- and13(
107119
- eq16(tasks.id, change.taskId),
107120
- or5(
107121
- isNull3(tasks.pipelineStage),
107122
- inArray7(tasks.pipelineStage, [
107123
- "research",
107124
- "consensus",
107125
- "architecture_decision",
107126
- "specification",
107127
- "decomposition",
107128
- "implementation",
107129
- "validation",
107130
- "testing",
107131
- "release"
107132
- ])
107133
- )
107134
- )
107135
- ).run();
107136
- }
107137
- }
107138
- if (!dryRun) {
107139
- const guardValue = JSON.stringify({
107140
- ranAt: (/* @__PURE__ */ new Date()).toISOString(),
107141
- tasksUpdated: changes.length,
107142
- task: "T871"
107143
- });
107144
- await db.insert(schemaMeta).values({ key: TERMINAL_BACKFILL_KEY, value: guardValue }).onConflictDoUpdate({
107145
- target: schemaMeta.key,
107146
- set: { value: guardValue }
107147
- }).run();
107148
- }
107149
- return {
107150
- alreadyRun: false,
107151
- dryRun,
107152
- tasksScanned,
107153
- tasksUpdated: changes.length,
107154
- changes
107155
- };
107156
- }
107157
- async function isTerminalPipelineStageBackfillDone(cwd) {
107158
- const db = await getDb(cwd);
107159
- const guard = await db.select().from(schemaMeta).where(eq16(schemaMeta.key, TERMINAL_BACKFILL_KEY)).limit(1).all();
107160
- return guard.length > 0;
107161
- }
107162
- var TERMINAL_BACKFILL_KEY, TERMINAL_STAGES;
107163
- var init_backfill_terminal_pipeline_stage = __esm({
107164
- "packages/core/src/lifecycle/backfill-terminal-pipeline-stage.ts"() {
107165
- "use strict";
107166
- init_sqlite2();
107167
- init_tasks_schema();
107168
- init_pipeline_stage();
107169
- TERMINAL_BACKFILL_KEY = "backfill:terminal-pipeline-stage";
107170
- TERMINAL_STAGES = Array.from(TERMINAL_PIPELINE_STAGES);
107171
- }
107172
- });
107173
-
107174
106973
  // packages/core/src/validation/chain-validation.ts
107175
106974
  function validateChainShape(shape) {
107176
106975
  const errors = [];
@@ -107308,9 +107107,9 @@ async function addChain(chain, projectRoot) {
107308
107107
  }
107309
107108
  async function showChain(id2, projectRoot) {
107310
107109
  const { getDb: getDb4 } = await Promise.resolve().then(() => (init_sqlite2(), sqlite_exports));
107311
- const { eq: eq22 } = await import("drizzle-orm");
107110
+ const { eq: eq20 } = await import("drizzle-orm");
107312
107111
  const db = await getDb4(projectRoot);
107313
- const rows = await db.select().from(warpChains).where(eq22(warpChains.id, id2));
107112
+ const rows = await db.select().from(warpChains).where(eq20(warpChains.id, id2));
107314
107113
  if (rows.length === 0) return null;
107315
107114
  return JSON.parse(rows[0].definition);
107316
107115
  }
@@ -107357,9 +107156,9 @@ async function createInstance(params2, projectRoot) {
107357
107156
  }
107358
107157
  async function showInstance(id2, projectRoot) {
107359
107158
  const { getDb: getDb4 } = await Promise.resolve().then(() => (init_sqlite2(), sqlite_exports));
107360
- const { eq: eq22 } = await import("drizzle-orm");
107159
+ const { eq: eq20 } = await import("drizzle-orm");
107361
107160
  const db = await getDb4(projectRoot);
107362
- const rows = await db.select().from(warpChainInstances).where(eq22(warpChainInstances.id, id2));
107161
+ const rows = await db.select().from(warpChainInstances).where(eq20(warpChainInstances.id, id2));
107363
107162
  if (rows.length === 0) return null;
107364
107163
  const row = rows[0];
107365
107164
  return {
@@ -107405,11 +107204,11 @@ async function advanceInstance(id2, nextStage, gateResults, projectRoot) {
107405
107204
  }
107406
107205
  }
107407
107206
  const { getDb: getDb4 } = await Promise.resolve().then(() => (init_sqlite2(), sqlite_exports));
107408
- const { eq: eq22 } = await import("drizzle-orm");
107207
+ const { eq: eq20 } = await import("drizzle-orm");
107409
107208
  const db = await getDb4(projectRoot);
107410
107209
  const now2 = (/* @__PURE__ */ new Date()).toISOString();
107411
107210
  const existingResults = [];
107412
- const row = (await db.select().from(warpChainInstances).where(eq22(warpChainInstances.id, id2)))[0];
107211
+ const row = (await db.select().from(warpChainInstances).where(eq20(warpChainInstances.id, id2)))[0];
107413
107212
  if (row?.gateResults) {
107414
107213
  existingResults.push(...JSON.parse(row.gateResults));
107415
107214
  }
@@ -107419,7 +107218,7 @@ async function advanceInstance(id2, nextStage, gateResults, projectRoot) {
107419
107218
  gateResults: JSON.stringify(allResults),
107420
107219
  status: "active",
107421
107220
  updatedAt: now2
107422
- }).where(eq22(warpChainInstances.id, id2));
107221
+ }).where(eq20(warpChainInstances.id, id2));
107423
107222
  return {
107424
107223
  ...instance,
107425
107224
  currentStage: nextStage,
@@ -107944,7 +107743,7 @@ var init_gate_runner = __esm({
107944
107743
 
107945
107744
  // packages/core/src/lifecycle/ivtr-loop.ts
107946
107745
  import { createHash as createHash20 } from "node:crypto";
107947
- import { eq as eq17 } from "drizzle-orm";
107746
+ import { eq as eq15 } from "drizzle-orm";
107948
107747
  function nextPhase(current) {
107949
107748
  const idx = PHASE_ORDER.indexOf(current);
107950
107749
  if (idx === -1 || idx >= PHASE_ORDER.length - 1) return null;
@@ -107952,7 +107751,7 @@ function nextPhase(current) {
107952
107751
  }
107953
107752
  async function readIvtrStateRaw(taskId, cwd) {
107954
107753
  const db = await getDb(cwd);
107955
- const rows = await db.select({ ivtrState: tasks.ivtrState }).from(tasks).where(eq17(tasks.id, taskId)).all();
107754
+ const rows = await db.select({ ivtrState: tasks.ivtrState }).from(tasks).where(eq15(tasks.id, taskId)).all();
107956
107755
  if (rows.length === 0 || rows[0]?.ivtrState == null) return null;
107957
107756
  try {
107958
107757
  return JSON.parse(rows[0].ivtrState);
@@ -107963,12 +107762,12 @@ async function readIvtrStateRaw(taskId, cwd) {
107963
107762
  }
107964
107763
  async function writeIvtrState(state, cwd) {
107965
107764
  const db = await getDb(cwd);
107966
- const exists2 = await db.select({ id: tasks.id }).from(tasks).where(eq17(tasks.id, state.taskId)).get();
107765
+ const exists2 = await db.select({ id: tasks.id }).from(tasks).where(eq15(tasks.id, state.taskId)).get();
107967
107766
  if (!exists2) {
107968
107767
  throw new Error(`Task ${state.taskId} not found --- cannot write IVTR state`);
107969
107768
  }
107970
107769
  const json3 = JSON.stringify(state);
107971
- await db.update(tasks).set({ ivtrState: json3, updatedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq17(tasks.id, state.taskId)).run();
107770
+ await db.update(tasks).set({ ivtrState: json3, updatedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq15(tasks.id, state.taskId)).run();
107972
107771
  }
107973
107772
  async function startIvtr(taskId, options) {
107974
107773
  const existing = await readIvtrStateRaw(taskId, options?.cwd);
@@ -108109,7 +107908,7 @@ async function releaseIvtr(taskId, options) {
108109
107908
  state.currentPhase = "released";
108110
107909
  await writeIvtrState(state, options?.cwd);
108111
107910
  const db = await getDb(options?.cwd);
108112
- await db.update(tasks).set({ status: "done", completedAt: now2, updatedAt: now2 }).where(eq17(tasks.id, taskId)).all();
107911
+ await db.update(tasks).set({ status: "done", completedAt: now2, updatedAt: now2 }).where(eq15(tasks.id, taskId)).all();
108113
107912
  log11.info({ taskId }, "IVTR released --- task marked done");
108114
107913
  return { released: true };
108115
107914
  }
@@ -109863,7 +109662,7 @@ var init_brain_maintenance = __esm({
109863
109662
  });
109864
109663
 
109865
109664
  // packages/core/src/memory/brain-purge.ts
109866
- import { inArray as inArray8, ne as ne3, sql as sql15 } from "drizzle-orm";
109665
+ import { inArray as inArray6, ne as ne3, sql as sql15 } from "drizzle-orm";
109867
109666
  function countRowsNative(tableName) {
109868
109667
  const nativeDb = getBrainNativeDb();
109869
109668
  if (!nativeDb) return 0;
@@ -109912,7 +109711,7 @@ async function purgeBrainNoise(projectRoot) {
109912
109711
  const BATCH = 500;
109913
109712
  for (let i = 0; i < patternIdsToDelete.length; i += BATCH) {
109914
109713
  const batch = patternIdsToDelete.slice(i, i + BATCH);
109915
- await db.delete(brainPatterns).where(inArray8(brainPatterns.id, batch));
109714
+ await db.delete(brainPatterns).where(inArray6(brainPatterns.id, batch));
109916
109715
  patternsDeleted += batch.length;
109917
109716
  }
109918
109717
  }
@@ -109924,7 +109723,7 @@ async function purgeBrainNoise(projectRoot) {
109924
109723
  const BATCH = 500;
109925
109724
  for (let i = 0; i < ids.length; i += BATCH) {
109926
109725
  const batch = ids.slice(i, i + BATCH);
109927
- await db.delete(brainLearnings).where(inArray8(brainLearnings.id, batch));
109726
+ await db.delete(brainLearnings).where(inArray6(brainLearnings.id, batch));
109928
109727
  }
109929
109728
  }
109930
109729
  console.log(`Learnings deleted (all): ${learningsDeleted}`);
@@ -109932,7 +109731,7 @@ async function purgeBrainNoise(projectRoot) {
109932
109731
  const decisionsDeleted = decisionsToDelete.length;
109933
109732
  if (decisionsDeleted > 0) {
109934
109733
  const ids = decisionsToDelete.map((r) => r.id);
109935
- await db.delete(brainDecisions).where(inArray8(brainDecisions.id, ids));
109734
+ await db.delete(brainDecisions).where(inArray6(brainDecisions.id, ids));
109936
109735
  }
109937
109736
  console.log(`Decisions deleted (all except D-mntpeeer): ${decisionsDeleted}`);
109938
109737
  const allObservations = await db.select().from(brainObservations);
@@ -109979,7 +109778,7 @@ async function purgeBrainNoise(projectRoot) {
109979
109778
  const BATCH = 500;
109980
109779
  for (let i = 0; i < obsIdsToDelete.length; i += BATCH) {
109981
109780
  const batch = obsIdsToDelete.slice(i, i + BATCH);
109982
- await db.delete(brainObservations).where(inArray8(brainObservations.id, batch));
109781
+ await db.delete(brainObservations).where(inArray6(brainObservations.id, batch));
109983
109782
  observationsDeleted += batch.length;
109984
109783
  }
109985
109784
  }
@@ -111931,7 +111730,7 @@ var init_engine_compat = __esm({
111931
111730
  import { createHash as createHash22 } from "node:crypto";
111932
111731
  import { existsSync as existsSync113, readFileSync as readFileSync82, renameSync as renameSync8 } from "node:fs";
111933
111732
  import { join as join114 } from "node:path";
111934
- import { and as and14, count as count3, desc as desc6, eq as eq18, gte as gte3, isNull as isNull4, like as like3, lte as lte2, or as or6 } from "drizzle-orm";
111733
+ import { and as and13, count as count3, desc as desc6, eq as eq16, gte as gte3, isNull as isNull3, like as like3, lte as lte2, or as or5 } from "drizzle-orm";
111935
111734
  async function getDb3(cwd) {
111936
111735
  const { getDb: _getDb } = await Promise.resolve().then(() => (init_sqlite2(), sqlite_exports));
111937
111736
  return _getDb(cwd);
@@ -111950,13 +111749,13 @@ function effectivePageLimit2(limit, offset) {
111950
111749
  return limit ?? (offset !== void 0 ? 50 : void 0);
111951
111750
  }
111952
111751
  function buildManifestSqlFilters(filter) {
111953
- const conditions = [isNull4(pipelineManifest.archivedAt)];
111752
+ const conditions = [isNull3(pipelineManifest.archivedAt)];
111954
111753
  if (filter.status) {
111955
111754
  const storedStatus = filter.status === "completed" ? "active" : filter.status;
111956
- conditions.push(eq18(pipelineManifest.status, storedStatus));
111755
+ conditions.push(eq16(pipelineManifest.status, storedStatus));
111957
111756
  }
111958
111757
  if (filter.agent_type) {
111959
- conditions.push(eq18(pipelineManifest.type, filter.agent_type));
111758
+ conditions.push(eq16(pipelineManifest.type, filter.agent_type));
111960
111759
  }
111961
111760
  if (filter.dateAfter) {
111962
111761
  conditions.push(gte3(pipelineManifest.createdAt, `${filter.dateAfter} 00:00:00`));
@@ -112049,7 +111848,7 @@ async function pipelineManifestShow(researchId, projectRoot) {
112049
111848
  }
112050
111849
  try {
112051
111850
  const db = await getDb3(projectRoot);
112052
- const rows = await db.select().from(pipelineManifest).where(eq18(pipelineManifest.id, researchId)).limit(1);
111851
+ const rows = await db.select().from(pipelineManifest).where(eq16(pipelineManifest.id, researchId)).limit(1);
112053
111852
  if (rows.length === 0) {
112054
111853
  return {
112055
111854
  success: false,
@@ -112091,8 +111890,8 @@ async function pipelineManifestList(params2, projectRoot) {
112091
111890
  const offset = normalizeOffset2(params2.offset);
112092
111891
  const pageLimit = effectivePageLimit2(limit, offset);
112093
111892
  const { conditions, requiresInMemoryFiltering } = buildManifestSqlFilters(filter);
112094
- const whereClause = and14(...conditions);
112095
- const totalRow = await db.select({ count: count3() }).from(pipelineManifest).where(isNull4(pipelineManifest.archivedAt)).get();
111893
+ const whereClause = and13(...conditions);
111894
+ const totalRow = await db.select({ count: count3() }).from(pipelineManifest).where(isNull3(pipelineManifest.archivedAt)).get();
112096
111895
  const total = totalRow?.count ?? 0;
112097
111896
  if (!requiresInMemoryFiltering) {
112098
111897
  const filteredRow = await db.select({ count: count3() }).from(pipelineManifest).where(whereClause).get();
@@ -112139,9 +111938,9 @@ async function pipelineManifestFind(query, options, projectRoot) {
112139
111938
  const db = await getDb3(projectRoot);
112140
111939
  const likePattern = `%${query}%`;
112141
111940
  const rows = await db.select().from(pipelineManifest).where(
112142
- and14(
112143
- isNull4(pipelineManifest.archivedAt),
112144
- or6(like3(pipelineManifest.content, likePattern), like3(pipelineManifest.type, likePattern))
111941
+ and13(
111942
+ isNull3(pipelineManifest.archivedAt),
111943
+ or5(like3(pipelineManifest.content, likePattern), like3(pipelineManifest.type, likePattern))
112145
111944
  )
112146
111945
  ).orderBy(desc6(pipelineManifest.createdAt));
112147
111946
  const queryLower = query.toLowerCase();
@@ -112183,7 +111982,7 @@ async function pipelineManifestFind(query, options, projectRoot) {
112183
111982
  async function pipelineManifestPending(epicId, projectRoot) {
112184
111983
  try {
112185
111984
  const db = await getDb3(projectRoot);
112186
- const rows = await db.select().from(pipelineManifest).where(isNull4(pipelineManifest.archivedAt)).orderBy(desc6(pipelineManifest.createdAt));
111985
+ const rows = await db.select().from(pipelineManifest).where(isNull3(pipelineManifest.archivedAt)).orderBy(desc6(pipelineManifest.createdAt));
112187
111986
  const entries = rows.map(rowToEntry);
112188
111987
  let pending = entries.filter(
112189
111988
  (e) => e.status === "partial" || e.status === "blocked" || e.needs_followup && e.needs_followup.length > 0
@@ -112216,7 +112015,7 @@ async function pipelineManifestPending(epicId, projectRoot) {
112216
112015
  async function pipelineManifestStats(epicId, projectRoot) {
112217
112016
  try {
112218
112017
  const db = await getDb3(projectRoot);
112219
- const rows = await db.select().from(pipelineManifest).where(isNull4(pipelineManifest.archivedAt));
112018
+ const rows = await db.select().from(pipelineManifest).where(isNull3(pipelineManifest.archivedAt));
112220
112019
  const entries = rows.map(rowToEntry);
112221
112020
  let filtered = entries;
112222
112021
  if (epicId) {
@@ -112321,7 +112120,7 @@ async function pipelineManifestArchive(beforeDate, projectRoot) {
112321
112120
  error: { code: "E_DB_NOT_INITIALIZED", message: "Database not initialized" }
112322
112121
  };
112323
112122
  }
112324
- const rows = await db.select().from(pipelineManifest).where(isNull4(pipelineManifest.archivedAt));
112123
+ const rows = await db.select().from(pipelineManifest).where(isNull3(pipelineManifest.archivedAt));
112325
112124
  const toArchive = rows.filter((r) => r.createdAt.slice(0, 10) < beforeDate);
112326
112125
  if (toArchive.length === 0) {
112327
112126
  const remaining2 = rows.length;
@@ -112332,7 +112131,7 @@ async function pipelineManifestArchive(beforeDate, projectRoot) {
112332
112131
  }
112333
112132
  const archivedAt = now();
112334
112133
  for (const row of toArchive) {
112335
- await db.update(pipelineManifest).set({ archivedAt }).where(eq18(pipelineManifest.id, row.id));
112134
+ await db.update(pipelineManifest).set({ archivedAt }).where(eq16(pipelineManifest.id, row.id));
112336
112135
  }
112337
112136
  const remaining = rows.length - toArchive.length;
112338
112137
  return { success: true, data: { archived: toArchive.length, remaining } };
@@ -112349,7 +112148,7 @@ async function pipelineManifestArchive(beforeDate, projectRoot) {
112349
112148
  async function readManifestEntries2(projectRoot) {
112350
112149
  try {
112351
112150
  const db = await getDb3(projectRoot);
112352
- const rows = await db.select().from(pipelineManifest).where(isNull4(pipelineManifest.archivedAt)).orderBy(desc6(pipelineManifest.createdAt));
112151
+ const rows = await db.select().from(pipelineManifest).where(isNull3(pipelineManifest.archivedAt)).orderBy(desc6(pipelineManifest.createdAt));
112353
112152
  return rows.map(rowToEntry);
112354
112153
  } catch {
112355
112154
  return [];
@@ -112681,25 +112480,25 @@ async function measureTokenExchange(input) {
112681
112480
  );
112682
112481
  }
112683
112482
  async function whereClauses(filters) {
112684
- const { eq: eq22, gte: gte4, lte: lte3 } = await import("drizzle-orm");
112483
+ const { eq: eq20, gte: gte4, lte: lte3 } = await import("drizzle-orm");
112685
112484
  const clauses = [];
112686
- if (filters.provider) clauses.push(eq22(tokenUsage.provider, filters.provider));
112687
- if (filters.transport) clauses.push(eq22(tokenUsage.transport, filters.transport));
112688
- if (filters.gateway) clauses.push(eq22(tokenUsage.gateway, filters.gateway));
112689
- if (filters.domain) clauses.push(eq22(tokenUsage.domain, filters.domain));
112690
- if (filters.operation) clauses.push(eq22(tokenUsage.operation, filters.operation));
112691
- if (filters.sessionId) clauses.push(eq22(tokenUsage.sessionId, filters.sessionId));
112692
- if (filters.taskId) clauses.push(eq22(tokenUsage.taskId, filters.taskId));
112693
- if (filters.method) clauses.push(eq22(tokenUsage.method, filters.method));
112694
- if (filters.confidence) clauses.push(eq22(tokenUsage.confidence, filters.confidence));
112695
- if (filters.requestId) clauses.push(eq22(tokenUsage.requestId, filters.requestId));
112485
+ if (filters.provider) clauses.push(eq20(tokenUsage.provider, filters.provider));
112486
+ if (filters.transport) clauses.push(eq20(tokenUsage.transport, filters.transport));
112487
+ if (filters.gateway) clauses.push(eq20(tokenUsage.gateway, filters.gateway));
112488
+ if (filters.domain) clauses.push(eq20(tokenUsage.domain, filters.domain));
112489
+ if (filters.operation) clauses.push(eq20(tokenUsage.operation, filters.operation));
112490
+ if (filters.sessionId) clauses.push(eq20(tokenUsage.sessionId, filters.sessionId));
112491
+ if (filters.taskId) clauses.push(eq20(tokenUsage.taskId, filters.taskId));
112492
+ if (filters.method) clauses.push(eq20(tokenUsage.method, filters.method));
112493
+ if (filters.confidence) clauses.push(eq20(tokenUsage.confidence, filters.confidence));
112494
+ if (filters.requestId) clauses.push(eq20(tokenUsage.requestId, filters.requestId));
112696
112495
  if (filters.since) clauses.push(gte4(tokenUsage.createdAt, filters.since));
112697
112496
  if (filters.until) clauses.push(lte3(tokenUsage.createdAt, filters.until));
112698
112497
  return clauses;
112699
112498
  }
112700
112499
  async function recordTokenExchange(input) {
112701
112500
  const { getDb: getDb4 } = await Promise.resolve().then(() => (init_sqlite2(), sqlite_exports));
112702
- const { eq: eq22 } = await import("drizzle-orm");
112501
+ const { eq: eq20 } = await import("drizzle-orm");
112703
112502
  const measurement = await measureTokenExchange(input);
112704
112503
  const db = await getDb4(input.cwd);
112705
112504
  const row = {
@@ -112728,22 +112527,22 @@ async function recordTokenExchange(input) {
112728
112527
  })
112729
112528
  };
112730
112529
  await db.insert(tokenUsage).values(row);
112731
- const inserted = await db.select().from(tokenUsage).where(eq22(tokenUsage.id, row.id)).limit(1);
112530
+ const inserted = await db.select().from(tokenUsage).where(eq20(tokenUsage.id, row.id)).limit(1);
112732
112531
  return inserted[0];
112733
112532
  }
112734
112533
  async function showTokenUsage(id2, cwd) {
112735
112534
  const { getDb: getDb4 } = await Promise.resolve().then(() => (init_sqlite2(), sqlite_exports));
112736
- const { eq: eq22 } = await import("drizzle-orm");
112535
+ const { eq: eq20 } = await import("drizzle-orm");
112737
112536
  const db = await getDb4(cwd);
112738
- const rows = await db.select().from(tokenUsage).where(eq22(tokenUsage.id, id2)).limit(1);
112537
+ const rows = await db.select().from(tokenUsage).where(eq20(tokenUsage.id, id2)).limit(1);
112739
112538
  return rows[0] ?? null;
112740
112539
  }
112741
112540
  async function listTokenUsage(filters = {}, cwd) {
112742
112541
  const { getDb: getDb4 } = await Promise.resolve().then(() => (init_sqlite2(), sqlite_exports));
112743
- const { and: and17, count: count5, desc: desc8 } = await import("drizzle-orm");
112542
+ const { and: and16, count: count5, desc: desc8 } = await import("drizzle-orm");
112744
112543
  const db = await getDb4(cwd);
112745
112544
  const clauses = await whereClauses(filters);
112746
- const where = clauses.length > 0 ? and17(...clauses) : void 0;
112545
+ const where = clauses.length > 0 ? and16(...clauses) : void 0;
112747
112546
  const totalRows = await db.select({ count: count5() }).from(tokenUsage);
112748
112547
  const filteredRows = await db.select({ count: count5() }).from(tokenUsage).where(where);
112749
112548
  let query = db.select().from(tokenUsage).orderBy(desc8(tokenUsage.createdAt));
@@ -112759,10 +112558,10 @@ async function listTokenUsage(filters = {}, cwd) {
112759
112558
  }
112760
112559
  async function summarizeTokenUsage(filters = {}, cwd) {
112761
112560
  const { getDb: getDb4 } = await Promise.resolve().then(() => (init_sqlite2(), sqlite_exports));
112762
- const { and: and17, desc: desc8 } = await import("drizzle-orm");
112561
+ const { and: and16, desc: desc8 } = await import("drizzle-orm");
112763
112562
  const db = await getDb4(cwd);
112764
112563
  const clauses = await whereClauses(filters);
112765
- const where = clauses.length > 0 ? and17(...clauses) : void 0;
112564
+ const where = clauses.length > 0 ? and16(...clauses) : void 0;
112766
112565
  const rows = await db.select().from(tokenUsage).where(where).orderBy(desc8(tokenUsage.createdAt));
112767
112566
  const byMethod = /* @__PURE__ */ new Map();
112768
112567
  const byTransport = /* @__PURE__ */ new Map();
@@ -112803,17 +112602,17 @@ async function summarizeTokenUsage(filters = {}, cwd) {
112803
112602
  }
112804
112603
  async function deleteTokenUsage(id2, cwd) {
112805
112604
  const { getDb: getDb4 } = await Promise.resolve().then(() => (init_sqlite2(), sqlite_exports));
112806
- const { eq: eq22 } = await import("drizzle-orm");
112605
+ const { eq: eq20 } = await import("drizzle-orm");
112807
112606
  const db = await getDb4(cwd);
112808
- await db.delete(tokenUsage).where(eq22(tokenUsage.id, id2));
112607
+ await db.delete(tokenUsage).where(eq20(tokenUsage.id, id2));
112809
112608
  return { deleted: true, id: id2 };
112810
112609
  }
112811
112610
  async function clearTokenUsage(filters = {}, cwd) {
112812
112611
  const { getDb: getDb4 } = await Promise.resolve().then(() => (init_sqlite2(), sqlite_exports));
112813
- const { and: and17, count: count5 } = await import("drizzle-orm");
112612
+ const { and: and16, count: count5 } = await import("drizzle-orm");
112814
112613
  const db = await getDb4(cwd);
112815
112614
  const clauses = await whereClauses(filters);
112816
- const where = clauses.length > 0 ? and17(...clauses) : void 0;
112615
+ const where = clauses.length > 0 ? and16(...clauses) : void 0;
112817
112616
  const countRows = await db.select({ count: count5() }).from(tokenUsage).where(where);
112818
112617
  await db.delete(tokenUsage).where(where);
112819
112618
  return { deleted: countRows[0]?.count ?? 0 };
@@ -113254,7 +113053,7 @@ function Pn(s3, t) {
113254
113053
  function zn(s3, t) {
113255
113054
  s3.head = new ue(t, void 0, s3.head, s3), s3.tail || (s3.tail = s3.head), s3.length++;
113256
113055
  }
113257
- var kr, vr, Os, Br, Pr, zr, q, j, rt, Le, jt, Ne, Ts, Ae, xs, z10, Mt, b, Qt, Bt, _, A, g, yi, De, L2, w, Ri, bi, Ls, _i, Z, gi, Ie, Jt, yt, C2, te, Ur, Hr, Wr, Gr, Ce, Oi, Zr, Yr, D, Vr, ot, H, ee, m, xi, J, Li, Ii, Ci, se, Fe, Ut, Ht, Ni, Pt, ht, U, nt, Y, zt, Ai, Q, ie, Di, ke, Rt, ve, bt, _t, Me, tt, Wt, $r, As, Ds, Is, Cs, Fs, Xr, re, K, jr, M2, Qr, vs, Jr, ki, Ot, Gt, vi, ne4, Be, Pe, ze, Ue, He, We, Ge, Ze, Ye, Ms, en, sn, Bs, rn, nn, Ps, zs, Bi, oe, hn, he, Ke, F, an, Tt, Pi, ln, at, cn, fn, dn, lt3, un, mn, pn, zi, En, xt, ct, Sn, yn, Rn, bn, f, Yt, Lt, gn, Zi, Yi, On, B, Nt, et, Ui, Us, V, ae, ft, Hs, p, it, dt, Hi, At, y, Ve, $e, Wi, Ws, Gs, le, Gi, Xe, Kt, ut, qe, Dt, je, Qe, Zs, Tn, st, mt, Nn, Ki, An, Dn, It, Vi, Cn, Ys, ce, Je, $i, Fn, kn, Xi, Ks, Js, vn, Xs, qs, js, ji, Qs, fe, ti, Qi, ei, Ji, ts, es, is2, pt, ii, ss, qi, X, de, si, ri, Mn, ni, ue, di, tr, oi, me, W2, Ct, Ft, pe, rs, G2, ns, hi, er, as, ls, ai, li, ir, os, ci, rr, hs, Et, kt, Un, Hn, or7, hr, Wn, Gn, Zn, Yn, fr, dr, ar, ur, mr, pr, Kn, Vn, $n, lr, cs, fs3, ui, Xn, ds, qn, us, we, wt, Qn, Er, ms, wr, Jn, Sr, ps, yr, $t, Rr, to, eo, io, Ei, _r, gr, ys, Or, Rs, P2, bs, _s, Si, Tr, xr, ye, Lr, Nr, Es, St, O, wi, Ar, Xt, ws, Ss, gs, Re, be, _e, ge, ro, Oe, no, oo, ho, Dr, qt, Se, Te, ao, lo, co, fo, uo, mo, po, Eo, vt, wo, So;
113056
+ var kr, vr, Os, Br, Pr, zr, q, j, rt, Le, jt, Ne, Ts, Ae, xs, z10, Mt, b, Qt, Bt, _, A, g, yi, De, L2, w, Ri, bi, Ls, _i, Z, gi, Ie, Jt, yt, C2, te, Ur, Hr, Wr, Gr, Ce, Oi, Zr, Yr, D, Vr, ot, H, ee, m, xi, J, Li, Ii, Ci, se, Fe, Ut, Ht, Ni, Pt, ht, U, nt, Y, zt, Ai, Q, ie, Di, ke, Rt, ve, bt, _t, Me, tt, Wt, $r, As, Ds, Is, Cs, Fs, Xr, re, K, jr, M2, Qr, vs, Jr, ki, Ot, Gt, vi, ne4, Be, Pe, ze, Ue, He, We, Ge, Ze, Ye, Ms, en, sn, Bs, rn, nn, Ps, zs, Bi, oe, hn, he, Ke, F, an, Tt, Pi, ln, at, cn, fn, dn, lt3, un, mn, pn, zi, En, xt, ct, Sn, yn, Rn, bn, f, Yt, Lt, gn, Zi, Yi, On, B, Nt, et, Ui, Us, V, ae, ft, Hs, p, it, dt, Hi, At, y, Ve, $e, Wi, Ws, Gs, le, Gi, Xe, Kt, ut, qe, Dt, je, Qe, Zs, Tn, st, mt, Nn, Ki, An, Dn, It, Vi, Cn, Ys, ce, Je, $i, Fn, kn, Xi, Ks, Js, vn, Xs, qs, js, ji, Qs, fe, ti, Qi, ei, Ji, ts, es, is2, pt, ii, ss, qi, X, de, si, ri, Mn, ni, ue, di, tr, oi, me, W2, Ct, Ft, pe, rs, G2, ns, hi, er, as, ls, ai, li, ir, os, ci, rr, hs, Et, kt, Un, Hn, or6, hr, Wn, Gn, Zn, Yn, fr, dr, ar, ur, mr, pr, Kn, Vn, $n, lr, cs, fs3, ui, Xn, ds, qn, us, we, wt, Qn, Er, ms, wr, Jn, Sr, ps, yr, $t, Rr, to, eo, io, Ei, _r, gr, ys, Or, Rs, P2, bs, _s, Si, Tr, xr, ye, Lr, Nr, Es, St, O, wi, Ar, Xt, ws, Ss, gs, Re, be, _e, ge, ro, Oe, no, oo, ho, Dr, qt, Se, Te, ao, lo, co, fo, uo, mo, po, Eo, vt, wo, So;
113258
113057
  var init_index_min = __esm({
113259
113058
  "node_modules/.pnpm/tar@7.5.13/node_modules/tar/dist/esm/index.min.js"() {
113260
113059
  kr = Object.defineProperty;
@@ -115281,7 +115080,7 @@ var init_index_min = __esm({
115281
115080
  };
115282
115081
  Un = (s3, t) => {
115283
115082
  let e = new kt(s3), i = new Wt(s3.file, { mode: s3.mode || 438 });
115284
- e.pipe(i), or7(e, t);
115083
+ e.pipe(i), or6(e, t);
115285
115084
  };
115286
115085
  Hn = (s3, t) => {
115287
115086
  let e = new Et(s3), i = new tt(s3.file, { mode: s3.mode || 438 });
@@ -115291,7 +115090,7 @@ var init_index_min = __esm({
115291
115090
  });
115292
115091
  return hr(e, t).catch((n) => e.emit("error", n)), r;
115293
115092
  };
115294
- or7 = (s3, t) => {
115093
+ or6 = (s3, t) => {
115295
115094
  t.forEach((e) => {
115296
115095
  e.charAt(0) === "@" ? It({ file: nr.resolve(s3.cwd, e.slice(1)), sync: true, noResume: true, onReadEntry: (i) => s3.add(i) }) : s3.add(e);
115297
115096
  }), s3.end();
@@ -115304,7 +115103,7 @@ var init_index_min = __esm({
115304
115103
  };
115305
115104
  Wn = (s3, t) => {
115306
115105
  let e = new kt(s3);
115307
- return or7(e, t), e;
115106
+ return or6(e, t), e;
115308
115107
  };
115309
115108
  Gn = (s3, t) => {
115310
115109
  let e = new Et(s3);
@@ -117116,7 +116915,7 @@ __export(session_store_exports, {
117116
116915
  updateSession: () => updateSession,
117117
116916
  workHistory: () => workHistory
117118
116917
  });
117119
- import { and as and15, desc as desc7, eq as eq19, isNull as isNull5 } from "drizzle-orm";
116918
+ import { and as and14, desc as desc7, eq as eq17, isNull as isNull4 } from "drizzle-orm";
117120
116919
  async function createSession(session, cwd) {
117121
116920
  const db = await getDb(cwd);
117122
116921
  const tw = session.taskWork;
@@ -117138,7 +116937,7 @@ async function createSession(session, cwd) {
117138
116937
  }
117139
116938
  async function getSession(sessionId, cwd) {
117140
116939
  const db = await getDb(cwd);
117141
- const rows = await db.select().from(sessions).where(eq19(sessions.id, sessionId)).all();
116940
+ const rows = await db.select().from(sessions).where(eq17(sessions.id, sessionId)).all();
117142
116941
  if (rows.length === 0) return null;
117143
116942
  return rowToSession(rows[0]);
117144
116943
  }
@@ -117167,16 +116966,16 @@ async function updateSession(sessionId, updates, cwd) {
117167
116966
  updateRow.handoffConsumedBy = updates.handoffConsumedBy;
117168
116967
  if (updates.debriefJson !== void 0) updateRow.debriefJson = updates.debriefJson;
117169
116968
  if (updates.handoffJson !== void 0) updateRow.handoffJson = updates.handoffJson;
117170
- db.update(sessions).set(updateRow).where(eq19(sessions.id, sessionId)).run();
116969
+ db.update(sessions).set(updateRow).where(eq17(sessions.id, sessionId)).run();
117171
116970
  return getSession(sessionId, cwd);
117172
116971
  }
117173
116972
  async function listSessions2(filters, cwd) {
117174
116973
  const db = await getDb(cwd);
117175
116974
  const conditions = [];
117176
116975
  if (filters?.active) {
117177
- conditions.push(eq19(sessions.status, "active"));
116976
+ conditions.push(eq17(sessions.status, "active"));
117178
116977
  }
117179
- const query = db.select().from(sessions).where(conditions.length > 0 ? and15(...conditions) : void 0).orderBy(desc7(sessions.startedAt));
116978
+ const query = db.select().from(sessions).where(conditions.length > 0 ? and14(...conditions) : void 0).orderBy(desc7(sessions.startedAt));
117180
116979
  const rows = filters?.limit ? await query.limit(filters.limit).all() : await query.all();
117181
116980
  return rows.map(rowToSession);
117182
116981
  }
@@ -117198,20 +116997,20 @@ async function startTask2(sessionId, taskId, cwd) {
117198
116997
  const db = await getDb(cwd);
117199
116998
  const now2 = (/* @__PURE__ */ new Date()).toISOString();
117200
116999
  db.update(taskWorkHistory).set({ clearedAt: now2 }).where(
117201
- and15(
117202
- eq19(taskWorkHistory.sessionId, sessionId),
117203
- isNull5(taskWorkHistory.clearedAt)
117000
+ and14(
117001
+ eq17(taskWorkHistory.sessionId, sessionId),
117002
+ isNull4(taskWorkHistory.clearedAt)
117204
117003
  )
117205
117004
  ).run();
117206
117005
  db.insert(taskWorkHistory).values({ sessionId, taskId, setAt: now2 }).run();
117207
- db.update(sessions).set({ currentTask: taskId, taskStartedAt: now2 }).where(eq19(sessions.id, sessionId)).run();
117006
+ db.update(sessions).set({ currentTask: taskId, taskStartedAt: now2 }).where(eq17(sessions.id, sessionId)).run();
117208
117007
  }
117209
117008
  async function getCurrentTask(sessionId, cwd) {
117210
117009
  const db = await getDb(cwd);
117211
117010
  const rows = await db.select({
117212
117011
  currentTask: sessions.currentTask,
117213
117012
  taskStartedAt: sessions.taskStartedAt
117214
- }).from(sessions).where(eq19(sessions.id, sessionId)).all();
117013
+ }).from(sessions).where(eq17(sessions.id, sessionId)).all();
117215
117014
  if (rows.length === 0) return { taskId: null, since: null };
117216
117015
  return { taskId: rows[0].currentTask, since: rows[0].taskStartedAt };
117217
117016
  }
@@ -117219,16 +117018,16 @@ async function stopTask2(sessionId, cwd) {
117219
117018
  const db = await getDb(cwd);
117220
117019
  const now2 = (/* @__PURE__ */ new Date()).toISOString();
117221
117020
  db.update(taskWorkHistory).set({ clearedAt: now2 }).where(
117222
- and15(
117223
- eq19(taskWorkHistory.sessionId, sessionId),
117224
- isNull5(taskWorkHistory.clearedAt)
117021
+ and14(
117022
+ eq17(taskWorkHistory.sessionId, sessionId),
117023
+ isNull4(taskWorkHistory.clearedAt)
117225
117024
  )
117226
117025
  ).run();
117227
- db.update(sessions).set({ currentTask: null, taskStartedAt: null }).where(eq19(sessions.id, sessionId)).run();
117026
+ db.update(sessions).set({ currentTask: null, taskStartedAt: null }).where(eq17(sessions.id, sessionId)).run();
117228
117027
  }
117229
117028
  async function workHistory(sessionId, limit = 50, cwd) {
117230
117029
  const db = await getDb(cwd);
117231
- const rows = await db.select().from(taskWorkHistory).where(eq19(taskWorkHistory.sessionId, sessionId)).orderBy(desc7(taskWorkHistory.setAt), desc7(taskWorkHistory.id)).limit(limit).all();
117030
+ const rows = await db.select().from(taskWorkHistory).where(eq17(taskWorkHistory.sessionId, sessionId)).orderBy(desc7(taskWorkHistory.setAt), desc7(taskWorkHistory.id)).limit(limit).all();
117232
117031
  return rows.map((r) => ({
117233
117032
  taskId: r.taskId,
117234
117033
  setAt: r.setAt,
@@ -117239,16 +117038,16 @@ async function gcSessions2(maxAgeDays = 30, cwd) {
117239
117038
  const db = await getDb(cwd);
117240
117039
  const threshold = /* @__PURE__ */ new Date();
117241
117040
  threshold.setDate(threshold.getDate() - maxAgeDays);
117242
- const before = await db.select({ id: sessions.id }).from(sessions).where(and15(eq19(sessions.status, "ended"))).all();
117041
+ const before = await db.select({ id: sessions.id }).from(sessions).where(and14(eq17(sessions.status, "ended"))).all();
117243
117042
  const toUpdate = before;
117244
117043
  if (toUpdate.length > 0) {
117245
- db.update(sessions).set({ status: "orphaned" }).where(eq19(sessions.status, "ended")).run();
117044
+ db.update(sessions).set({ status: "orphaned" }).where(eq17(sessions.status, "ended")).run();
117246
117045
  }
117247
117046
  return toUpdate.length;
117248
117047
  }
117249
117048
  async function getActiveSession(cwd) {
117250
117049
  const db = await getDb(cwd);
117251
- const rows = await db.select().from(sessions).where(eq19(sessions.status, "active")).orderBy(desc7(sessions.startedAt)).limit(1).all();
117050
+ const rows = await db.select().from(sessions).where(eq17(sessions.status, "active")).orderBy(desc7(sessions.startedAt)).limit(1).all();
117252
117051
  if (rows.length === 0) return null;
117253
117052
  return rowToSession(rows[0]);
117254
117053
  }
@@ -117262,12 +117061,12 @@ var init_session_store = __esm({
117262
117061
  });
117263
117062
 
117264
117063
  // packages/core/src/store/data-safety.ts
117265
- import { eq as eq20 } from "drizzle-orm";
117064
+ import { eq as eq18 } from "drizzle-orm";
117266
117065
  async function checkTaskExists(taskId, cwd, config2 = {}) {
117267
117066
  const cfg = { ...DEFAULT_CONFIG2, ...config2 };
117268
117067
  if (!cfg.detectCollisions) return false;
117269
117068
  const db = await getDb(cwd);
117270
- const existing = await db.select().from(tasks).where(eq20(tasks.id, taskId)).all();
117069
+ const existing = await db.select().from(tasks).where(eq18(tasks.id, taskId)).all();
117271
117070
  const exists2 = existing.length > 0;
117272
117071
  if (exists2 && cfg.strictMode) {
117273
117072
  throw new SafetyError(
@@ -117417,7 +117216,7 @@ __export(task_store_exports, {
117417
117216
  updateTask: () => updateTask2,
117418
117217
  updateTaskSafe: () => updateTaskSafe
117419
117218
  });
117420
- import { and as and16, asc as asc4, count as count4, eq as eq21, inArray as inArray9, isNull as isNull6, ne as ne5, sql as sql16 } from "drizzle-orm";
117219
+ import { and as and15, asc as asc4, count as count4, eq as eq19, inArray as inArray7, isNull as isNull5, ne as ne5, sql as sql16 } from "drizzle-orm";
117421
117220
  async function insertTaskRow(task, cwd) {
117422
117221
  const db = await getDb(cwd);
117423
117222
  const row = taskToRow(task);
@@ -117431,10 +117230,10 @@ async function insertTaskRow(task, cwd) {
117431
117230
  }
117432
117231
  async function getTask(taskId, cwd) {
117433
117232
  const db = await getDb(cwd);
117434
- const rows = await db.select().from(tasks).where(eq21(tasks.id, taskId)).all();
117233
+ const rows = await db.select().from(tasks).where(eq19(tasks.id, taskId)).all();
117435
117234
  if (rows.length === 0) return null;
117436
117235
  const task = rowToTask(rows[0]);
117437
- const deps = await db.select().from(taskDependencies).where(eq21(taskDependencies.taskId, taskId)).all();
117236
+ const deps = await db.select().from(taskDependencies).where(eq19(taskDependencies.taskId, taskId)).all();
117438
117237
  if (deps.length > 0) {
117439
117238
  task.depends = deps.map((d) => d.dependsOn);
117440
117239
  }
@@ -117477,9 +117276,9 @@ async function updateTask2(taskId, updates, cwd) {
117477
117276
  if (updates.verification !== void 0)
117478
117277
  updateRow.verificationJson = JSON.stringify(updates.verification);
117479
117278
  if (updates.assignee !== void 0) updateRow.assignee = updates.assignee;
117480
- db.update(tasks).set(updateRow).where(eq21(tasks.id, taskId)).run();
117279
+ db.update(tasks).set(updateRow).where(eq19(tasks.id, taskId)).run();
117481
117280
  if (updates.depends !== void 0) {
117482
- db.delete(taskDependencies).where(eq21(taskDependencies.taskId, taskId)).run();
117281
+ db.delete(taskDependencies).where(eq19(taskDependencies.taskId, taskId)).run();
117483
117282
  for (const depId of updates.depends) {
117484
117283
  db.insert(taskDependencies).values({ taskId, dependsOn: depId }).run();
117485
117284
  }
@@ -117488,9 +117287,9 @@ async function updateTask2(taskId, updates, cwd) {
117488
117287
  }
117489
117288
  async function deleteTask2(taskId, cwd) {
117490
117289
  const db = await getDb(cwd);
117491
- const existing = await db.select({ id: tasks.id }).from(tasks).where(eq21(tasks.id, taskId)).all();
117290
+ const existing = await db.select({ id: tasks.id }).from(tasks).where(eq19(tasks.id, taskId)).all();
117492
117291
  if (existing.length === 0) return false;
117493
- db.delete(tasks).where(eq21(tasks.id, taskId)).run();
117292
+ db.delete(tasks).where(eq19(tasks.id, taskId)).run();
117494
117293
  void cleanupBrainRefsOnTaskDelete(taskId, cwd);
117495
117294
  return true;
117496
117295
  }
@@ -117498,17 +117297,17 @@ async function listTasks2(filters, cwd) {
117498
117297
  const db = await getDb(cwd);
117499
117298
  const conditions = [];
117500
117299
  conditions.push(ne5(tasks.status, "archived"));
117501
- if (filters?.status) conditions.push(eq21(tasks.status, filters.status));
117300
+ if (filters?.status) conditions.push(eq19(tasks.status, filters.status));
117502
117301
  if (filters?.parentId !== void 0) {
117503
117302
  if (filters.parentId === null) {
117504
- conditions.push(isNull6(tasks.parentId));
117303
+ conditions.push(isNull5(tasks.parentId));
117505
117304
  } else {
117506
- conditions.push(eq21(tasks.parentId, filters.parentId));
117305
+ conditions.push(eq19(tasks.parentId, filters.parentId));
117507
117306
  }
117508
117307
  }
117509
- if (filters?.type) conditions.push(eq21(tasks.type, filters.type));
117510
- if (filters?.phase) conditions.push(eq21(tasks.phase, filters.phase));
117511
- const query = db.select().from(tasks).where(conditions.length > 0 ? and16(...conditions) : void 0).orderBy(asc4(tasks.position), asc4(tasks.createdAt));
117308
+ if (filters?.type) conditions.push(eq19(tasks.type, filters.type));
117309
+ if (filters?.phase) conditions.push(eq19(tasks.phase, filters.phase));
117310
+ const query = db.select().from(tasks).where(conditions.length > 0 ? and15(...conditions) : void 0).orderBy(asc4(tasks.position), asc4(tasks.createdAt));
117512
117311
  const rows = filters?.limit ? await query.limit(filters.limit).all() : await query.all();
117513
117312
  const tasks2 = rows.map(rowToTask);
117514
117313
  await loadDependencies(tasks2, cwd);
@@ -117518,7 +117317,7 @@ async function findTasks2(query, limit = 20, cwd) {
117518
117317
  const db = await getDb(cwd);
117519
117318
  const pattern = `%${query}%`;
117520
117319
  const rows = await db.select().from(tasks).where(
117521
- and16(
117320
+ and15(
117522
117321
  ne5(tasks.status, "archived"),
117523
117322
  sql16`(${tasks.id} LIKE ${pattern} OR ${tasks.title} LIKE ${pattern} OR ${tasks.description} LIKE ${pattern})`
117524
117323
  )
@@ -117537,14 +117336,14 @@ async function archiveTask(taskId, reason, cwd) {
117537
117336
  archiveReason: reason ?? "completed",
117538
117337
  cycleTimeDays: cycleTime,
117539
117338
  updatedAt: now2
117540
- }).where(eq21(tasks.id, taskId)).run();
117339
+ }).where(eq19(tasks.id, taskId)).run();
117541
117340
  return true;
117542
117341
  }
117543
117342
  async function loadDependencies(tasks2, cwd) {
117544
117343
  if (tasks2.length === 0) return;
117545
117344
  const db = await getDb(cwd);
117546
117345
  const taskIds = tasks2.map((t) => t.id);
117547
- const deps = await db.select().from(taskDependencies).where(inArray9(taskDependencies.taskId, taskIds)).all();
117346
+ const deps = await db.select().from(taskDependencies).where(inArray7(taskDependencies.taskId, taskIds)).all();
117548
117347
  const depMap = /* @__PURE__ */ new Map();
117549
117348
  for (const dep of deps) {
117550
117349
  if (!depMap.has(dep.taskId)) depMap.set(dep.taskId, []);
@@ -117564,9 +117363,9 @@ async function addDependency(taskId, dependsOn, cwd) {
117564
117363
  async function removeDependency(taskId, dependsOn, cwd) {
117565
117364
  const db = await getDb(cwd);
117566
117365
  db.delete(taskDependencies).where(
117567
- and16(
117568
- eq21(taskDependencies.taskId, taskId),
117569
- eq21(taskDependencies.dependsOn, dependsOn)
117366
+ and15(
117367
+ eq19(taskDependencies.taskId, taskId),
117368
+ eq19(taskDependencies.dependsOn, dependsOn)
117570
117369
  )
117571
117370
  ).run();
117572
117371
  }
@@ -117576,7 +117375,7 @@ async function addRelation(taskId, relatedTo, relationType = "related", cwd, rea
117576
117375
  }
117577
117376
  async function getRelations(taskId, cwd) {
117578
117377
  const db = await getDb(cwd);
117579
- const rows = await db.select().from(taskRelations).where(eq21(taskRelations.taskId, taskId)).all();
117378
+ const rows = await db.select().from(taskRelations).where(eq19(taskRelations.taskId, taskId)).all();
117580
117379
  return rows.map((r) => ({
117581
117380
  relatedTo: r.relatedTo,
117582
117381
  type: r.relationType,
@@ -117600,7 +117399,7 @@ async function getBlockerChain(taskId, cwd) {
117600
117399
  }
117601
117400
  async function getChildren2(parentId, cwd) {
117602
117401
  const db = await getDb(cwd);
117603
- const rows = await db.select().from(tasks).where(eq21(tasks.parentId, parentId)).orderBy(asc4(tasks.position), asc4(tasks.createdAt)).all();
117402
+ const rows = await db.select().from(tasks).where(eq19(tasks.parentId, parentId)).orderBy(asc4(tasks.position), asc4(tasks.createdAt)).all();
117604
117403
  return rows.map(rowToTask);
117605
117404
  }
117606
117405
  async function getSubtree(rootId, cwd) {
@@ -119008,6 +118807,7 @@ async function runMigrationDataImport(db, cleoDir, result, logger) {
119008
118807
  for (let i = 0; i < tasks2.length; i++) {
119009
118808
  const task = tasks2[i];
119010
118809
  try {
118810
+ const importedPipelineStage = task.pipelineStage ?? (task.status === "done" ? "contribution" : task.status === "cancelled" ? "cancelled" : null);
119011
118811
  await db.insert(tasks).values({
119012
118812
  id: task.id,
119013
118813
  title: task.title,
@@ -119035,7 +118835,8 @@ async function runMigrationDataImport(db, cleoDir, result, logger) {
119035
118835
  verificationJson: task.verification ? JSON.stringify(task.verification) : void 0,
119036
118836
  createdBy: task.provenance?.createdBy,
119037
118837
  modifiedBy: task.provenance?.modifiedBy,
119038
- sessionId: task.provenance?.sessionId
118838
+ sessionId: task.provenance?.sessionId,
118839
+ pipelineStage: importedPipelineStage
119039
118840
  }).onConflictDoNothing().run();
119040
118841
  if (task.depends) {
119041
118842
  for (const depId of task.depends) {
@@ -119217,10 +119018,10 @@ async function migrateJsonToSqlite2(cwd, options) {
119217
119018
  const jsonCounts = countJsonRecords(cleoDir);
119218
119019
  result.jsonCounts = jsonCounts;
119219
119020
  if (dbExists(cwd)) {
119220
- const { ne: ne6, eq: eq22, count: count5 } = await import("drizzle-orm");
119021
+ const { ne: ne6, eq: eq20, count: count5 } = await import("drizzle-orm");
119221
119022
  const db2 = await getDb(cwd);
119222
119023
  const tasksResult = await db2.select({ count: count5() }).from(tasks).where(ne6(tasks.status, "archived")).get();
119223
- const archivedResult = await db2.select({ count: count5() }).from(tasks).where(eq22(tasks.status, "archived")).get();
119024
+ const archivedResult = await db2.select({ count: count5() }).from(tasks).where(eq20(tasks.status, "archived")).get();
119224
119025
  const sessionsResult = await db2.select({ count: count5() }).from(sessions).get();
119225
119026
  const existingCounts = {
119226
119027
  tasks: tasksResult?.count ?? 0,
@@ -119282,6 +119083,7 @@ async function migrateJsonToSqlite2(cwd, options) {
119282
119083
  const tasks2 = topoSortTasks(todoData.tasks ?? []);
119283
119084
  for (const task of tasks2) {
119284
119085
  try {
119086
+ const importedPipelineStage = task.pipelineStage ?? (task.status === "done" ? "contribution" : task.status === "cancelled" ? "cancelled" : null);
119285
119087
  db.insert(tasks).values({
119286
119088
  id: task.id,
119287
119089
  title: task.title,
@@ -119309,7 +119111,8 @@ async function migrateJsonToSqlite2(cwd, options) {
119309
119111
  verificationJson: task.verification ? JSON.stringify(task.verification) : void 0,
119310
119112
  createdBy: task.provenance?.createdBy,
119311
119113
  modifiedBy: task.provenance?.modifiedBy,
119312
- sessionId: task.provenance?.sessionId
119114
+ sessionId: task.provenance?.sessionId,
119115
+ pipelineStage: importedPipelineStage
119313
119116
  }).onConflictDoNothing().run();
119314
119117
  if (task.depends) {
119315
119118
  for (const depId of task.depends) {
@@ -119404,10 +119207,10 @@ async function migrateJsonToSqlite2(cwd, options) {
119404
119207
  async function exportToJson(cwd) {
119405
119208
  const { listTasks: listTasks3 } = await Promise.resolve().then(() => (init_task_store(), task_store_exports));
119406
119209
  const { listSessions: listSessions3 } = await Promise.resolve().then(() => (init_session_store(), session_store_exports));
119407
- const { eq: eq22 } = await import("drizzle-orm");
119210
+ const { eq: eq20 } = await import("drizzle-orm");
119408
119211
  const tasks2 = await listTasks3(void 0, cwd);
119409
119212
  const db = await getDb(cwd);
119410
- const archivedRows = await db.select().from(tasks).where(eq22(tasks.status, "archived")).all();
119213
+ const archivedRows = await db.select().from(tasks).where(eq20(tasks.status, "archived")).all();
119411
119214
  const archived = archivedRows.map((row) => ({
119412
119215
  id: row.id,
119413
119216
  title: row.title,
@@ -119443,9 +119246,9 @@ __export(repair_exports, {
119443
119246
  async function repairMissingSizes(cwd, dryRun) {
119444
119247
  const { getDb: getDb4 } = await Promise.resolve().then(() => (init_sqlite2(), sqlite_exports));
119445
119248
  const { tasks: tasks2 } = await Promise.resolve().then(() => (init_tasks_schema(), tasks_schema_exports));
119446
- const { isNull: isNull7 } = await import("drizzle-orm");
119249
+ const { isNull: isNull6 } = await import("drizzle-orm");
119447
119250
  const db = await getDb4(cwd);
119448
- const affected = await db.select({ id: tasks2.id }).from(tasks2).where(isNull7(tasks2.size));
119251
+ const affected = await db.select({ id: tasks2.id }).from(tasks2).where(isNull6(tasks2.size));
119449
119252
  if (affected.length === 0) {
119450
119253
  return {
119451
119254
  action: "fix_missing_sizes",
@@ -119460,7 +119263,7 @@ async function repairMissingSizes(cwd, dryRun) {
119460
119263
  details: `Would set size='medium' for ${affected.length} task(s)`
119461
119264
  };
119462
119265
  }
119463
- await db.update(tasks2).set({ size: "medium" }).where(isNull7(tasks2.size));
119266
+ await db.update(tasks2).set({ size: "medium" }).where(isNull6(tasks2.size));
119464
119267
  return {
119465
119268
  action: "fix_missing_sizes",
119466
119269
  status: "applied",
@@ -122318,7 +122121,7 @@ async function validateSqliteRows(type, projectRoot) {
122318
122121
  const { getDb: getDb4 } = await Promise.resolve().then(() => (init_sqlite2(), sqlite_exports));
122319
122122
  const schemaTable = await Promise.resolve().then(() => (init_tasks_schema(), tasks_schema_exports));
122320
122123
  const zodSchemas = await Promise.resolve().then(() => (init_validation_schemas(), validation_schemas_exports));
122321
- const { ne: ne6, eq: eq22 } = await import("drizzle-orm");
122124
+ const { ne: ne6, eq: eq20 } = await import("drizzle-orm");
122322
122125
  const db = await getDb4(projectRoot);
122323
122126
  const errors = [];
122324
122127
  switch (type) {
@@ -122330,7 +122133,7 @@ async function validateSqliteRows(type, projectRoot) {
122330
122133
  break;
122331
122134
  }
122332
122135
  case "archive": {
122333
- const rows = await db.select().from(schemaTable.tasks).where(eq22(schemaTable.tasks.status, "archived"));
122136
+ const rows = await db.select().from(schemaTable.tasks).where(eq20(schemaTable.tasks.status, "archived"));
122334
122137
  for (const row of rows) {
122335
122138
  errors.push(...collectZodErrors(zodSchemas.selectTaskSchema.safeParse(row), row.id));
122336
122139
  }
@@ -123983,15 +123786,15 @@ var require_codegen = __commonJS({
123983
123786
  }
123984
123787
  exports.not = not2;
123985
123788
  var andCode = mappend(exports.operators.AND);
123986
- function and17(...args2) {
123789
+ function and16(...args2) {
123987
123790
  return args2.reduce(andCode);
123988
123791
  }
123989
- exports.and = and17;
123792
+ exports.and = and16;
123990
123793
  var orCode = mappend(exports.operators.OR);
123991
- function or8(...args2) {
123794
+ function or7(...args2) {
123992
123795
  return args2.reduce(orCode);
123993
123796
  }
123994
- exports.or = or8;
123797
+ exports.or = or7;
123995
123798
  function mappend(op) {
123996
123799
  return (x, y2) => x === code_1.nil ? y2 : y2 === code_1.nil ? x : (0, code_1._)`${par(x)} ${op} ${par(y2)}`;
123997
123800
  }
@@ -132266,7 +132069,6 @@ __export(internal_exports, {
132266
132069
  MINIMUM_NODE_MAJOR: () => MINIMUM_NODE_MAJOR,
132267
132070
  OrchestrationLevel: () => OrchestrationLevel,
132268
132071
  PIPELINE_STAGES: () => PIPELINE_STAGES,
132269
- PIPELINE_STAGE_BACKFILL_KEY: () => BACKFILL_KEY,
132270
132072
  PIPELINE_STATUS_ICONS: () => PIPELINE_STATUS_ICONS,
132271
132073
  PLATFORM: () => PLATFORM,
132272
132074
  PROTOCOL_RULES: () => PROTOCOL_RULES,
@@ -132288,7 +132090,6 @@ __export(internal_exports, {
132288
132090
  TASK_STATUSES: () => TASK_STATUSES,
132289
132091
  TASK_STATUS_SYMBOLS_ASCII: () => TASK_STATUS_SYMBOLS_ASCII,
132290
132092
  TASK_STATUS_SYMBOLS_UNICODE: () => TASK_STATUS_SYMBOLS_UNICODE,
132291
- TERMINAL_PIPELINE_STAGE_BACKFILL_KEY: () => TERMINAL_BACKFILL_KEY,
132292
132093
  TERMINAL_PIPELINE_STATUSES: () => TERMINAL_PIPELINE_STATUSES,
132293
132094
  TERMINAL_STAGE_STATUSES: () => TERMINAL_STAGE_STATUSES,
132294
132095
  TERMINAL_TASK_STATUSES: () => TERMINAL_TASK_STATUSES,
@@ -132351,9 +132152,7 @@ __export(internal_exports, {
132351
132152
  autoRecordDispatchTokenUsage: () => autoRecordDispatchTokenUsage,
132352
132153
  autoRunGatesAndRecord: () => autoRunGatesAndRecord,
132353
132154
  backfillBrainGraph: () => backfillBrainGraph,
132354
- backfillPipelineStageFromLifecycle: () => backfillPipelineStageFromLifecycle,
132355
132155
  backfillTasks: () => backfillTasks,
132356
- backfillTerminalPipelineStage: () => backfillTerminalPipelineStage,
132357
132156
  backupGlobalSalt: () => backupGlobalSalt,
132358
132157
  batchParse: () => batchParse,
132359
132158
  blobAttachmentSchema: () => blobAttachmentSchema,
@@ -132779,14 +132578,12 @@ __export(internal_exports, {
132779
132578
  isLafsSuccess: () => isLafsSuccess,
132780
132579
  isNoChangeCode: () => isNoChangeCode,
132781
132580
  isOverloaded: () => isOverloaded,
132782
- isPipelineStageBackfillDone: () => isPipelineStageBackfillDone,
132783
132581
  isPipelineTransitionForward: () => isPipelineTransitionForward,
132784
132582
  isProjectInitialized: () => isProjectInitialized,
132785
132583
  isProviderHookEvent: () => isProviderHookEvent,
132786
132584
  isRecoverableCode: () => isRecoverableCode,
132787
132585
  isSuccessCode: () => isSuccessCode,
132788
132586
  isTelemetryEnabled: () => isTelemetryEnabled,
132789
- isTerminalPipelineStageBackfillDone: () => isTerminalPipelineStageBackfillDone,
132790
132587
  isTreeSitterAvailable: () => isTreeSitterAvailable,
132791
132588
  isValidStage: () => isValidStage,
132792
132589
  isValidStatus: () => isValidStatus,
@@ -133187,8 +132984,6 @@ var init_internal = __esm({
133187
132984
  init_create();
133188
132985
  init_diagnostics();
133189
132986
  init_retry2();
133190
- init_backfill_pipeline_stage();
133191
- init_backfill_terminal_pipeline_stage();
133192
132987
  init_chain_store();
133193
132988
  init_lifecycle2();
133194
132989
  init_ivtr_loop();
@@ -141596,10 +141391,10 @@ async function releaseShip(params2, projectRoot) {
141596
141391
  );
141597
141392
  const { getDb: getDb4 } = await Promise.resolve().then(() => (init_internal(), internal_exports));
141598
141393
  const { releaseManifests: releaseManifests2 } = await Promise.resolve().then(() => (init_internal(), internal_exports));
141599
- const { eq: eq22 } = await import("drizzle-orm");
141394
+ const { eq: eq20 } = await import("drizzle-orm");
141600
141395
  const normalizedVer = version2.startsWith("v") ? version2 : `v${version2}`;
141601
141396
  const db = await getDb4(cwd);
141602
- await db.update(releaseManifests2).set({ epicId }).where(eq22(releaseManifests2.version, normalizedVer)).run();
141397
+ await db.update(releaseManifests2).set({ epicId }).where(eq20(releaseManifests2.version, normalizedVer)).run();
141603
141398
  await generateReleaseChangelog(version2, () => loadTasks2(projectRoot), cwd);
141604
141399
  }
141605
141400
  logStep(0, 8, "Auto-prepare release record", true);
@@ -145868,12 +145663,12 @@ function scanForbiddenPhrases(filePath, lines) {
145868
145663
  }
145869
145664
  function countCanonicalDomains(typesFilePath) {
145870
145665
  const lines = readLines(typesFilePath);
145871
- let inArray10 = false;
145666
+ let inArray8 = false;
145872
145667
  let count5 = 0;
145873
145668
  for (const line2 of lines) {
145874
- if (!inArray10) {
145669
+ if (!inArray8) {
145875
145670
  if (line2.includes("CANONICAL_DOMAINS") && line2.includes("[")) {
145876
- inArray10 = true;
145671
+ inArray8 = true;
145877
145672
  }
145878
145673
  continue;
145879
145674
  }
@@ -168847,7 +168642,7 @@ var analyzeCommand3 = defineCommand({
168847
168642
  );
168848
168643
  }
168849
168644
  try {
168850
- const [{ getNexusDb: getNexusDb2, nexusSchema }, { runPipeline: runPipeline2 }, { getProjectRoot: getProjectRoot4 }, { eq: eq22 }] = await Promise.all([
168645
+ const [{ getNexusDb: getNexusDb2, nexusSchema }, { runPipeline: runPipeline2 }, { getProjectRoot: getProjectRoot4 }, { eq: eq20 }] = await Promise.all([
168851
168646
  import("@cleocode/core/store/nexus-sqlite"),
168852
168647
  import("@cleocode/nexus/pipeline"),
168853
168648
  Promise.resolve().then(() => (init_internal(), internal_exports)),
@@ -168864,11 +168659,11 @@ var analyzeCommand3 = defineCommand({
168864
168659
  process.stderr.write("[nexus] Clearing existing index for project...\n");
168865
168660
  }
168866
168661
  try {
168867
- db.delete(nexusSchema.nexusNodes).where(eq22(nexusSchema.nexusNodes.projectId, projectId)).run();
168662
+ db.delete(nexusSchema.nexusNodes).where(eq20(nexusSchema.nexusNodes.projectId, projectId)).run();
168868
168663
  } catch {
168869
168664
  }
168870
168665
  try {
168871
- db.delete(nexusSchema.nexusRelations).where(eq22(nexusSchema.nexusRelations.projectId, projectId)).run();
168666
+ db.delete(nexusSchema.nexusRelations).where(eq20(nexusSchema.nexusRelations.projectId, projectId)).run();
168872
168667
  } catch {
168873
168668
  }
168874
168669
  }
@@ -169525,7 +169320,7 @@ var projectsCleanCommand = defineCommand({
169525
169320
  const { getNexusDb: getNexusDb2 } = await import("@cleocode/core/store/nexus-sqlite");
169526
169321
  const { projectRegistry: regTable, nexusAuditLog: auditTable } = await import("@cleocode/core/store/nexus-schema");
169527
169322
  const { randomUUID: randomUUID16 } = await import("node:crypto");
169528
- const { inArray: inArray10 } = await import("drizzle-orm");
169323
+ const { inArray: inArray8 } = await import("drizzle-orm");
169529
169324
  const db = await getNexusDb2();
169530
169325
  const allRows = await db.select({
169531
169326
  projectId: regTable.projectId,
@@ -169635,7 +169430,7 @@ var projectsCleanCommand = defineCommand({
169635
169430
  }
169636
169431
  }
169637
169432
  const idsToDelete = matches.map((r) => r.projectId);
169638
- await db.delete(regTable).where(inArray10(regTable.projectId, idsToDelete));
169433
+ await db.delete(regTable).where(inArray8(regTable.projectId, idsToDelete));
169639
169434
  const remaining = totalCount - matchCount;
169640
169435
  try {
169641
169436
  await db.insert(auditTable).values({