@rulemetric/cli 0.7.41 → 0.7.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/dist/base-command.js +1 -1
  2. package/dist/{chunk-LWI5K6T4.js → chunk-2DXBC2JQ.js} +1 -1
  3. package/dist/{chunk-EDJMMKA5.js → chunk-3BZPEN5H.js} +1 -1
  4. package/dist/chunk-7G6T5C7J.js +1 -0
  5. package/dist/{chunk-3HZU6FNG.js → chunk-ATA4J4ZG.js} +1 -1
  6. package/dist/{chunk-C7YRLB37.js → chunk-DGH4FBMM.js} +1 -1
  7. package/dist/{chunk-QUDMK76I.js → chunk-KZZ2MUQQ.js} +1 -1
  8. package/dist/{chunk-X23L2MF6.js → chunk-NBTC5FNV.js} +1 -1
  9. package/dist/{chunk-OMD3JCGB.js → chunk-O56AZKJL.js} +1 -1
  10. package/dist/{chunk-JCXKWHZX.js → chunk-O7PSLZO6.js} +1 -1
  11. package/dist/chunk-PRKJFYVF.js +1 -0
  12. package/dist/{chunk-2J3IHWE2.js → chunk-RWF75MTD.js} +1 -1
  13. package/dist/{chunk-B22HYCBV.js → chunk-TU2AR6XO.js} +1 -1
  14. package/dist/commands/antigravity/backfill.js +1 -1
  15. package/dist/commands/auth/create-key.js +1 -1
  16. package/dist/commands/auth/login.js +1 -1
  17. package/dist/commands/auth/logout.js +1 -1
  18. package/dist/commands/auth/revoke-key.js +1 -1
  19. package/dist/commands/auth/signup.js +1 -1
  20. package/dist/commands/auth/status.js +1 -1
  21. package/dist/commands/capture/scope.js +1 -1
  22. package/dist/commands/catalog/index.js +1 -1
  23. package/dist/commands/catalog/recommend.js +1 -1
  24. package/dist/commands/convert.js +1 -1
  25. package/dist/commands/converters.js +1 -1
  26. package/dist/commands/crons/list.js +1 -1
  27. package/dist/commands/crons/run.js +1 -1
  28. package/dist/commands/dashboard.js +1 -1
  29. package/dist/commands/diagnostics.js +1 -1
  30. package/dist/commands/eval-targets/create.js +1 -1
  31. package/dist/commands/eval-targets/list.js +1 -1
  32. package/dist/commands/evals/agent.js +1 -1
  33. package/dist/commands/evals/auto-run.js +1 -1
  34. package/dist/commands/evals/benchmark.js +1 -1
  35. package/dist/commands/evals/compare.js +1 -1
  36. package/dist/commands/evals/create.js +1 -1
  37. package/dist/commands/evals/optimize-description.js +1 -1
  38. package/dist/commands/evals/optimize.js +1 -1
  39. package/dist/commands/evals/refine-cases.js +1 -1
  40. package/dist/commands/evals/run.js +1 -1
  41. package/dist/commands/evals/validate-judge.js +1 -1
  42. package/dist/commands/gateway/ensure.js +1 -1
  43. package/dist/commands/hooks/install.js +1 -1
  44. package/dist/commands/hooks/run.js +1 -1
  45. package/dist/commands/hooks/uninstall.js +1 -1
  46. package/dist/commands/import.js +1 -1
  47. package/dist/commands/instructions/create.js +1 -1
  48. package/dist/commands/instructions/delete.js +1 -1
  49. package/dist/commands/instructions/fork.js +1 -1
  50. package/dist/commands/instructions/get.js +1 -1
  51. package/dist/commands/instructions/list.js +1 -1
  52. package/dist/commands/instructions/promote.js +1 -1
  53. package/dist/commands/instructions/pull.js +1 -1
  54. package/dist/commands/instructions/restore.js +1 -0
  55. package/dist/commands/instructions/upstream.js +1 -1
  56. package/dist/commands/instructions/versions.js +1 -1
  57. package/dist/commands/launcher.js +1 -1
  58. package/dist/commands/local/down.js +1 -1
  59. package/dist/commands/local/up.js +1 -1
  60. package/dist/commands/org/current.js +1 -1
  61. package/dist/commands/org/list.js +1 -1
  62. package/dist/commands/org/switch.js +1 -1
  63. package/dist/commands/packs/add-instruction.js +1 -1
  64. package/dist/commands/packs/apply.js +1 -1
  65. package/dist/commands/packs/create.js +1 -1
  66. package/dist/commands/packs/fork.js +1 -1
  67. package/dist/commands/packs/get.js +1 -1
  68. package/dist/commands/packs/list.js +1 -1
  69. package/dist/commands/packs/remove-instruction.js +1 -1
  70. package/dist/commands/proxy/env.js +1 -1
  71. package/dist/commands/proxy/logs.js +1 -1
  72. package/dist/commands/proxy/restart.js +1 -1
  73. package/dist/commands/proxy/setup.js +1 -1
  74. package/dist/commands/proxy/start.js +1 -1
  75. package/dist/commands/proxy/status.js +1 -1
  76. package/dist/commands/proxy/stop.js +1 -1
  77. package/dist/commands/research/backfill.js +1 -1
  78. package/dist/commands/research/tail-transcript.js +1 -1
  79. package/dist/commands/service/install.js +1 -1
  80. package/dist/commands/service/status.js +1 -1
  81. package/dist/commands/service/uninstall.js +1 -1
  82. package/dist/commands/sessions/analyze.js +1 -1
  83. package/dist/commands/sessions/delete.js +1 -1
  84. package/dist/commands/sessions/end.js +1 -1
  85. package/dist/commands/sessions/import.js +1 -1
  86. package/dist/commands/sessions/list.js +1 -1
  87. package/dist/commands/sessions/start.js +1 -1
  88. package/dist/commands/setup.js +1 -1
  89. package/dist/commands/skills/export-approved.js +1 -1
  90. package/dist/commands/skills/install.js +1 -1
  91. package/dist/commands/skills/list.js +1 -1
  92. package/dist/commands/skills/publish.js +1 -1
  93. package/dist/commands/skills/search.js +1 -1
  94. package/dist/commands/skills/update.js +1 -1
  95. package/dist/commands/suggestions/accept.js +7 -5
  96. package/dist/commands/suggestions/dismiss.js +1 -1
  97. package/dist/commands/suggestions/list.js +3 -2
  98. package/dist/commands/suggestions/refresh.js +1 -1
  99. package/dist/dashboard/Dashboard.js +1 -1
  100. package/dist/dashboard/launcher/ActiveJobsList.js +1 -1
  101. package/dist/dashboard/launcher/LauncherOverlay.js +1 -1
  102. package/dist/dashboard/launcher/NewLaunchForm.js +1 -1
  103. package/dist/lib/agent-loop.js +1 -1
  104. package/dist/lib/handlers/cron-suggest-instructions.js +1 -1
  105. package/dist/lib/handlers/process-announcement.js +1 -1
  106. package/dist/lib/handlers/process-changelog.js +1 -1
  107. package/dist/lib/handlers/process-insights.js +1 -1
  108. package/dist/lib/handlers/process-memory-ab.js +1 -1
  109. package/dist/lib/handlers/process-run-cleanup.js +1 -1
  110. package/dist/lib/manual-tasks.js +1 -1
  111. package/oclif.manifest.json +41 -1
  112. package/package.json +7 -7
  113. package/dist/chunk-45DOTNQM.js +0 -1
  114. package/dist/chunk-6ME5OTS5.js +0 -1
@@ -1 +1 @@
1
- import{a}from"./chunk-LWI5K6T4.js";import"./chunk-IZTIYR5Q.js";import"./chunk-6VKQT2J3.js";import"./chunk-NIRD7ETU.js";import"./chunk-QY3UKLDE.js";import"./chunk-3AV3GTMP.js";import"./chunk-KLEF5D3A.js";import"./chunk-JZ5Z2BRO.js";import"./chunk-ZLLER3HP.js";export{a as BaseCommand};
1
+ import{a}from"./chunk-2DXBC2JQ.js";import"./chunk-IZTIYR5Q.js";import"./chunk-NIRD7ETU.js";import"./chunk-6VKQT2J3.js";import"./chunk-QY3UKLDE.js";import"./chunk-3AV3GTMP.js";import"./chunk-KLEF5D3A.js";import"./chunk-JZ5Z2BRO.js";import"./chunk-ZLLER3HP.js";export{a as BaseCommand};
@@ -1,4 +1,4 @@
1
- import{a as c,c as d}from"./chunk-IZTIYR5Q.js";import{d as u}from"./chunk-6VKQT2J3.js";import{a}from"./chunk-NIRD7ETU.js";import{a as n}from"./chunk-QY3UKLDE.js";import{b as i}from"./chunk-KLEF5D3A.js";import{g as r}from"./chunk-JZ5Z2BRO.js";import{a as s}from"./chunk-ZLLER3HP.js";import{Command as f,Flags as h}from"@oclif/core";function p(t){return t instanceof i?t.statusCode>=500||t.statusCode===408||t.statusCode===0:/fetch failed|ECONNREFUSED|ECONNRESET|ETIMEDOUT|EAI_AGAIN|bad gateway|timed out/i.test(t.message??"")}s(p,"isAvailabilityError");var m=class extends f{static{s(this,"BaseCommand")}static baseFlags={"api-url":h.string({description:"Override API base URL",env:"RULEMETRIC_API_URL",hidden:!0})};async init(){await super.init();let{flags:e}=await this.parse(this.constructor);e["api-url"]&&(process.env.RULEMETRIC_API_URL=e["api-url"]);let o=d(this.config.version);o&&!this.argv.includes("--quiet")&&!process.env.RULEMETRIC_QUIET&&process.stderr.write(`
1
+ import{a as c,c as d}from"./chunk-IZTIYR5Q.js";import{a}from"./chunk-NIRD7ETU.js";import{d as u}from"./chunk-6VKQT2J3.js";import{a as n}from"./chunk-QY3UKLDE.js";import{b as i}from"./chunk-KLEF5D3A.js";import{g as r}from"./chunk-JZ5Z2BRO.js";import{a as s}from"./chunk-ZLLER3HP.js";import{Command as f,Flags as h}from"@oclif/core";function p(t){return t instanceof i?t.statusCode>=500||t.statusCode===408||t.statusCode===0:/fetch failed|ECONNREFUSED|ECONNRESET|ETIMEDOUT|EAI_AGAIN|bad gateway|timed out/i.test(t.message??"")}s(p,"isAvailabilityError");var m=class extends f{static{s(this,"BaseCommand")}static baseFlags={"api-url":h.string({description:"Override API base URL",env:"RULEMETRIC_API_URL",hidden:!0})};async init(){await super.init();let{flags:e}=await this.parse(this.constructor);e["api-url"]&&(process.env.RULEMETRIC_API_URL=e["api-url"]);let o=d(this.config.version);o&&!this.argv.includes("--quiet")&&!process.env.RULEMETRIC_QUIET&&process.stderr.write(`
2
2
  ${o}
3
3
 
4
4
  `),c();try{await a()}catch{}}requireAuth(){r()||this.error("Not logged in. Run `rulemetric auth login` to authenticate."),n()}async catch(e){throw p(e)&&await u({command:this.id,statusCode:e instanceof i?e.statusCode:void 0,message:e.message,cliVersion:this.config.version}),e instanceof i&&(e.statusCode===401&&this.error("Session expired. Run `rulemetric auth login` to re-authenticate."),this.error(e.message)),(e.message?.includes("fetch failed")||e.message?.includes("ECONNREFUSED"))&&this.error("Could not connect to the API server. Is it running?"),e}};export{m as a};
@@ -1 +1 @@
1
- import{a as C}from"./chunk-N7TGRFVZ.js";import{f as c,i as f}from"./chunk-45DOTNQM.js";import{d as m,e as p}from"./chunk-5R5RGKOW.js";import{a as r}from"./chunk-ZLLER3HP.js";import*as a from"node:fs/promises";import*as g from"node:path";import{eq as b}from"drizzle-orm";async function v(e){let n=e;for(let t=0;t<50;t++){try{return await a.stat(g.join(n,"pnpm-workspace.yaml")),n}catch{}let i=g.dirname(n);if(i===n)return null;n=i}return null}r(v,"findRepoRoot");async function k(e){if(e)try{return await a.readFile(e,"utf-8")}catch{return null}let n=await v(process.cwd())??process.cwd(),t=g.join(n,"CHANGELOG.md");try{return await a.readFile(t,"utf-8")}catch{return null}}r(k,"readChangelog");var _="https://rulemetric.com";function D(e){let n=e.date??new Date().toISOString().slice(0,10),t=C({version:e.version,date:n,sections:e.sections,unsubscribeUrl:"{{unsubscribe_url}}",recipientName:"{{recipient_name}}",productUrl:_});return{version:e.version,releaseDate:n,subject:t.subject,htmlBody:t.html,textBody:t.text,sections:e.sections}}r(D,"renderRow");async function R(e={}){let n=e.db??f(),t=e.logger??{info:r(s=>console.log(s),"info"),warn:r(s=>console.warn(s),"warn")},i=await k(e.changelogPath);if(i===null)return t.info("[cron_check_changelog] CHANGELOG.md not found; nothing to do"),{createdCount:0,skippedCount:0};let y=m(i),h=p(y);if(h.length===0)return t.info("[cron_check_changelog] No announceable entries; nothing to do"),{createdCount:0,skippedCount:0};let d=0,l=0;for(let s of h){if((await n.select({id:c.id}).from(c).where(b(c.version,s.version)).limit(1)).length>0){l++;continue}let o=D(s);try{await n.insert(c).values({version:o.version,releaseDate:o.releaseDate,subject:o.subject,htmlBody:o.htmlBody,textBody:o.textBody,sections:o.sections,status:"draft"}),d++,t.info(`[cron_check_changelog] Created draft announcement for ${o.version}`)}catch(u){let w=u instanceof Error?u.message:String(u);if(/duplicate key|unique/i.test(w)){l++;continue}throw u}}return t.info(`[cron_check_changelog] Done: created ${d}, skipped ${l}`),{createdCount:d,skippedCount:l}}r(R,"processChangelog");export{R as a};
1
+ import{a as C}from"./chunk-N7TGRFVZ.js";import{f as c,i as f}from"./chunk-7G6T5C7J.js";import{d as m,e as p}from"./chunk-5R5RGKOW.js";import{a as r}from"./chunk-ZLLER3HP.js";import*as a from"node:fs/promises";import*as g from"node:path";import{eq as b}from"drizzle-orm";async function v(e){let n=e;for(let t=0;t<50;t++){try{return await a.stat(g.join(n,"pnpm-workspace.yaml")),n}catch{}let i=g.dirname(n);if(i===n)return null;n=i}return null}r(v,"findRepoRoot");async function k(e){if(e)try{return await a.readFile(e,"utf-8")}catch{return null}let n=await v(process.cwd())??process.cwd(),t=g.join(n,"CHANGELOG.md");try{return await a.readFile(t,"utf-8")}catch{return null}}r(k,"readChangelog");var _="https://rulemetric.com";function D(e){let n=e.date??new Date().toISOString().slice(0,10),t=C({version:e.version,date:n,sections:e.sections,unsubscribeUrl:"{{unsubscribe_url}}",recipientName:"{{recipient_name}}",productUrl:_});return{version:e.version,releaseDate:n,subject:t.subject,htmlBody:t.html,textBody:t.text,sections:e.sections}}r(D,"renderRow");async function R(e={}){let n=e.db??f(),t=e.logger??{info:r(s=>console.log(s),"info"),warn:r(s=>console.warn(s),"warn")},i=await k(e.changelogPath);if(i===null)return t.info("[cron_check_changelog] CHANGELOG.md not found; nothing to do"),{createdCount:0,skippedCount:0};let y=m(i),h=p(y);if(h.length===0)return t.info("[cron_check_changelog] No announceable entries; nothing to do"),{createdCount:0,skippedCount:0};let d=0,l=0;for(let s of h){if((await n.select({id:c.id}).from(c).where(b(c.version,s.version)).limit(1)).length>0){l++;continue}let o=D(s);try{await n.insert(c).values({version:o.version,releaseDate:o.releaseDate,subject:o.subject,htmlBody:o.htmlBody,textBody:o.textBody,sections:o.sections,status:"draft"}),d++,t.info(`[cron_check_changelog] Created draft announcement for ${o.version}`)}catch(u){let w=u instanceof Error?u.message:String(u);if(/duplicate key|unique/i.test(w)){l++;continue}throw u}}return t.info(`[cron_check_changelog] Done: created ${d}, skipped ${l}`),{createdCount:d,skippedCount:l}}r(R,"processChangelog");export{R as a};
@@ -0,0 +1 @@
1
+ import{a as p,c as Or}from"./chunk-ZLLER3HP.js";import{boolean as So,pgTable as qr,text as Ze,timestamp as Ct,uuid as Ko}from"drizzle-orm/pg-core";import{pgTable as Xe,text as re,timestamp as Re,jsonb as Eo,uuid as Y,primaryKey as bo}from"drizzle-orm/pg-core";var u=Xe("organizations",{id:Y("id").primaryKey().defaultRandom(),name:re("name").unique().notNull(),slug:re("slug").unique().notNull(),metadata:Eo("metadata"),createdAt:Re("created_at",{withTimezone:!0}).defaultNow(),updatedAt:Re("updated_at",{withTimezone:!0}).defaultNow()}),h=Xe("teams",{id:Y("id").primaryKey().defaultRandom(),orgId:Y("org_id").references(()=>u.id,{onDelete:"cascade"}),name:re("name").notNull(),slug:re("slug").notNull(),metadata:Eo("metadata"),createdAt:Re("created_at",{withTimezone:!0}).defaultNow()}),se=Xe("user_organizations",{userId:Y("user_id").notNull(),orgId:Y("org_id").references(()=>u.id,{onDelete:"cascade"}).notNull(),role:re("role").notNull().default("member"),createdAt:Re("created_at",{withTimezone:!0}).defaultNow()},e=>[bo({columns:[e.userId,e.orgId]})]),ie=Xe("user_teams",{userId:Y("user_id").notNull(),teamId:Y("team_id").references(()=>h.id,{onDelete:"cascade"}).notNull(),role:re("role").notNull().default("member"),createdAt:Re("created_at",{withTimezone:!0}).defaultNow()},e=>[bo({columns:[e.userId,e.teamId]})]);var o=qr("profiles",{id:Ko("id").primaryKey(),email:Ze("email"),displayName:Ze("display_name"),activeOrgId:Ko("active_org_id").references(()=>u.id,{onDelete:"set null"}),isSuperadmin:So("is_superadmin").notNull().default(!1),claudeCodePlan:Ze("claude_code_plan"),planSource:Ze("plan_source").notNull().default("detected"),setupCompletedAt:Ct("setup_completed_at",{withTimezone:!0}),liveSendSkipped:So("live_send_skipped").notNull().default(!1),createdAt:Ct("created_at",{withTimezone:!0}).defaultNow(),updatedAt:Ct("updated_at",{withTimezone:!0}).defaultNow()});import{pgTable as Hr,text as de,timestamp as Lt,jsonb as qo,uuid as nt,integer as Vr,boolean as Gr,index as Ut}from"drizzle-orm/pg-core";import{boolean as Lr,jsonb as Ur,pgTable as Mt,primaryKey as Co,text as Q,timestamp as ke,uniqueIndex as qt,uuid as W}from"drizzle-orm/pg-core";import{sql as Br}from"drizzle-orm";import{pgTable as Ot,text as x,timestamp as L,jsonb as et,uuid as D,integer as tt,boolean as Mr,uniqueIndex as ot,index as je}from"drizzle-orm/pg-core";var r=Ot("instructions",{id:D("id").primaryKey().defaultRandom(),name:x("name").notNull(),description:x("description").notNull(),type:x("type").notNull().default("instruction"),scope:x("scope").notNull(),scopeRef:D("scope_ref"),version:x("version").notNull(),content:x("content").notNull(),frontmatter:et("frontmatter").notNull(),slots:et("slots"),tags:x("tags").array(),compatibility:x("compatibility").array(),createdBy:D("created_by"),createdAt:L("created_at",{withTimezone:!0}).defaultNow(),updatedAt:L("updated_at",{withTimezone:!0}).defaultNow(),archived:Mr("archived").default(!1),archivedAt:L("archived_at",{withTimezone:!0}),archivedBy:D("archived_by"),forkedFromId:D("forked_from_id").references(()=>r.id,{onDelete:"set null"}),upstreamVersion:x("upstream_version"),badge:x("badge"),contentHash:x("content_hash"),contextIdentity:x("context_identity"),scanScore:tt("scan_score"),scanFindings:et("scan_findings"),popularityScore:tt("popularity_score"),sourceUpdatedAt:L("source_updated_at",{withTimezone:!0})},e=>[ot("instructions_name_scope_ref_idx").on(e.name,e.scope,e.scopeRef),je("idx_instructions_scope").on(e.scope,e.scopeRef),je("idx_instructions_created_by").on(e.createdBy),je("idx_instructions_context_identity").on(e.createdBy,e.contextIdentity),je("idx_instructions_public_recency").on(e.scope,e.sourceUpdatedAt.desc())]),Po=Ot("instruction_version_identities",{id:D("id").primaryKey().defaultRandom(),instructionId:D("instruction_id").notNull().references(()=>r.id,{onDelete:"cascade"}),contentHash:x("content_hash").notNull(),versionOrdinal:tt("version_ordinal").notNull(),content:x("content"),firstSeenAt:L("first_seen_at",{withTimezone:!0}).notNull().defaultNow(),lastSeenAt:L("last_seen_at",{withTimezone:!0}).notNull().defaultNow(),createdAt:L("created_at",{withTimezone:!0}).notNull().defaultNow()},e=>[ot("instruction_version_identities_hash_unique").on(e.instructionId,e.contentHash),ot("instruction_version_identities_ordinal_unique").on(e.instructionId,e.versionOrdinal),je("idx_ivi_instruction").on(e.instructionId)]),ae=Ot("instruction_versions",{id:D("id").primaryKey().defaultRandom(),instructionId:D("instruction_id").references(()=>r.id,{onDelete:"cascade"}),versionNumber:tt("version_number").notNull(),content:x("content").notNull(),frontmatter:et("frontmatter").notNull(),changeSummary:x("change_summary"),createdBy:D("created_by"),createdAt:L("created_at",{withTimezone:!0}).defaultNow()},e=>[ot("instruction_versions_instruction_version_idx").on(e.instructionId,e.versionNumber)]);var s=Mt("projects",{id:W("id").primaryKey().defaultRandom(),orgId:W("org_id").references(()=>u.id,{onDelete:"cascade"}),name:Q("name").notNull(),description:Q("description"),githubRepo:Q("github_repo"),gitRemoteUrl:Q("git_remote_url"),gitRootCommit:Q("git_root_commit"),gitRemoteAliases:Q("git_remote_aliases").array().notNull().default([]),metadata:Ur("metadata"),createdBy:W("created_by"),createdAt:ke("created_at",{withTimezone:!0}).defaultNow(),updatedAt:ke("updated_at",{withTimezone:!0}).defaultNow()},e=>[qt("projects_org_name_idx").on(e.orgId,e.name),qt("projects_git_remote_url_unique").on(e.gitRemoteUrl).where(Br`${e.gitRemoteUrl} IS NOT NULL`)]),U=Mt("project_instructions",{projectId:W("project_id").references(()=>s.id,{onDelete:"cascade"}).notNull(),instructionId:W("instruction_id").references(()=>r.id,{onDelete:"cascade"}).notNull(),addedAt:ke("added_at",{withTimezone:!0}).defaultNow(),addedBy:W("added_by")},e=>[Co({columns:[e.projectId,e.instructionId]})]),Oo=Mt("project_checkouts",{projectId:W("project_id").references(()=>s.id,{onDelete:"cascade"}).notNull(),path:Q("path").notNull(),isWorktree:Lr("is_worktree").notNull().default(!1),firstSeen:ke("first_seen",{withTimezone:!0}).notNull().defaultNow(),lastSeen:ke("last_seen",{withTimezone:!0}).notNull().defaultNow()},e=>[Co({columns:[e.projectId,e.path]}),qt("project_checkouts_path_unique").on(e.path)]);var g=Hr("agent_runs",{id:nt("id").primaryKey().defaultRandom(),userId:nt("user_id").notNull().references(()=>o.id,{onDelete:"cascade"}),orgId:nt("org_id").references(()=>u.id,{onDelete:"set null"}),projectId:nt("project_id").references(()=>s.id,{onDelete:"set null"}),projectPath:de("project_path"),gitRemote:de("git_remote"),baseBranch:de("base_branch"),title:de("title"),prompt:de("prompt"),toolSpec:qo("tool_spec").notNull().default([]),autoWorktree:Gr("auto_worktree").notNull().default(!0),status:de("status").notNull().default("pending"),sessionCount:Vr("session_count").notNull().default(0),metadata:qo("metadata").notNull().default({}),createdAt:Lt("created_at",{withTimezone:!0}).notNull().defaultNow(),updatedAt:Lt("updated_at",{withTimezone:!0}).notNull().defaultNow(),completedAt:Lt("completed_at",{withTimezone:!0})},e=>[Ut("idx_agent_runs_user").on(e.userId),Ut("idx_agent_runs_org_created").on(e.orgId,e.createdAt),Ut("idx_agent_runs_project").on(e.projectId)]);import{pgTable as Bt,text as I,timestamp as Ee,jsonb as X,uuid as E,integer as rt,uniqueIndex as Mo,index as R}from"drizzle-orm/pg-core";var d=Bt("sessions",{id:E("id").primaryKey().defaultRandom(),userId:E("user_id").notNull().references(()=>o.id,{onDelete:"cascade"}),externalSessionId:I("external_session_id"),projectId:E("project_id").references(()=>s.id,{onDelete:"set null"}),orgId:E("org_id").references(()=>u.id,{onDelete:"set null"}),tool:I("tool").notNull(),projectPath:I("project_path"),gitBranch:I("git_branch"),startedAt:Ee("started_at",{withTimezone:!0}).notNull(),endedAt:Ee("ended_at",{withTimezone:!0}),eventCount:rt("event_count").default(0),tokenUsage:X("token_usage"),analysis:X("analysis"),analyzedAt:Ee("analyzed_at",{withTimezone:!0}),analyzedEventCount:rt("analyzed_event_count"),analyzedTurnCount:rt("analyzed_turn_count"),metadata:X("metadata").default({}),origin:I("origin").notNull().default("unknown"),runId:E("run_id").references(()=>g.id,{onDelete:"set null"}),model:I("model"),harnessVersion:I("harness_version"),createdAt:Ee("created_at",{withTimezone:!0}).defaultNow()},e=>[R("idx_sessions_user").on(e.userId),R("idx_sessions_tool").on(e.tool),R("idx_sessions_started_at").on(e.startedAt),R("idx_sessions_project").on(e.projectId),R("idx_sessions_org_started_at").on(e.orgId,e.startedAt),R("idx_sessions_run").on(e.runId),Mo("idx_sessions_user_external").on(e.userId,e.externalSessionId)]),ue=Bt("session_events",{id:E("id").primaryKey().defaultRandom(),sessionId:E("session_id").notNull().references(()=>d.id,{onDelete:"cascade"}),sequence:rt("sequence").notNull(),eventType:I("event_type").notNull(),content:I("content"),toolName:I("tool_name"),toolInput:X("tool_input"),toolOutput:X("tool_output"),tokenUsage:X("token_usage"),model:I("model"),timestamp:Ee("timestamp",{withTimezone:!0}).notNull(),metadata:X("metadata").default({})},e=>[Mo("session_events_session_sequence_idx").on(e.sessionId,e.sequence),R("idx_session_events_session_id").on(e.sessionId),R("idx_session_events_event_type").on(e.eventType),R("idx_session_events_model").on(e.model)]),B=Bt("session_instructions",{sessionId:E("session_id").notNull().references(()=>d.id,{onDelete:"cascade"}),instructionId:E("instruction_id").notNull().references(()=>r.id,{onDelete:"cascade"}),linkMethod:I("link_method").notNull(),contentHash:I("content_hash")},e=>[R("idx_session_instructions_instruction_id").on(e.instructionId)]);import{pgTable as Fr,text as le,timestamp as Ht,uuid as be,integer as Lo,index as st}from"drizzle-orm/pg-core";var T=Fr("memories",{id:be("id").primaryKey().defaultRandom(),userId:be("user_id").notNull().references(()=>o.id,{onDelete:"cascade"}),orgId:be("org_id"),projectId:be("project_id").references(()=>s.id,{onDelete:"set null"}),version:Lo("version").notNull().default(1),parentId:be("parent_id").references(()=>T.id,{onDelete:"set null"}),kind:le("kind").notNull(),title:le("title").notNull(),body:le("body").notNull(),source:le("source").notNull(),status:le("status").notNull().default("active"),trustClass:le("trust_class"),trustVersion:Lo("trust_version"),trustComputedAt:Ht("trust_computed_at",{withTimezone:!0}),createdAt:Ht("created_at",{withTimezone:!0}).notNull().defaultNow(),updatedAt:Ht("updated_at",{withTimezone:!0}).notNull().defaultNow()},e=>[st("idx_memories_user").on(e.userId),st("idx_memories_project").on(e.projectId),st("idx_memories_parent").on(e.parentId),st("idx_memories_user_status").on(e.userId,e.status)]);import{pgTable as Jr,text as Se,timestamp as Vt,uuid as Gt,integer as Uo,jsonb as $r,index as Bo}from"drizzle-orm/pg-core";var Ho=Jr("memory_experiments",{id:Gt("id").primaryKey().defaultRandom(),memoryId:Gt("memory_id").notNull().references(()=>T.id,{onDelete:"cascade"}),userId:Gt("user_id").notNull().references(()=>o.id,{onDelete:"cascade"}),memoryVersion:Uo("memory_version").notNull().default(1),taskPrompt:Se("task_prompt").notNull(),expectations:Se("expectations").array().notNull().default([]),trials:Uo("trials").notNull().default(10),model:Se("model"),status:Se("status").notNull().default("pending"),result:$r("result").$type(),error:Se("error"),createdAt:Vt("created_at",{withTimezone:!0}).notNull().defaultNow(),startedAt:Vt("started_at",{withTimezone:!0}),completedAt:Vt("completed_at",{withTimezone:!0})},e=>[Bo("idx_memory_experiments_memory").on(e.memoryId),Bo("idx_memory_experiments_user").on(e.userId)]);import{boolean as Yr,date as Qr,index as Ft,integer as Wr,jsonb as Xr,pgTable as Jt,text as A,timestamp as H,uniqueIndex as Zr,uuid as ce}from"drizzle-orm/pg-core";var Vo=Jt("announcements",{id:ce("id").primaryKey().defaultRandom(),version:A("version").notNull().unique(),releaseDate:Qr("release_date").notNull(),subject:A("subject").notNull(),htmlBody:A("html_body").notNull(),textBody:A("text_body").notNull(),sections:Xr("sections").notNull().default({}),status:A("status").notNull().default("draft"),recipientCount:Wr("recipient_count"),sentAt:H("sent_at",{withTimezone:!0}),sentBy:ce("sent_by"),error:A("error"),createdAt:H("created_at",{withTimezone:!0}).notNull().defaultNow(),updatedAt:H("updated_at",{withTimezone:!0}).notNull().defaultNow()},e=>[Ft("idx_announcements_status").on(e.status),Ft("idx_announcements_created").on(e.createdAt)]),Go=Jt("announcement_deliveries",{id:ce("id").primaryKey().defaultRandom(),announcementId:ce("announcement_id").notNull(),userId:ce("user_id").notNull(),email:A("email").notNull(),status:A("status").notNull().default("pending"),providerId:A("provider_id"),error:A("error"),sentAt:H("sent_at",{withTimezone:!0}),createdAt:H("created_at",{withTimezone:!0}).notNull().defaultNow()},e=>[Zr("uniq_announcement_deliveries_announcement_user").on(e.announcementId,e.userId),Ft("idx_announcement_deliveries_user").on(e.userId,e.createdAt)]),Fo=Jt("notification_preferences",{userId:ce("user_id").primaryKey(),productAnnouncements:Yr("product_announcements").notNull().default(!0),unsubscribeToken:A("unsubscribe_token").notNull().unique(),unsubscribedAt:H("unsubscribed_at",{withTimezone:!0}),createdAt:H("created_at",{withTimezone:!0}).notNull().defaultNow(),updatedAt:H("updated_at",{withTimezone:!0}).notNull().defaultNow()});import{pgTable as es,text as $t,timestamp as it,uuid as at,index as Jo}from"drizzle-orm/pg-core";var b=es("org_invitations",{id:at("id").primaryKey().defaultRandom(),orgId:at("org_id").notNull().references(()=>u.id,{onDelete:"cascade"}),email:$t("email").notNull(),role:$t("role").notNull().default("member"),teamId:at("team_id").references(()=>h.id,{onDelete:"set null"}),invitedBy:at("invited_by").notNull().references(()=>o.id,{onDelete:"cascade"}),token:$t("token").notNull().unique(),expiresAt:it("expires_at",{withTimezone:!0}).notNull(),acceptedAt:it("accepted_at",{withTimezone:!0}),revokedAt:it("revoked_at",{withTimezone:!0}),createdAt:it("created_at",{withTimezone:!0}).notNull().defaultNow()},e=>[Jo("idx_org_invitations_token").on(e.token),Jo("idx_org_invitations_org").on(e.orgId)]);import{pgTable as ts,text as os,timestamp as ns,jsonb as rs,uuid as Yt,index as $o}from"drizzle-orm/pg-core";var _e=ts("instruction_events",{id:Yt("id").primaryKey().defaultRandom(),instructionId:Yt("instruction_id").notNull().references(()=>r.id,{onDelete:"cascade"}),eventType:os("event_type").notNull(),actorId:Yt("actor_id").notNull(),metadata:rs("metadata"),createdAt:ns("created_at",{withTimezone:!0}).defaultNow()},e=>[$o("idx_instruction_events_instruction").on(e.instructionId),$o("idx_instruction_events_type").on(e.eventType)]);import{pgTable as Yo,text as dt,timestamp as Qo,uuid as j,integer as Wo,index as me,unique as ss}from"drizzle-orm/pg-core";var S=Yo("treatment_assignments",{id:j("id").primaryKey().defaultRandom(),userId:j("user_id").notNull().references(()=>o.id,{onDelete:"cascade"}),treatmentType:dt("treatment_type").notNull(),treatmentId:j("treatment_id").notNull(),treatmentVersion:Wo("treatment_version").notNull().default(1),projectId:j("project_id").references(()=>s.id,{onDelete:"set null"}),assignedBy:j("assigned_by").references(()=>o.id,{onDelete:"set null"}),method:dt("method").notNull(),assignedAt:Qo("assigned_at",{withTimezone:!0}).notNull().defaultNow()},e=>[me("idx_treatment_assignments_user").on(e.userId),me("idx_treatment_assignments_treatment").on(e.treatmentType,e.treatmentId),me("idx_treatment_assignments_project").on(e.projectId)]),K=Yo("treatment_exposures",{id:j("id").primaryKey().defaultRandom(),sessionId:j("session_id").notNull().references(()=>d.id,{onDelete:"cascade"}),userId:j("user_id").notNull().references(()=>o.id,{onDelete:"cascade"}),treatmentType:dt("treatment_type").notNull(),treatmentId:j("treatment_id").notNull(),treatmentVersion:Wo("treatment_version").notNull().default(1),assignmentId:j("assignment_id").references(()=>S.id,{onDelete:"set null"}),method:dt("method").notNull(),exposedAt:Qo("exposed_at",{withTimezone:!0}).notNull().defaultNow()},e=>[ss("treatment_exposures_unique").on(e.sessionId,e.treatmentType,e.treatmentId,e.treatmentVersion),me("idx_treatment_exposures_treatment").on(e.treatmentType,e.treatmentId),me("idx_treatment_exposures_user").on(e.userId),me("idx_treatment_exposures_session").on(e.sessionId)]);import{pgTable as is,text as Qt,timestamp as as,uuid as ut,integer as ds,index as Xo,uniqueIndex as us}from"drizzle-orm/pg-core";var Zo=is("pending_treatment_exposures",{id:ut("id").primaryKey().defaultRandom(),userId:ut("user_id").notNull().references(()=>o.id,{onDelete:"cascade"}),externalSessionId:Qt("external_session_id").notNull(),treatmentType:Qt("treatment_type").notNull(),treatmentId:ut("treatment_id").notNull(),treatmentVersion:ds("treatment_version").notNull().default(1),method:Qt("method").notNull().default("injected"),projectId:ut("project_id").references(()=>s.id,{onDelete:"set null"}),createdAt:as("created_at",{withTimezone:!0}).notNull().defaultNow()},e=>[us("pending_treatment_exposures_unique").on(e.externalSessionId,e.treatmentType,e.treatmentId,e.treatmentVersion),Xo("idx_pending_treatment_exposures_ext").on(e.externalSessionId),Xo("idx_pending_treatment_exposures_user").on(e.userId)]);import{pgTable as ls,text as pe,timestamp as Wt,uuid as Xt,jsonb as cs,uniqueIndex as _s,index as en}from"drizzle-orm/pg-core";var lt=ls("session_terminal_targets",{id:Xt("id").primaryKey().defaultRandom(),userId:Xt("user_id").notNull().references(()=>o.id,{onDelete:"cascade"}),sessionId:Xt("session_id").references(()=>d.id,{onDelete:"set null"}),externalSessionId:pe("external_session_id"),kind:pe("kind").notNull(),target:pe("target").notNull(),status:pe("status").notNull().default("active"),attachCommand:pe("attach_command").notNull(),projectPath:pe("project_path"),metadata:cs("metadata").notNull().default({}),lastSeenAt:Wt("last_seen_at",{withTimezone:!0}).defaultNow(),createdAt:Wt("created_at",{withTimezone:!0}).defaultNow(),updatedAt:Wt("updated_at",{withTimezone:!0}).defaultNow()},e=>[_s("idx_session_terminal_targets_user_target").on(e.userId,e.target),en("idx_session_terminal_targets_session").on(e.sessionId),en("idx_session_terminal_targets_user_status").on(e.userId,e.status)]);import{boolean as ms,index as ct,jsonb as tn,pgTable as ps,text as Z,timestamp as Ke,uuid as _t,integer as on}from"drizzle-orm/pg-core";var nn=ps("session_send_jobs",{id:_t("id").primaryKey().defaultRandom(),userId:_t("user_id").notNull(),sessionId:_t("session_id").notNull().references(()=>d.id,{onDelete:"cascade"}),terminalTargetId:_t("terminal_target_id").references(()=>lt.id,{onDelete:"set null"}),target:Z("target").notNull(),message:Z("message").notNull(),submit:ms("submit").notNull().default(!0),delivery:Z("delivery").notNull().default("live"),status:Z("status").notNull().default("pending"),result:tn("result"),error:Z("error"),attempts:on("attempts").notNull().default(0),taskKind:Z("task_kind"),payload:tn("payload"),claimedBy:Z("claimed_by"),claimedAt:Ke("claimed_at",{withTimezone:!0}),leaseExpiresAt:Ke("lease_expires_at",{withTimezone:!0}),leaseRecoveries:on("lease_recoveries").notNull().default(0),createdAt:Ke("created_at",{withTimezone:!0}).defaultNow(),updatedAt:Ke("updated_at",{withTimezone:!0}).defaultNow(),completedAt:Ke("completed_at",{withTimezone:!0})},e=>[ct("idx_session_send_jobs_user").on(e.userId),ct("idx_session_send_jobs_session").on(e.sessionId),ct("idx_session_send_jobs_status").on(e.status),ct("idx_session_send_jobs_pending").on(e.userId,e.status)]);import{pgTable as sn,text as ee,timestamp as mt,jsonb as an,uuid as V,integer as fs,boolean as xs,uniqueIndex as Ns,index as rn,primaryKey as gs}from"drizzle-orm/pg-core";var z=sn("packs",{id:V("id").primaryKey().defaultRandom(),name:ee("name").notNull(),description:ee("description").notNull(),scope:ee("scope").notNull(),scopeRef:V("scope_ref"),version:ee("version").notNull().default("1.0.0"),tags:ee("tags").array(),badge:ee("badge"),metadata:an("metadata"),createdBy:V("created_by"),createdAt:mt("created_at",{withTimezone:!0}).defaultNow(),updatedAt:mt("updated_at",{withTimezone:!0}).defaultNow(),archived:xs("archived").default(!1),archivedAt:mt("archived_at",{withTimezone:!0}),archivedBy:V("archived_by"),forkedFromId:V("forked_from_id").references(()=>z.id,{onDelete:"set null"}),upstreamVersion:ee("upstream_version")},e=>[Ns("packs_name_scope_ref_idx").on(e.name,e.scope,e.scopeRef),rn("idx_packs_scope").on(e.scope,e.scopeRef),rn("idx_packs_created_by").on(e.createdBy)]),G=sn("pack_instructions",{packId:V("pack_id").references(()=>z.id,{onDelete:"cascade"}).notNull(),instructionId:V("instruction_id").references(()=>r.id,{onDelete:"cascade"}).notNull(),position:fs("position").notNull().default(0),slotOverrides:an("slot_overrides"),addedAt:mt("added_at",{withTimezone:!0}).defaultNow(),addedBy:V("added_by")},e=>[gs({columns:[e.packId,e.instructionId]})]);import{pgTable as vs,text as Zt,timestamp as hs,jsonb as Is,uuid as eo,index as fe}from"drizzle-orm/pg-core";var xe=vs("instruction_usage_events",{id:eo("id").primaryKey().defaultRandom(),instructionId:eo("instruction_id").references(()=>r.id,{onDelete:"set null"}),userId:eo("user_id").notNull(),surface:Zt("surface").notNull(),action:Zt("action").notNull(),metadata:Is("metadata"),traceId:Zt("trace_id"),createdAt:hs("created_at",{withTimezone:!0}).defaultNow()},e=>[fe("idx_usage_events_instruction").on(e.instructionId),fe("idx_usage_events_user").on(e.userId),fe("idx_usage_events_surface").on(e.surface),fe("idx_usage_events_action").on(e.action),fe("idx_usage_events_created_at").on(e.createdAt),fe("idx_usage_events_user_created").on(e.userId,e.createdAt)]);import{pgTable as ys,text as pt,timestamp as dn,jsonb as Ts,uuid as un,index as to}from"drizzle-orm/pg-core";var ln=ys("worker_connections",{id:un("id").primaryKey().defaultRandom(),userId:un("user_id").notNull(),workerType:pt("worker_type").notNull().default("mcp"),clientName:pt("client_name").notNull(),clientVersion:pt("client_version"),workerVersion:pt("worker_version"),lastHeartbeat:dn("last_heartbeat",{withTimezone:!0}).notNull().defaultNow(),connectedAt:dn("connected_at",{withTimezone:!0}).notNull().defaultNow(),metadata:Ts("metadata")},e=>[to("idx_worker_connections_user").on(e.userId),to("idx_worker_connections_heartbeat").on(e.userId,e.lastHeartbeat),to("idx_worker_connections_type").on(e.userId,e.workerType)]);import{pgTable as ws,text as ft,timestamp as As,jsonb as zs,uuid as cn,index as _n}from"drizzle-orm/pg-core";var mn=ws("cli_setup_events",{id:cn("id").primaryKey().defaultRandom(),userId:cn("user_id").notNull(),deviceId:ft("device_id").notNull(),event:ft("event").notNull(),cliVersion:ft("cli_version"),os:ft("os"),props:zs("props").notNull().default({}),createdAt:As("created_at",{withTimezone:!0}).notNull().defaultNow()},e=>[_n("idx_cli_setup_events_user").on(e.userId,e.createdAt),_n("idx_cli_setup_events_device").on(e.deviceId,e.createdAt)]);import{pgTable as Ds,text as te,integer as Rs,boolean as js,timestamp as ks,jsonb as Es,uuid as bs,index as pn}from"drizzle-orm/pg-core";var fn=Ds("cli_error_events",{id:bs("id").primaryKey().defaultRandom(),deviceId:te("device_id"),event:te("event").notNull(),command:te("command"),statusCode:Rs("status_code"),message:te("message"),cliVersion:te("cli_version"),os:te("os"),nodeVersion:te("node_version"),proxied:js("proxied"),props:Es("props").notNull().default({}),createdAt:ks("created_at",{withTimezone:!0}).notNull().defaultNow()},e=>[pn("idx_cli_error_events_created").on(e.createdAt),pn("idx_cli_error_events_device").on(e.deviceId,e.createdAt)]);import{sql as Ss}from"drizzle-orm";import{pgTable as oe,text as _,timestamp as v,jsonb as w,uuid as c,integer as P,boolean as Pe,index as N,unique as xn}from"drizzle-orm/pg-core";var n=oe("eval_targets",{id:c("id").primaryKey().defaultRandom(),userId:c("user_id").notNull(),name:_("name").notNull(),type:_("type").notNull(),content:_("content").notNull(),description:_("description").notNull().default(""),metadata:w("metadata").notNull().default({}),version:P("version").notNull().default(1),parentId:c("parent_id").references(()=>n.id,{onDelete:"set null"}),createdAt:v("created_at",{withTimezone:!0}).defaultNow(),updatedAt:v("updated_at",{withTimezone:!0}).defaultNow()},e=>[N("eval_targets_name_user_idx").on(e.name,e.userId),N("idx_eval_targets_user").on(e.userId),N("idx_eval_targets_type").on(e.type),N("idx_eval_targets_parent").on(e.parentId)]),C=oe("evals",{id:c("id").primaryKey().defaultRandom(),evalTargetId:c("eval_target_id").notNull().references(()=>n.id,{onDelete:"cascade"}),name:_("name").notNull(),prompt:_("prompt").notNull(),expectedOutput:_("expected_output").notNull().default(""),files:w("files").notNull().default([]),expectations:w("expectations").notNull().default([]),retiredAt:v("retired_at",{withTimezone:!0}),retiredReason:_("retired_reason"),createdAt:v("created_at",{withTimezone:!0}).defaultNow(),updatedAt:v("updated_at",{withTimezone:!0}).defaultNow(),contentUpdatedAt:v("content_updated_at",{withTimezone:!0}).notNull().defaultNow()},e=>[N("idx_evals_target").on(e.evalTargetId),N("idx_evals_target_active").on(e.evalTargetId).where(Ss`${e.retiredAt} IS NULL`)]),k=oe("eval_runs",{id:c("id").primaryKey().defaultRandom(),jobId:c("job_id"),evalId:c("eval_id").notNull().references(()=>C.id,{onDelete:"cascade"}),evalTargetId:c("eval_target_id").notNull().references(()=>n.id,{onDelete:"cascade"}),evalTargetVersion:P("eval_target_version").notNull(),configuration:_("configuration").notNull(),runNumber:P("run_number").notNull().default(1),iteration:P("iteration").notNull().default(1),status:_("status").notNull().default("completed"),outputs:w("outputs").notNull().default({}),timing:w("timing").notNull().default({}),grading:w("grading").notNull().default({}),comparison:w("comparison"),createdAt:v("created_at",{withTimezone:!0}).defaultNow()},e=>[N("idx_eval_runs_eval").on(e.evalId),N("idx_eval_runs_target").on(e.evalTargetId),N("idx_eval_runs_iteration").on(e.evalTargetId,e.iteration)]),Nn=oe("eval_comparisons",{id:c("id").primaryKey().defaultRandom(),userId:c("user_id").notNull(),targetAId:c("target_a_id").notNull().references(()=>n.id,{onDelete:"cascade"}),targetBId:c("target_b_id").notNull().references(()=>n.id,{onDelete:"cascade"}),targetAVersion:P("target_a_version").notNull(),targetBVersion:P("target_b_version").notNull(),isSwapped:Pe("is_swapped").notNull().default(!1),winnerTargetId:c("winner_target_id").references(()=>n.id,{onDelete:"set null"}),perEval:w("per_eval").notNull().default([]),overall:w("overall").notNull().default({}),rawOutput:_("raw_output"),model:_("model"),status:_("status").notNull().default("completed"),createdAt:v("created_at",{withTimezone:!0}).defaultNow()},e=>[N("idx_eval_comparisons_target_a").on(e.targetAId),N("idx_eval_comparisons_target_b").on(e.targetBId),N("idx_eval_comparisons_user").on(e.userId)]),gn=oe("eval_grade_annotations",{id:c("id").primaryKey().defaultRandom(),userId:c("user_id").notNull(),evalRunId:c("eval_run_id").notNull().references(()=>k.id,{onDelete:"cascade"}),evalTargetId:c("eval_target_id").notNull().references(()=>n.id,{onDelete:"cascade"}),expectationIndex:P("expectation_index").notNull(),expectationText:_("expectation_text").notNull(),judgePassed:Pe("judge_passed").notNull(),judgeMethod:_("judge_method").notNull(),judgeModel:_("judge_model"),verdict:_("verdict").notNull(),flag:_("flag"),note:_("note"),createdAt:v("created_at",{withTimezone:!0}).defaultNow(),updatedAt:v("updated_at",{withTimezone:!0}).defaultNow()},e=>[N("idx_eval_grade_annotations_target").on(e.evalTargetId),N("idx_eval_grade_annotations_run").on(e.evalRunId),xn("eval_grade_annotations_eval_run_id_expectation_index_key").on(e.evalRunId,e.expectationIndex)]),vn=oe("judge_reviewer_verdicts",{id:c("id").primaryKey().defaultRandom(),userId:c("user_id").notNull(),evalTargetId:c("eval_target_id").notNull().references(()=>n.id,{onDelete:"cascade"}),evalRunId:c("eval_run_id").notNull().references(()=>k.id,{onDelete:"cascade"}),expectationIndex:P("expectation_index").notNull(),expectationText:_("expectation_text").notNull(),judgePassed:Pe("judge_passed").notNull(),humanPassed:Pe("human_passed").notNull(),reviewerEngine:_("reviewer_engine").notNull(),reviewerModel:_("reviewer_model").notNull(),reviewerPassed:Pe("reviewer_passed").notNull(),resolvedAt:v("resolved_at",{withTimezone:!0}),resolution:_("resolution"),createdAt:v("created_at",{withTimezone:!0}).defaultNow(),updatedAt:v("updated_at",{withTimezone:!0}).defaultNow()},e=>[N("idx_jrv_target").on(e.evalTargetId),xn("judge_reviewer_verdicts_eval_run_id_expectation_index_review_key").on(e.evalRunId,e.expectationIndex,e.reviewerModel)]),Ne=oe("benchmarks",{id:c("id").primaryKey().defaultRandom(),evalTargetId:c("eval_target_id").notNull().references(()=>n.id,{onDelete:"cascade"}),iteration:P("iteration").notNull().default(1),runSummary:w("run_summary").notNull().default({}),notes:w("notes").notNull().default([]),feedback:w("feedback"),createdAt:v("created_at",{withTimezone:!0}).defaultNow()},e=>[N("idx_benchmarks_target").on(e.evalTargetId)]);import{sql as oo}from"drizzle-orm";import{pgTable as Ks,text as O,timestamp as Ps,jsonb as xt,uuid as Nt,boolean as Cs,index as Ce,uniqueIndex as Os}from"drizzle-orm/pg-core";var hn=Ks("instruction_promotions",{id:Nt("id").primaryKey().defaultRandom(),userId:Nt("user_id").notNull(),evalTargetId:Nt("eval_target_id").notNull().references(()=>n.id,{onDelete:"cascade"}),instructionId:Nt("instruction_id").references(()=>r.id,{onDelete:"set null"}),fromContentHash:O("from_content_hash").notNull(),toContentHash:O("to_content_hash").notNull(),fromContent:O("from_content").notNull(),toContent:O("to_content").notNull(),proposalSource:O("proposal_source").notNull(),proposalRationale:O("proposal_rationale").notNull().default(""),decision:O("decision").notNull(),applied:Cs("applied").notNull().default(!1),refusals:xt("refusals").notNull().default([]),rationale:O("rationale").notNull().default(""),effectClass:O("effect_class").notNull(),verdict:xt("verdict").notNull().default({}),gates:xt("gates").notNull().default({}),touchedSections:xt("touched_sections").notNull().default([]),createdAt:Ps("created_at",{withTimezone:!0}).notNull().defaultNow()},e=>[Ce("idx_instruction_promotions_budget").on(e.evalTargetId,e.createdAt.desc()).where(oo`${e.applied}`),Ce("idx_instruction_promotions_target").on(e.evalTargetId,e.createdAt.desc()),Ce("idx_instruction_promotions_user").on(e.userId,e.createdAt.desc()),Ce("idx_instruction_promotions_to_hash").on(e.toContentHash),Os("uq_instruction_promotions_applied").on(e.evalTargetId,e.fromContentHash,e.toContentHash).where(oo`${e.applied}`),Ce("idx_instruction_promotions_applied_hash").on(e.toContentHash,e.createdAt.desc()).where(oo`${e.applied}`)]);import{pgTable as yn,text as no,timestamp as ro,jsonb as Tn,uuid as ge,integer as Oe,index as gt,real as In}from"drizzle-orm/pg-core";var ve=yn("trigger_evals",{id:ge("id").primaryKey().defaultRandom(),evalTargetId:ge("eval_target_id").notNull().references(()=>n.id,{onDelete:"cascade"}),userId:ge("user_id").notNull(),queries:Tn("queries").notNull().default([]),status:no("status").notNull().default("pending_review"),trainIndices:Oe("train_indices").array().default([]),testIndices:Oe("test_indices").array().default([]),createdAt:ro("created_at",{withTimezone:!0}).defaultNow(),updatedAt:ro("updated_at",{withTimezone:!0}).defaultNow()},e=>[gt("idx_trigger_evals_target").on(e.evalTargetId),gt("idx_trigger_evals_user").on(e.userId)]),he=yn("optimization_runs",{id:ge("id").primaryKey().defaultRandom(),evalTargetId:ge("eval_target_id").notNull().references(()=>n.id,{onDelete:"cascade"}),userId:ge("user_id").notNull(),type:no("type").notNull(),iteration:Oe("iteration").notNull(),inputVersion:Oe("input_version").notNull(),outputVersion:Oe("output_version"),trainScore:In("train_score"),testScore:In("test_score"),analysis:Tn("analysis").notNull().default({}),status:no("status").notNull().default("running"),createdAt:ro("created_at",{withTimezone:!0}).defaultNow()},e=>[gt("idx_optimization_runs_target").on(e.evalTargetId),gt("idx_optimization_runs_user").on(e.userId)]);import{pgTable as qs,text as F,timestamp as Ms,jsonb as qe,uuid as so,integer as io,real as Ls,index as Me,uniqueIndex as wn}from"drizzle-orm/pg-core";var J=qs("context_snapshots",{id:so("id").primaryKey().defaultRandom(),sessionId:so("session_id").references(()=>d.id,{onDelete:"cascade"}),userId:so("user_id").notNull().references(()=>o.id,{onDelete:"cascade"}),sequence:io("sequence").notNull().default(0),provider:F("provider").notNull(),model:F("model").notNull(),systemPrompt:F("system_prompt").notNull(),injectedInstructions:qe("injected_instructions").notNull().default([]),messagesSummary:qe("messages_summary").notNull(),tools:qe("tools").notNull().default([]),systemHash:F("system_hash").notNull(),requestHash:F("request_hash").notNull().default(""),toolsHash:F("tools_hash"),injectedHash:F("injected_hash"),messagesDelta:qe("messages_delta").default([]),messagesDeltaRef:F("messages_delta_ref"),maxTokens:io("max_tokens"),temperature:Ls("temperature"),estimatedTokens:io("estimated_tokens"),capturedAt:Ms("captured_at",{withTimezone:!0}).notNull().defaultNow(),metadata:qe("metadata").default({})},e=>[Me("idx_context_snapshots_session").on(e.sessionId),Me("idx_context_snapshots_user").on(e.userId),Me("idx_context_snapshots_hash").on(e.systemHash),Me("idx_context_snapshots_request_hash").on(e.requestHash),wn("idx_snapshots_session_request").on(e.sessionId,e.requestHash),wn("idx_snapshots_session_sequence").on(e.sessionId,e.sequence),Me("idx_context_snapshots_user_session_captured").on(e.userId,e.sessionId,e.capturedAt.desc())]);import{pgTable as Us,text as An,timestamp as Bs,jsonb as Hs,integer as Vs,index as Gs}from"drizzle-orm/pg-core";var zn=Us("content_blobs",{hash:An("hash").primaryKey(),contentType:An("content_type").notNull(),content:Hs("content").notNull(),sizeBytes:Vs("size_bytes").notNull().default(0),createdAt:Bs("created_at",{withTimezone:!0}).defaultNow()},e=>[Gs("idx_content_blobs_type").on(e.contentType)]);import{pgTable as Fs,text as vt,timestamp as Le,jsonb as ht,uuid as ao,index as It,integer as Dn}from"drizzle-orm/pg-core";var Ie=Fs("eval_jobs",{id:ao("id").primaryKey().defaultRandom(),userId:ao("user_id").notNull(),evalTargetId:ao("eval_target_id").notNull().references(()=>n.id,{onDelete:"cascade"}),status:vt("status").notNull().default("pending"),config:ht("config").notNull().default({}),progress:ht("progress").notNull().default({}),result:ht("result"),error:vt("error"),attempts:Dn("attempts").notNull().default(0),taskKind:vt("task_kind"),payload:ht("payload"),claimedBy:vt("claimed_by"),claimedAt:Le("claimed_at",{withTimezone:!0}),leaseExpiresAt:Le("lease_expires_at",{withTimezone:!0}),leaseRecoveries:Dn("lease_recoveries").notNull().default(0),createdAt:Le("created_at",{withTimezone:!0}).defaultNow(),updatedAt:Le("updated_at",{withTimezone:!0}).defaultNow(),completedAt:Le("completed_at",{withTimezone:!0})},e=>[It("idx_eval_jobs_user").on(e.userId),It("idx_eval_jobs_target").on(e.evalTargetId),It("idx_eval_jobs_status").on(e.status),It("idx_eval_jobs_pending").on(e.userId,e.status)]);import{pgTable as Js,text as Ue,timestamp as Be,jsonb as Rn,uuid as jn,integer as kn,index as En}from"drizzle-orm/pg-core";var bn=Js("agent_jobs",{id:jn("id").primaryKey().defaultRandom(),userId:jn("user_id").notNull(),taskKind:Ue("task_kind").notNull(),status:Ue("status").notNull().default("pending"),payload:Rn("payload").notNull(),dedupeKey:Ue("dedupe_key"),result:Rn("result"),error:Ue("error"),attempts:kn("attempts").notNull().default(0),claimedBy:Ue("claimed_by"),claimedAt:Be("claimed_at",{withTimezone:!0}),leaseExpiresAt:Be("lease_expires_at",{withTimezone:!0}),leaseRecoveries:kn("lease_recoveries").notNull().default(0),createdAt:Be("created_at",{withTimezone:!0}).notNull().defaultNow(),updatedAt:Be("updated_at",{withTimezone:!0}).notNull().defaultNow(),completedAt:Be("completed_at",{withTimezone:!0})},e=>[En("idx_agent_jobs_claim").on(e.userId,e.status,e.taskKind,e.createdAt),En("idx_agent_jobs_dedupe").on(e.userId,e.taskKind,e.dedupeKey)]);import{pgTable as $s,text as He,timestamp as Ve,jsonb as yt,uuid as uo,index as Tt,integer as Sn}from"drizzle-orm/pg-core";var Kn=$s("insights_jobs",{id:uo("id").primaryKey().defaultRandom(),userId:uo("user_id").notNull(),status:He("status").notNull().default("pending"),projectPath:He("project_path"),projectId:uo("project_id").references(()=>s.id,{onDelete:"set null"}),config:yt("config").notNull().default({}),progress:yt("progress").notNull().default({}),result:yt("result"),error:He("error"),attempts:Sn("attempts").notNull().default(0),taskKind:He("task_kind"),payload:yt("payload"),claimedBy:He("claimed_by"),claimedAt:Ve("claimed_at",{withTimezone:!0}),leaseExpiresAt:Ve("lease_expires_at",{withTimezone:!0}),leaseRecoveries:Sn("lease_recoveries").notNull().default(0),createdAt:Ve("created_at",{withTimezone:!0}).defaultNow(),updatedAt:Ve("updated_at",{withTimezone:!0}).defaultNow(),completedAt:Ve("completed_at",{withTimezone:!0})},e=>[Tt("idx_insights_jobs_user").on(e.userId),Tt("idx_insights_jobs_status").on(e.status),Tt("idx_insights_jobs_pending").on(e.userId,e.status),Tt("idx_insights_jobs_project").on(e.projectId)]);import{pgTable as Ys,text as lo,timestamp as wt,uuid as Pn,index as Qs,uniqueIndex as Ws}from"drizzle-orm/pg-core";var ye=Ys("api_keys",{id:Pn("id").primaryKey().defaultRandom(),userId:Pn("user_id").notNull().references(()=>o.id,{onDelete:"cascade"}),name:lo("name").notNull(),keyHash:lo("key_hash").notNull(),keyPrefix:lo("key_prefix").notNull(),lastUsedAt:wt("last_used_at",{withTimezone:!0}),expiresAt:wt("expires_at",{withTimezone:!0}),revokedAt:wt("revoked_at",{withTimezone:!0}),createdAt:wt("created_at",{withTimezone:!0}).defaultNow()},e=>[Qs("idx_api_keys_user").on(e.userId),Ws("idx_api_keys_hash").on(e.keyHash)]);import{pgTable as Xs,text as co,timestamp as Cn,uuid as Zs,index as ei}from"drizzle-orm/pg-core";var On=Xs("extension_auth_codes",{code:co("code").primaryKey(),userId:Zs("user_id").notNull().references(()=>o.id,{onDelete:"cascade"}),editor:co("editor"),email:co("email"),expiresAt:Cn("expires_at",{withTimezone:!0}).notNull(),createdAt:Cn("created_at",{withTimezone:!0}).defaultNow()},e=>[ei("idx_ext_auth_codes_expiry").on(e.expiresAt)]);import{pgTable as ti,text as oi,timestamp as qn,jsonb as ni,uuid as _o,index as Mn}from"drizzle-orm/pg-core";var Te=ti("eval_conversations",{id:_o("id").primaryKey().defaultRandom(),evalTargetId:_o("eval_target_id").notNull().references(()=>n.id,{onDelete:"cascade"}),userId:_o("user_id").notNull(),messages:ni("messages").notNull().default([]),status:oi("status").notNull().default("active"),createdAt:qn("created_at",{withTimezone:!0}).defaultNow(),updatedAt:qn("updated_at",{withTimezone:!0}).defaultNow()},e=>[Mn("idx_eval_conversations_target").on(e.evalTargetId),Mn("idx_eval_conversations_user").on(e.userId)]);import{pgTable as ri,text as q,timestamp as Ln,jsonb as si,uuid as mo}from"drizzle-orm/pg-core";var Un=ri("skill_submissions",{id:mo("id").primaryKey().defaultRandom(),skillId:q("skill_id").notNull(),name:q("name").notNull(),description:q("description").notNull(),category:q("category").notNull(),tools:q("tools").array().notNull(),tags:q("tags").array().default([]),content:q("content").notNull(),status:q("status").notNull().default("pending"),submittedBy:mo("submitted_by").notNull(),reviewedBy:mo("reviewed_by"),reviewNote:q("review_note"),metadata:si("metadata"),createdAt:Ln("created_at",{withTimezone:!0}).defaultNow(),updatedAt:Ln("updated_at",{withTimezone:!0}).defaultNow()});import{pgTable as ii,text as Ge,timestamp as Bn,jsonb as ai,uuid as di,uniqueIndex as ui,index as Hn}from"drizzle-orm/pg-core";var Vn=ii("harness_releases",{id:di("id").primaryKey().defaultRandom(),harness:Ge("harness").notNull(),version:Ge("version").notNull(),publishedAt:Bn("published_at",{withTimezone:!0}).notNull(),title:Ge("title"),body:Ge("body"),categories:ai("categories").default({}),url:Ge("url"),createdAt:Bn("created_at",{withTimezone:!0}).defaultNow()},e=>[ui("idx_harness_releases_unique").on(e.harness,e.version),Hn("idx_harness_releases_harness").on(e.harness),Hn("idx_harness_releases_published").on(e.publishedAt)]);import{pgTable as li,text as we,timestamp as Gn,jsonb as ci,uuid as Fn,index as Jn,uniqueIndex as _i}from"drizzle-orm/pg-core";var po=li("notifications",{id:Fn("id").primaryKey().defaultRandom(),userId:Fn("user_id").notNull(),type:we("type").notNull(),title:we("title").notNull(),body:we("body"),url:we("url"),sourceTable:we("source_table"),sourceId:we("source_id"),metadata:ci("metadata").notNull().default({}),readAt:Gn("read_at",{withTimezone:!0}),createdAt:Gn("created_at",{withTimezone:!0}).notNull().defaultNow()},e=>[Jn("idx_notifications_user_created").on(e.userId,e.createdAt),Jn("idx_notifications_user_unread").on(e.userId),_i("idx_notifications_source_dedup").on(e.userId,e.sourceTable,e.sourceId)]);import{pgTable as mi,text as Fe,timestamp as Je,jsonb as fo,uuid as xo,index as At,integer as $n}from"drizzle-orm/pg-core";var Ae=mi("launch_jobs",{id:xo("id").primaryKey().defaultRandom(),userId:xo("user_id").notNull(),tool:Fe("tool").notNull(),status:Fe("status").notNull().default("pending"),config:fo("config").notNull().default({}),result:fo("result"),error:Fe("error"),attempts:$n("attempts").notNull().default(0),taskKind:Fe("task_kind"),payload:fo("payload"),claimedBy:Fe("claimed_by"),claimedAt:Je("claimed_at",{withTimezone:!0}),leaseExpiresAt:Je("lease_expires_at",{withTimezone:!0}),leaseRecoveries:$n("lease_recoveries").notNull().default(0),createdAt:Je("created_at",{withTimezone:!0}).defaultNow(),updatedAt:Je("updated_at",{withTimezone:!0}).defaultNow(),completedAt:Je("completed_at",{withTimezone:!0}),runId:xo("run_id").references(()=>g.id,{onDelete:"set null"})},e=>[At("idx_launch_jobs_user").on(e.userId),At("idx_launch_jobs_status").on(e.status),At("idx_launch_jobs_pending").on(e.userId,e.status),At("idx_launch_jobs_run").on(e.runId)]);import{pgTable as Yn,uuid as M,text as ze,real as pi,timestamp as zt,boolean as fi,uniqueIndex as xi,index as $e}from"drizzle-orm/pg-core";var Qn=["add","remove","trim"],No=Yn("instruction_suggestions",{id:M("id").primaryKey().defaultRandom(),userId:M("user_id").notNull().references(()=>o.id,{onDelete:"cascade"}),instructionId:M("instruction_id").notNull().references(()=>r.id,{onDelete:"cascade"}),projectPath:ze("project_path").notNull(),projectId:M("project_id").references(()=>s.id,{onDelete:"set null"}),score:pi("score").notNull(),reason:ze("reason").notNull(),kind:ze("kind").$type().notNull().default("add"),generatedAt:zt("generated_at",{withTimezone:!0}).notNull().defaultNow(),isStale:fi("is_stale").notNull().default(!1),dismissedAt:zt("dismissed_at",{withTimezone:!0}),acceptedAt:zt("accepted_at",{withTimezone:!0}),promotedToInstructionId:M("promoted_to_instruction_id").references(()=>r.id,{onDelete:"set null"})},e=>[xi("idx_instruction_suggestions_user_project_instruction_kind").on(e.userId,e.projectPath,e.instructionId,e.kind),$e("idx_instruction_suggestions_user_project").on(e.userId,e.projectPath),$e("idx_instruction_suggestions_user_proj_id").on(e.userId,e.projectId),$e("idx_instruction_suggestions_generated_at").on(e.generatedAt)]),Wn=Yn("instruction_suggestion_events",{id:M("id").primaryKey().defaultRandom(),suggestionId:M("suggestion_id").notNull().references(()=>No.id,{onDelete:"cascade"}),userId:M("user_id").notNull().references(()=>o.id,{onDelete:"cascade"}),eventType:ze("event_type").notNull(),tool:ze("tool"),sessionId:M("session_id"),projectPath:ze("project_path").notNull(),createdAt:zt("created_at",{withTimezone:!0}).notNull().defaultNow()},e=>[$e("idx_instruction_suggestion_events_suggestion_id").on(e.suggestionId),$e("idx_instruction_suggestion_events_user_id").on(e.userId)]);import{pgTable as Ni,text as go,integer as gi,numeric as Ye,timestamp as vo,index as vi,primaryKey as hi}from"drizzle-orm/pg-core";var Xn=Ni("model_pricing",{provider:go("provider").notNull(),modelId:go("model_id").notNull(),inputPerM:Ye("input_per_m").notNull(),outputPerM:Ye("output_per_m").notNull(),cacheReadPerM:Ye("cache_read_per_m").notNull(),cacheWrite5mPerM:Ye("cache_write_5m_per_m").notNull(),cacheWrite1hPerM:Ye("cache_write_1h_per_m").notNull(),contextWindow:gi("context_window"),effectiveFrom:vo("effective_from",{withTimezone:!0}).notNull(),effectiveUntil:vo("effective_until",{withTimezone:!0}),source:go("source").notNull(),verifiedAt:vo("verified_at",{withTimezone:!0})},e=>[hi({columns:[e.provider,e.modelId,e.effectiveFrom]}),vi("idx_model_pricing_active").on(e.provider,e.modelId,e.effectiveFrom.desc())]);import{pgTable as Ii,text as ne,numeric as Zn,timestamp as er,uuid as tr,jsonb as yi,index as or}from"drizzle-orm/pg-core";var nr=Ii("limit_observations",{id:tr("id").primaryKey().defaultRandom(),observedAt:er("observed_at",{withTimezone:!0}).notNull().defaultNow(),provider:ne("provider").notNull(),plan:ne("plan").notNull(),limitType:ne("limit_type").notNull(),value:Zn("value").notNull(),unit:ne("unit").notNull(),comparator:ne("comparator").notNull().default("="),resetsAt:er("resets_at",{withTimezone:!0}),sourceType:ne("source_type").notNull(),sourceUrl:ne("source_url"),sourceEvidence:yi("source_evidence"),confidence:Zn("confidence").notNull(),userId:tr("user_id")},e=>[or("idx_limit_obs_lookup").on(e.provider,e.plan,e.limitType,e.observedAt.desc()),or("idx_limit_obs_user").on(e.userId,e.observedAt.desc())]);import{pgTable as Ti,text as Dt,timestamp as wi,uuid as Ai,jsonb as zi,boolean as Di,uniqueIndex as Ri}from"drizzle-orm/pg-core";var rr=Ti("provider_docs_snapshots",{id:Ai("id").primaryKey().defaultRandom(),fetchedAt:wi("fetched_at",{withTimezone:!0}).notNull().defaultNow(),provider:Dt("provider").notNull(),docUrl:Dt("doc_url").notNull(),contentHash:Dt("content_hash").notNull(),content:Dt("content").notNull(),parseSuccess:Di("parse_success").notNull(),parseErrors:zi("parse_errors")},e=>[Ri("idx_docs_dedup").on(e.provider,e.docUrl,e.contentHash)]);import{pgTable as ji,text as Rt,numeric as sr,timestamp as ir,uuid as ki,primaryKey as Ei,index as bi}from"drizzle-orm/pg-core";var ar=ji("plan_limits_active",{provider:Rt("provider").notNull(),plan:Rt("plan").notNull(),limitType:Rt("limit_type").notNull(),value:sr("value").notNull(),unit:Rt("unit").notNull(),effectiveFrom:ir("effective_from",{withTimezone:!0}).notNull(),effectiveUntil:ir("effective_until",{withTimezone:!0}),confidence:sr("confidence").notNull(),sourceObservationIds:ki("source_observation_ids").array().notNull()},e=>[Ei({columns:[e.provider,e.plan,e.limitType,e.effectiveFrom]}),bi("idx_plan_limits_lookup").on(e.provider,e.plan,e.limitType,e.effectiveFrom.desc())]);import{pgTable as Si,text as ho,timestamp as Ki,uuid as dr,jsonb as Pi,index as Ci}from"drizzle-orm/pg-core";var ur=Si("alert_dispatches",{id:dr("id").primaryKey().defaultRandom(),userId:dr("user_id").notNull(),alertKey:ho("alert_key").notNull(),severity:ho("severity").notNull(),lastDispatchedAt:Ki("last_dispatched_at",{withTimezone:!0}).notNull().defaultNow(),lastState:Pi("last_state").notNull(),channel:ho("channel").notNull()},e=>[Ci("idx_alert_user_key").on(e.userId,e.alertKey,e.lastDispatchedAt.desc())]);import{pgTable as Oi,text as Io,timestamp as lr,uuid as yo,integer as qi,index as Mi,unique as Li}from"drizzle-orm/pg-core";var cr=Oi("scaffolding_fingerprints",{id:yo("id").primaryKey().defaultRandom(),userId:yo("user_id").notNull(),harness:Io("harness").notNull(),model:Io("model").notNull(),toolsHash:Io("tools_hash").notNull(),firstSeenAt:lr("first_seen_at",{withTimezone:!0}).notNull().defaultNow(),lastSeenAt:lr("last_seen_at",{withTimezone:!0}).notNull().defaultNow(),snapshotCount:qi("snapshot_count").notNull().default(1),firstSessionId:yo("first_session_id")},e=>[Li("scaffolding_fingerprints_user_id_harness_model_tools_hash_key").on(e.userId,e.harness,e.model,e.toolsHash),Mi("idx_scaffolding_fp_segment").on(e.userId,e.harness,e.model)]);import{pgTable as Ui,text as To,timestamp as Bi,jsonb as Hi,uuid as _r,integer as Vi,unique as Gi}from"drizzle-orm/pg-core";var mr=Ui("scaffolding_segments",{id:_r("id").primaryKey().defaultRandom(),userId:_r("user_id").notNull(),harness:To("harness").notNull(),model:To("model").notNull(),coreNames:Hi("core_names").notNull(),coreHash:To("core_hash").notNull(),activeFingerprints:Vi("active_fingerprints").notNull(),computedAt:Bi("computed_at",{withTimezone:!0}).notNull().defaultNow()},e=>[Gi("scaffolding_segments_user_id_harness_model_key").on(e.userId,e.harness,e.model)]);import{drizzle as gr}from"drizzle-orm/postgres-js";import vr from"postgres";var jt={};Or(jt,{SUGGESTION_KINDS:()=>Qn,agentJobs:()=>bn,agentRuns:()=>g,agentRunsRelations:()=>ia,alertDispatches:()=>ur,announcementDeliveries:()=>Go,announcements:()=>Vo,apiKeys:()=>ye,apiKeysRelations:()=>Ji,benchmarks:()=>Ne,benchmarksRelations:()=>ga,cliErrorEvents:()=>fn,cliSetupEvents:()=>mn,contentBlobs:()=>zn,contextSnapshots:()=>J,contextSnapshotsRelations:()=>Ta,evalComparisons:()=>Nn,evalConversations:()=>Te,evalConversationsRelations:()=>ya,evalGradeAnnotations:()=>gn,evalJobs:()=>Ie,evalJobsRelations:()=>Ia,evalRuns:()=>k,evalRunsRelations:()=>Na,evalTargets:()=>n,evalTargetsRelations:()=>fa,evals:()=>C,evalsRelations:()=>xa,extensionAuthCodes:()=>On,harnessReleases:()=>Vn,insightsJobs:()=>Kn,instructionEvents:()=>_e,instructionEventsRelations:()=>ea,instructionPromotions:()=>hn,instructionSuggestionEvents:()=>Wn,instructionSuggestions:()=>No,instructionUsageEvents:()=>xe,instructionUsageEventsRelations:()=>pa,instructionVersionIdentities:()=>Po,instructionVersions:()=>ae,instructionVersionsRelations:()=>oa,instructions:()=>r,instructionsRelations:()=>Zi,judgeReviewerVerdicts:()=>vn,launchJobs:()=>Ae,launchJobsRelations:()=>aa,limitObservations:()=>nr,memories:()=>T,memoriesRelations:()=>ta,memoryExperiments:()=>Ho,modelPricing:()=>Xn,notificationPreferences:()=>Fo,notifications:()=>po,optimizationRuns:()=>he,optimizationRunsRelations:()=>ha,orgInvitations:()=>b,orgInvitationsRelations:()=>Qi,organizations:()=>u,organizationsRelations:()=>$i,packInstructions:()=>G,packInstructionsRelations:()=>ma,packs:()=>z,packsRelations:()=>_a,pendingTreatmentExposures:()=>Zo,planLimitsActive:()=>ar,profiles:()=>o,profilesRelations:()=>Fi,projectCheckouts:()=>Oo,projectInstructions:()=>U,projectInstructionsRelations:()=>ra,projects:()=>s,projectsRelations:()=>na,providerDocsSnapshots:()=>rr,scaffoldingFingerprints:()=>cr,scaffoldingSegments:()=>mr,sessionEvents:()=>ue,sessionEventsRelations:()=>da,sessionInstructions:()=>B,sessionInstructionsRelations:()=>ua,sessionSendJobs:()=>nn,sessionTerminalTargets:()=>lt,sessions:()=>d,sessionsRelations:()=>sa,skillSubmissions:()=>Un,teams:()=>h,teamsRelations:()=>Yi,treatmentAssignments:()=>S,treatmentAssignmentsRelations:()=>la,treatmentExposures:()=>K,treatmentExposuresRelations:()=>ca,triggerEvals:()=>ve,triggerEvalsRelations:()=>va,userOrganizations:()=>se,userOrganizationsRelations:()=>Wi,userTeams:()=>ie,userTeamsRelations:()=>Xi,workerConnections:()=>ln});import{relations as i}from"drizzle-orm";var Fi=i(o,({many:e})=>({sessions:e(d),contextSnapshots:e(J),apiKeys:e(ye)})),Ji=i(ye,({one:e})=>({profile:e(o,{fields:[ye.userId],references:[o.id]})})),$i=i(u,({many:e})=>({teams:e(h),userOrganizations:e(se),projects:e(s),invitations:e(b)})),Yi=i(h,({one:e,many:t})=>({organization:e(u,{fields:[h.orgId],references:[u.id]}),userTeams:t(ie),invitations:t(b)})),Qi=i(b,({one:e})=>({organization:e(u,{fields:[b.orgId],references:[u.id]}),team:e(h,{fields:[b.teamId],references:[h.id]}),inviter:e(o,{fields:[b.invitedBy],references:[o.id]})})),Wi=i(se,({one:e})=>({organization:e(u,{fields:[se.orgId],references:[u.id]})})),Xi=i(ie,({one:e})=>({team:e(h,{fields:[ie.teamId],references:[h.id]})})),Zi=i(r,({one:e,many:t})=>({versions:t(ae),projectInstructions:t(U),events:t(_e),usageEvents:t(xe),sessionInstructions:t(B),packInstructions:t(G),forkedFrom:e(r,{fields:[r.forkedFromId],references:[r.id]})})),ea=i(_e,({one:e})=>({instruction:e(r,{fields:[_e.instructionId],references:[r.id]})})),ta=i(T,({one:e,many:t})=>({project:e(s,{fields:[T.projectId],references:[s.id]}),parent:e(T,{fields:[T.parentId],references:[T.id]}),versions:t(T)})),oa=i(ae,({one:e})=>({instruction:e(r,{fields:[ae.instructionId],references:[r.id]})})),na=i(s,({one:e,many:t})=>({organization:e(u,{fields:[s.orgId],references:[u.id]}),projectInstructions:t(U),sessions:t(d)})),ra=i(U,({one:e})=>({project:e(s,{fields:[U.projectId],references:[s.id]}),instruction:e(r,{fields:[U.instructionId],references:[r.id]})})),sa=i(d,({one:e,many:t})=>({profile:e(o,{fields:[d.userId],references:[o.id]}),project:e(s,{fields:[d.projectId],references:[s.id]}),run:e(g,{fields:[d.runId],references:[g.id]}),events:t(ue),sessionInstructions:t(B),treatmentExposures:t(K),contextSnapshots:t(J)})),ia=i(g,({one:e,many:t})=>({profile:e(o,{fields:[g.userId],references:[o.id]}),organization:e(u,{fields:[g.orgId],references:[u.id]}),project:e(s,{fields:[g.projectId],references:[s.id]}),sessions:t(d),launchJobs:t(Ae)})),aa=i(Ae,({one:e})=>({run:e(g,{fields:[Ae.runId],references:[g.id]})})),da=i(ue,({one:e})=>({session:e(d,{fields:[ue.sessionId],references:[d.id]})})),ua=i(B,({one:e})=>({session:e(d,{fields:[B.sessionId],references:[d.id]}),instruction:e(r,{fields:[B.instructionId],references:[r.id]})})),la=i(S,({one:e,many:t})=>({owner:e(o,{fields:[S.userId],references:[o.id]}),project:e(s,{fields:[S.projectId],references:[s.id]}),exposures:t(K)})),ca=i(K,({one:e})=>({session:e(d,{fields:[K.sessionId],references:[d.id]}),owner:e(o,{fields:[K.userId],references:[o.id]}),assignment:e(S,{fields:[K.assignmentId],references:[S.id]})})),_a=i(z,({one:e,many:t})=>({packInstructions:t(G),forkedFrom:e(z,{fields:[z.forkedFromId],references:[z.id]})})),ma=i(G,({one:e})=>({pack:e(z,{fields:[G.packId],references:[z.id]}),instruction:e(r,{fields:[G.instructionId],references:[r.id]})})),pa=i(xe,({one:e})=>({instruction:e(r,{fields:[xe.instructionId],references:[r.id]})})),fa=i(n,({one:e,many:t})=>({parent:e(n,{fields:[n.parentId],references:[n.id]}),evals:t(C),evalRuns:t(k),benchmarks:t(Ne),triggerEvals:t(ve),optimizationRuns:t(he),evalJobs:t(Ie),evalConversations:t(Te)})),xa=i(C,({one:e,many:t})=>({evalTarget:e(n,{fields:[C.evalTargetId],references:[n.id]}),runs:t(k)})),Na=i(k,({one:e})=>({eval:e(C,{fields:[k.evalId],references:[C.id]}),evalTarget:e(n,{fields:[k.evalTargetId],references:[n.id]})})),ga=i(Ne,({one:e})=>({evalTarget:e(n,{fields:[Ne.evalTargetId],references:[n.id]})})),va=i(ve,({one:e})=>({evalTarget:e(n,{fields:[ve.evalTargetId],references:[n.id]})})),ha=i(he,({one:e})=>({evalTarget:e(n,{fields:[he.evalTargetId],references:[n.id]})})),Ia=i(Ie,({one:e})=>({evalTarget:e(n,{fields:[Ie.evalTargetId],references:[n.id]})})),ya=i(Te,({one:e})=>({evalTarget:e(n,{fields:[Te.evalTargetId],references:[n.id]})})),Ta=i(J,({one:e})=>({session:e(d,{fields:[J.sessionId],references:[d.id]}),profile:e(o,{fields:[J.userId],references:[o.id]})}));var Qe=0,pr=0,We=0,fr=0;var wa=0;function wo(){Qe++,Qe>pr&&(pr=Qe)}p(wo,"trackDbOpStart");function Ao(){Qe>0&&Qe--}p(Ao,"trackDbOpEnd");function zo(){We++,We>fr&&(fr=We)}p(zo,"trackHeavyDbOpStart");function Do(){We>0&&We--}p(Do,"trackHeavyDbOpEnd");function xr(){wa++}p(xr,"recordQueryDeadline");var Et,St,Ro=!1,kt;var Nr,Kt,bt;function hr(e){let t=process.env[e];if(!t)throw new Error(`Missing required env var: ${e}`);return t}p(hr,"getEnv");function Ir(){if(Ro)throw new Error("getDb() called after closeDb(): the connection pool is closed for shutdown. Stop issuing queries (timers/requests) before draining the pool.");if(!Et){let e=process.env.PG_APPLICATION_NAME||"rulemetric",t=Number(process.env.PG_POOL_MAX)||3,a=Number(process.env.PG_CONNECT_TIMEOUT_S)||10,l=Number(process.env.PG_STATEMENT_TIMEOUT_MS)||0,m=Number(process.env.PG_IDLE_TIMEOUT)||5,f=Number(process.env.PG_KEEP_ALIVE_S)||60;St=vr(hr("DATABASE_URL"),{prepare:!1,max:t,connect_timeout:a,idle_timeout:m,keep_alive:f,max_lifetime:300,connection:{application_name:e,...l>0?{statement_timeout:l}:{}}}),Et=gr(St,{schema:jt})}return Et}p(Ir,"getDb");function yr(){if(Ro)throw new Error("getHeavyDb() called after closeDb(): the connection pool is closed for shutdown. Stop issuing queries (timers/requests) before draining the pool.");if(!bt){let e=(process.env.PG_APPLICATION_NAME||"rulemetric")+":heavy",t=Number(process.env.PG_HEAVY_POOL_MAX)||2;Kt=vr(hr("DATABASE_URL"),{prepare:!1,max:t,connect_timeout:Number(process.env.PG_CONNECT_TIMEOUT_S)||10,idle_timeout:Number(process.env.PG_IDLE_TIMEOUT)||5,keep_alive:Number(process.env.PG_KEEP_ALIVE_S)||60,max_lifetime:300,connection:{application_name:e}}),bt=gr(Kt,{schema:jt})}return bt}p(yr,"getHeavyDb");async function Aa(){if(kt)return kt;Ro=!0;let e=St,t=Nr,a=Kt;return St=void 0,Et=void 0,Nr=void 0,Kt=void 0,bt=void 0,kt=Promise.allSettled([e?e.end({timeout:5}):Promise.resolve(),t?t.end({timeout:5}):Promise.resolve(),a?a.end({timeout:5}):Promise.resolve()]).then(()=>{}),kt}p(Aa,"closeDb");var za=new Set(["CONNECT_TIMEOUT","ETIMEDOUT","ENOTFOUND","ECONNREFUSED","EAI_AGAIN"]);function Tr(e){let t=e,a=t?.code??t?.cause?.code??t?.errno;return a!==void 0&&za.has(a)}p(Tr,"isRetryableConnectError");var Da=new Set(["CONNECTION_CLOSED","ECONNRESET","EPIPE"]);function wr(e){let t=e,a=t?.code??t?.cause?.code??t?.errno;return a!==void 0&&Da.has(a)}p(wr,"isRetryableResetError");async function Ar(e,t={}){let a=t.attempts??3,l=t.baseMs??100,m;for(let f=0;f<a;f++)try{return await e()}catch(y){m=y;let De=Tr(y)||t.retryResets===!0&&wr(y);if(f===a-1||!De)throw y;await new Promise($=>setTimeout($,l*2**f))}throw m}p(Ar,"withDbRetry");var Pt=class extends Error{static{p(this,"QueryDeadlineError")}code="QUERY_DEADLINE";constructor(t){super(`Query exceeded the client-side deadline of ${t}ms \u2014 the DB pool is likely saturated (acquire-wait) or holding a dead socket; failing fast to avoid pinning the caller. See client.ts.`),this.name="QueryDeadlineError"}};function zr(){let e=Number(process.env.PG_QUERY_DEADLINE_MS);return Number.isFinite(e)&&e>=0?e:2e4}p(zr,"queryDeadlineMs");function Ra(e,t){let a,l=new Promise((m,f)=>{a=setTimeout(()=>{xr(),f(new Pt(t))},t);let y=a;typeof y.unref=="function"&&y.unref()});return Promise.race([e,l]).finally(()=>clearTimeout(a))}p(Ra,"raceWithDeadline");var Dr=new Set(["select","selectDistinct","selectDistinctOn","insert","update","delete","execute","with","$count","refreshMaterializedView"]),Rr=new Set(["select","selectDistinct","selectDistinctOn","$count"]);function jo(e,t=!1,a=0,l=!1){return e===null||typeof e!="object"&&typeof e!="function"?e:new Proxy(e,{get(m,f,y){if(f==="then"){let $=Reflect.get(m,f,y);return typeof $!="function"?$:(Er,br)=>{let Sr=l?zo:wo,Kr=l?Do:Ao;Sr();let ko=Ar(()=>new Promise((Pr,Cr)=>$.call(m,Pr,Cr)),{retryResets:t});return(a>0?Ra(ko,a):ko).finally(Kr).then(Er,br)}}let De=Reflect.get(m,f,y);return typeof De=="function"?(...$)=>jo(De.apply(m,$),t,a,l):De}})}p(jo,"wrapBuilder");function jr(e,t=!1){let a=t?zo:wo,l=t?Do:Ao;a();try{return Promise.resolve(e()).finally(l)}catch(m){throw l(),m}}p(jr,"gaugeTransaction");var kr=new Proxy({},{get(e,t){let a=Ir(),l=a[t];if(typeof t=="string"&&Dr.has(t)&&typeof l=="function"){let m=Rr.has(t),f=zr();return(...y)=>jo(l.apply(a,y),m,f)}return t==="transaction"&&typeof l=="function"?(...m)=>jr(()=>l.apply(a,m)):l}}),ja=new Proxy({},{get(e,t){let a=yr(),l=a[t];if(typeof t=="string"&&Dr.has(t)&&typeof l=="function"){let m=Rr.has(t);return(...f)=>jo(l.apply(a,f),m,0,!0)}return t==="transaction"&&typeof l=="function"?(...m)=>jr(()=>l.apply(a,m),!0):l}});export{o as a,g as b,d as c,T as d,Ho as e,Vo as f,Go as g,Fo as h,Ir as i,Aa as j};
@@ -1 +1 @@
1
- import{a as E}from"./chunk-X23L2MF6.js";import{a as J}from"./chunk-B22HYCBV.js";import{a as j}from"./chunk-ULMEKK7C.js";import{b as I,c as P,d as v}from"./chunk-5RUEROLC.js";import{d as T}from"./chunk-NJ5UED3H.js";import{a as b}from"./chunk-ZLLER3HP.js";import{useEffect as R,useState as i}from"react";import{Box as l,Text as s,useInput as Z}from"ink";import{jsx as t,jsxs as a}from"react/jsx-runtime";function K({onClose:A,activeOrg:F,defaultProjectPath:y,width:_}){let{jobs:u,error:L,loading:$,refetch:S}=j(20),[M,C]=i([]),[d,m]=i("list"),[f,w]=i(0),[h,g]=i(null),[x,B]=i(null),[p,c]=i(null);R(()=>{v().then(C).catch(o=>{let r=o instanceof Error?o.message:String(o);c(`couldn't load launchers: ${r}`),C([{tool:"claude_code",capabilities:{headless:!0,interactive:!0,remoteSpawn:!0}}])})},[]),R(()=>{if(!p)return;let o=setTimeout(()=>c(null),5e3);return()=>clearTimeout(o)},[p]),Z((o,r)=>{if(h){if(o==="y"||o==="Y"){let e=h.id;g(null),P(e).then(()=>{S(),c(`cancelled ${e.slice(0,8)}`)}).catch(n=>c(`cancel failed: ${n instanceof Error?n.message:String(n)}`))}else(o==="n"||o==="N"||r.escape)&&g(null);return}if(r.escape){if(d!=="none"){m("none");return}A();return}if(r.tab){m(e=>e==="list"?"form":e==="form"?"none":"list");return}if(o!=="q"&&d==="list"){if(r.upArrow)w(e=>Math.max(0,e-1));else if(r.downArrow)w(e=>Math.min(u.length-1,e+1));else if(o==="c"){let e=u[f];e&&(e.status==="running"||e.status==="queued"||e.status==="pending")&&g(e)}else if(o==="r"){let e=u[f],n=e?.result?.externalSessionId;e&&e.tool==="claude_code"&&n?(B({tool:"claude_code",projectPath:e.config.projectPath,resumeSessionId:n}),m("form")):c("resume needs a Claude Code session with a session id")}else if(o==="o"){let n=u[f]?.result?.externalSessionId;if(n){let O=process.env.RULEMETRIC_WEB_URL??"http://localhost:5174";import("node:child_process").then(({spawn:U})=>{U("open",[`${O}/sessions/${n}`],{detached:!0,stdio:"ignore"}).unref()})}}}});async function N(o){await I(o),B(null),m("list"),c("launched"),S()}return b(N,"handleSubmit"),a(l,{flexDirection:"column",borderStyle:"round",borderColor:T,width:_,paddingX:1,children:[a(l,{children:[t(s,{bold:!0,color:T,children:"Launcher"}),t(s,{dimColor:!0,children:" active org: "}),t(s,{children:F??"(none)"}),$&&t(s,{dimColor:!0,children:" loading\u2026"}),L&&a(s,{color:"#F55B5B",children:[" \u26A0 ",L]})]}),t(l,{marginTop:1,children:t(E,{jobs:u,selectedIndex:f,focused:d==="list"})}),t(l,{marginTop:1,children:t(J,{launchers:M,defaultProjectPath:x?.projectPath??y,defaultTool:x?.tool,defaultResumeSessionId:x?.resumeSessionId,focused:d==="form",onSubmit:N})}),h&&t(l,{marginTop:1,children:a(s,{color:"#FFD700",children:["Cancel job ",h.id.slice(0,8),"? (y/n)"]})}),p&&t(l,{marginTop:1,children:a(s,{dimColor:!0,children:["\xB7 ",p]})}),t(l,{marginTop:1,children:a(s,{dimColor:!0,children:["\u2191\u2193 select tab focus c cancel r resume o open esc ",d==="none"?"close":"back"]})})]})}b(K,"LauncherOverlay");export{K as a};
1
+ import{a as E}from"./chunk-NBTC5FNV.js";import{a as J}from"./chunk-TU2AR6XO.js";import{d as T}from"./chunk-NJ5UED3H.js";import{a as j}from"./chunk-ULMEKK7C.js";import{b as I,c as P,d as v}from"./chunk-5RUEROLC.js";import{a as b}from"./chunk-ZLLER3HP.js";import{useEffect as R,useState as i}from"react";import{Box as l,Text as s,useInput as Z}from"ink";import{jsx as t,jsxs as a}from"react/jsx-runtime";function K({onClose:A,activeOrg:F,defaultProjectPath:y,width:_}){let{jobs:u,error:L,loading:$,refetch:S}=j(20),[M,C]=i([]),[d,m]=i("list"),[f,w]=i(0),[h,g]=i(null),[x,B]=i(null),[p,c]=i(null);R(()=>{v().then(C).catch(o=>{let r=o instanceof Error?o.message:String(o);c(`couldn't load launchers: ${r}`),C([{tool:"claude_code",capabilities:{headless:!0,interactive:!0,remoteSpawn:!0}}])})},[]),R(()=>{if(!p)return;let o=setTimeout(()=>c(null),5e3);return()=>clearTimeout(o)},[p]),Z((o,r)=>{if(h){if(o==="y"||o==="Y"){let e=h.id;g(null),P(e).then(()=>{S(),c(`cancelled ${e.slice(0,8)}`)}).catch(n=>c(`cancel failed: ${n instanceof Error?n.message:String(n)}`))}else(o==="n"||o==="N"||r.escape)&&g(null);return}if(r.escape){if(d!=="none"){m("none");return}A();return}if(r.tab){m(e=>e==="list"?"form":e==="form"?"none":"list");return}if(o!=="q"&&d==="list"){if(r.upArrow)w(e=>Math.max(0,e-1));else if(r.downArrow)w(e=>Math.min(u.length-1,e+1));else if(o==="c"){let e=u[f];e&&(e.status==="running"||e.status==="queued"||e.status==="pending")&&g(e)}else if(o==="r"){let e=u[f],n=e?.result?.externalSessionId;e&&e.tool==="claude_code"&&n?(B({tool:"claude_code",projectPath:e.config.projectPath,resumeSessionId:n}),m("form")):c("resume needs a Claude Code session with a session id")}else if(o==="o"){let n=u[f]?.result?.externalSessionId;if(n){let O=process.env.RULEMETRIC_WEB_URL??"http://localhost:5174";import("node:child_process").then(({spawn:U})=>{U("open",[`${O}/sessions/${n}`],{detached:!0,stdio:"ignore"}).unref()})}}}});async function N(o){await I(o),B(null),m("list"),c("launched"),S()}return b(N,"handleSubmit"),a(l,{flexDirection:"column",borderStyle:"round",borderColor:T,width:_,paddingX:1,children:[a(l,{children:[t(s,{bold:!0,color:T,children:"Launcher"}),t(s,{dimColor:!0,children:" active org: "}),t(s,{children:F??"(none)"}),$&&t(s,{dimColor:!0,children:" loading\u2026"}),L&&a(s,{color:"#F55B5B",children:[" \u26A0 ",L]})]}),t(l,{marginTop:1,children:t(E,{jobs:u,selectedIndex:f,focused:d==="list"})}),t(l,{marginTop:1,children:t(J,{launchers:M,defaultProjectPath:x?.projectPath??y,defaultTool:x?.tool,defaultResumeSessionId:x?.resumeSessionId,focused:d==="form",onSubmit:N})}),h&&t(l,{marginTop:1,children:a(s,{color:"#FFD700",children:["Cancel job ",h.id.slice(0,8),"? (y/n)"]})}),p&&t(l,{marginTop:1,children:a(s,{dimColor:!0,children:["\xB7 ",p]})}),t(l,{marginTop:1,children:a(s,{dimColor:!0,children:["\u2191\u2193 select tab focus c cancel r resume o open esc ",d==="none"?"close":"back"]})})]})}b(K,"LauncherOverlay");export{K as a};
@@ -1,2 +1,2 @@
1
- import{b as s,c as r,i as j}from"./chunk-45DOTNQM.js";import{c as R}from"./chunk-6QKI756T.js";import{a as P}from"./chunk-5RBLIVBF.js";import{a as g}from"./chunk-ZLLER3HP.js";import{and as y,eq as l,isNotNull as I}from"drizzle-orm";async function O($,p={}){let k=p.db??j(),b=p.removeWorktreeFn??R,n=p.log??(e=>process.stderr.write(`[process_run_cleanup] ${e}
1
+ import{c as R}from"./chunk-6QKI756T.js";import{b as s,c as r,i as j}from"./chunk-7G6T5C7J.js";import{a as P}from"./chunk-5RBLIVBF.js";import{a as g}from"./chunk-ZLLER3HP.js";import{and as y,eq as l,isNotNull as I}from"drizzle-orm";async function O($,p={}){let k=p.db??j(),b=p.removeWorktreeFn??R,n=p.log??(e=>process.stderr.write(`[process_run_cleanup] ${e}
2
2
  `)),{runId:t}=$,[i]=await k.select({id:s.id,userId:s.userId,projectPath:s.projectPath}).from(s).where(l(s.id,t)).limit(1);if(!i)throw new P(`Run ${t} not found`);if(!i.projectPath)throw new P(`Run ${t} has no projectPath; cannot resolve a repo root for worktree cleanup`);let c=i.projectPath,v=await k.select({id:r.id,projectPath:r.projectPath}).from(r).where(y(l(r.runId,t),l(r.userId,i.userId),I(r.endedAt))),a=[],u=0,d=0,h=0,m=0,w=new Set;for(let e of v)if(!(!e.projectPath||e.projectPath===c)&&!w.has(e.projectPath)){w.add(e.projectPath);try{let o=await b({repoRoot:c,worktreePath:e.projectPath});o.removed?(u++,a.push({sessionId:e.id,worktreePath:e.projectPath,status:"removed"}),n(`removed worktree ${e.projectPath} (session ${e.id})`)):o.reason==="dirty"?(d++,a.push({sessionId:e.id,worktreePath:e.projectPath,status:"skipped-dirty"}),n(`skipped dirty worktree ${e.projectPath} (session ${e.id}) \u2014 uncommitted changes`)):(h++,a.push({sessionId:e.id,worktreePath:e.projectPath,status:"absent"}),n(`worktree absent ${e.projectPath} (session ${e.id})`))}catch(o){let f=o instanceof Error?o.message:String(o);m++,a.push({sessionId:e.id,worktreePath:e.projectPath,status:"error",error:f.slice(0,1e3)}),n(`error removing worktree ${e.projectPath} (session ${e.id}): ${f}`)}}return n(`run ${t} cleanup: removed=${u} skippedDirty=${d} absent=${h} errored=${m}`),{runId:t,repoRoot:c,removed:u,skippedDirty:d,absent:h,errored:m,worktrees:a}}g(O,"processRunCleanup");export{O as a};
@@ -1 +1 @@
1
- import{d as u,e as t,i as x}from"./chunk-45DOTNQM.js";import{a as A}from"./chunk-4L2ZEIRE.js";import{b as P}from"./chunk-G5BXZT6F.js";import{c as E}from"./chunk-HMMO27U4.js";import{a as f}from"./chunk-ZLLER3HP.js";import{eq as s}from"drizzle-orm";var v=f(m=>(m.summary.pass_rate??0)>=1?1:0,"fullPassScore");async function q(m,d={}){let r=d.db??x(),w=d.executeEval??E,y=d.grade??A,n=d.now??Date.now,[e]=await r.select().from(t).where(s(t.id,m.experimentId)).limit(1);if(!e)return{skipped:"not_found"};if(e.status==="completed"||e.status==="failed")return{skipped:"already_terminal",status:e.status};let[g]=await r.select({body:u.body}).from(u).where(s(u.id,e.memoryId)).limit(1);if(!g)return await r.update(t).set({status:"failed",error:"memory no longer exists",completedAt:new Date(n())}).where(s(t.id,e.id)),{skipped:"memory_gone",status:"failed"};await r.update(t).set({status:"running",startedAt:new Date(n())}).where(s(t.id,e.id));let b=e.expectations??[],l=e.model??void 0,a=[],h=0;try{for(let i=0;i<e.trials;i++){let c=await w({prompt:e.taskPrompt,targetContent:g.body,model:l}),p=await w({prompt:e.taskPrompt,model:l});if(c.error||p.error){h++;continue}let[D,M]=await Promise.all([y({prompt:e.taskPrompt,output:c.output,expectations:b,model:l}),y({prompt:e.taskPrompt,output:p.output,expectations:b,model:l})]);a.push({withScore:v(D),withoutScore:v(M),withLatency:c.durationMs/1e3,withoutLatency:p.durationMs/1e3})}if(a.length===0){let i=`no trials completed (${h}/${e.trials} runs errored \u2014 is the claude CLI available?)`;return await r.update(t).set({status:"failed",error:i,completedAt:new Date(n())}).where(s(t.id,e.id)),{status:"failed",requestedTrials:e.trials,completedTrials:0}}let o=P(a);return await r.update(t).set({status:"completed",result:{verdict:o,pairs:a,completedTrials:a.length,model:l??null},completedAt:new Date(n())}).where(s(t.id,e.id)),{status:"completed",requestedTrials:e.trials,completedTrials:a.length,significant:o.significant,delta:o.delta}}catch(o){let i=o instanceof Error?o.message:String(o);return await r.update(t).set({status:"failed",error:i.slice(0,500),completedAt:new Date(n())}).where(s(t.id,e.id)),{status:"failed",requestedTrials:e.trials,completedTrials:a.length}}}f(q,"processMemoryAb");export{q as a};
1
+ import{d as u,e as t,i as x}from"./chunk-7G6T5C7J.js";import{a as A}from"./chunk-4L2ZEIRE.js";import{b as P}from"./chunk-G5BXZT6F.js";import{c as E}from"./chunk-HMMO27U4.js";import{a as f}from"./chunk-ZLLER3HP.js";import{eq as s}from"drizzle-orm";var v=f(m=>(m.summary.pass_rate??0)>=1?1:0,"fullPassScore");async function q(m,d={}){let r=d.db??x(),w=d.executeEval??E,y=d.grade??A,n=d.now??Date.now,[e]=await r.select().from(t).where(s(t.id,m.experimentId)).limit(1);if(!e)return{skipped:"not_found"};if(e.status==="completed"||e.status==="failed")return{skipped:"already_terminal",status:e.status};let[g]=await r.select({body:u.body}).from(u).where(s(u.id,e.memoryId)).limit(1);if(!g)return await r.update(t).set({status:"failed",error:"memory no longer exists",completedAt:new Date(n())}).where(s(t.id,e.id)),{skipped:"memory_gone",status:"failed"};await r.update(t).set({status:"running",startedAt:new Date(n())}).where(s(t.id,e.id));let b=e.expectations??[],l=e.model??void 0,a=[],h=0;try{for(let i=0;i<e.trials;i++){let c=await w({prompt:e.taskPrompt,targetContent:g.body,model:l}),p=await w({prompt:e.taskPrompt,model:l});if(c.error||p.error){h++;continue}let[D,M]=await Promise.all([y({prompt:e.taskPrompt,output:c.output,expectations:b,model:l}),y({prompt:e.taskPrompt,output:p.output,expectations:b,model:l})]);a.push({withScore:v(D),withoutScore:v(M),withLatency:c.durationMs/1e3,withoutLatency:p.durationMs/1e3})}if(a.length===0){let i=`no trials completed (${h}/${e.trials} runs errored \u2014 is the claude CLI available?)`;return await r.update(t).set({status:"failed",error:i,completedAt:new Date(n())}).where(s(t.id,e.id)),{status:"failed",requestedTrials:e.trials,completedTrials:0}}let o=P(a);return await r.update(t).set({status:"completed",result:{verdict:o,pairs:a,completedTrials:a.length,model:l??null},completedAt:new Date(n())}).where(s(t.id,e.id)),{status:"completed",requestedTrials:e.trials,completedTrials:a.length,significant:o.significant,delta:o.delta}}catch(o){let i=o instanceof Error?o.message:String(o);return await r.update(t).set({status:"failed",error:i.slice(0,500),completedAt:new Date(n())}).where(s(t.id,e.id)),{status:"failed",requestedTrials:e.trials,completedTrials:a.length}}}f(q,"processMemoryAb");export{q as a};
@@ -1 +1 @@
1
- import{b as f}from"./chunk-ZXF5NE54.js";import{d as i,e as n,g,h as m}from"./chunk-NJ5UED3H.js";import{a as s}from"./chunk-ZLLER3HP.js";import{Box as u,Text as t}from"ink";import{jsx as l,jsxs as e}from"react/jsx-runtime";var y={pending:{glyph:"\u25CC",color:n},queued:{glyph:"\u25CC",color:n},running:{glyph:"\u25CF",color:i},completed:{glyph:"\u2713",color:g},failed:{glyph:"\u2717",color:m},cancelled:{glyph:"\u2298",color:n}};function b(c){let p=Date.now()-new Date(c).getTime(),r=Math.floor(p/6e4);if(r<1)return"now";if(r<60)return`${r}m`;let o=Math.floor(r/60);return o<24?`${o}h`:`${Math.floor(o/24)}d`}s(b,"ago");function w({jobs:c,selectedIndex:p,focused:r}){return c.length===0?e(u,{flexDirection:"column",paddingX:1,children:[l(t,{bold:!0,color:i,children:"\u25BC Active jobs"}),l(t,{dimColor:!0,children:" (no jobs yet \u2014 press tab to focus the form below)"})]}):e(u,{flexDirection:"column",paddingX:1,children:[e(t,{bold:!0,color:i,children:["\u25BC Active jobs (last ",c.length,")"]}),c.map((o,h)=>{let d=r&&h===p,a=y[o.status]??{glyph:"?",color:n},x=o.config?.projectPath??"",T=(o.config?.prompt??"").slice(0,30);return e(t,{wrap:"truncate-end",children:[l(t,{color:d?i:n,children:d?"\u25B6 ":" "}),e(t,{color:a.color,children:[a.glyph," "]}),l(t,{dimColor:!0,children:o.status.padEnd(10)}),l(t,{children:f(o.tool).padEnd(14)}),l(t,{dimColor:!0,children:x.padEnd(28)}),e(t,{children:['"',T,'"']}),e(t,{dimColor:!0,children:[" ",b(o.createdAt)]})]},o.id)})]})}s(w,"ActiveJobsList");export{w as a};
1
+ import{d as i,e as n,g,h as m}from"./chunk-NJ5UED3H.js";import{b as f}from"./chunk-ZXF5NE54.js";import{a as s}from"./chunk-ZLLER3HP.js";import{Box as u,Text as t}from"ink";import{jsx as l,jsxs as e}from"react/jsx-runtime";var y={pending:{glyph:"\u25CC",color:n},queued:{glyph:"\u25CC",color:n},running:{glyph:"\u25CF",color:i},completed:{glyph:"\u2713",color:g},failed:{glyph:"\u2717",color:m},cancelled:{glyph:"\u2298",color:n}};function b(c){let p=Date.now()-new Date(c).getTime(),r=Math.floor(p/6e4);if(r<1)return"now";if(r<60)return`${r}m`;let o=Math.floor(r/60);return o<24?`${o}h`:`${Math.floor(o/24)}d`}s(b,"ago");function w({jobs:c,selectedIndex:p,focused:r}){return c.length===0?e(u,{flexDirection:"column",paddingX:1,children:[l(t,{bold:!0,color:i,children:"\u25BC Active jobs"}),l(t,{dimColor:!0,children:" (no jobs yet \u2014 press tab to focus the form below)"})]}):e(u,{flexDirection:"column",paddingX:1,children:[e(t,{bold:!0,color:i,children:["\u25BC Active jobs (last ",c.length,")"]}),c.map((o,h)=>{let d=r&&h===p,a=y[o.status]??{glyph:"?",color:n},x=o.config?.projectPath??"",T=(o.config?.prompt??"").slice(0,30);return e(t,{wrap:"truncate-end",children:[l(t,{color:d?i:n,children:d?"\u25B6 ":" "}),e(t,{color:a.color,children:[a.glyph," "]}),l(t,{dimColor:!0,children:o.status.padEnd(10)}),l(t,{children:f(o.tool).padEnd(14)}),l(t,{dimColor:!0,children:x.padEnd(28)}),e(t,{children:['"',T,'"']}),e(t,{dimColor:!0,children:[" ",b(o.createdAt)]})]},o.id)})]})}s(w,"ActiveJobsList");export{w as a};
@@ -1 +1 @@
1
- import{c as C}from"./chunk-5XUN743A.js";import{a as M}from"./chunk-QUDMK76I.js";import{a as L}from"./chunk-C7YRLB37.js";import{a as y}from"./chunk-RSKQRVPJ.js";import{a as H}from"./chunk-HXZM2UHO.js";import{b as R}from"./chunk-YW3JQKGY.js";import{a as T}from"./chunk-2J3IHWE2.js";import{a as A}from"./chunk-O2BKBW7Z.js";import{a as E}from"./chunk-KGQ5W54Y.js";import{a as I}from"./chunk-JCXKWHZX.js";import{a as x}from"./chunk-MOAJLSYV.js";import{b as S}from"./chunk-BLCMXTIK.js";import{b as h}from"./chunk-5RBLIVBF.js";import{a as P}from"./chunk-EN43UYBN.js";import{a as N}from"./chunk-FAXV5AAG.js";import{a as k}from"./chunk-UF6US7VU.js";import{b as _}from"./chunk-6ME5OTS5.js";import{j as b}from"./chunk-2RCWYVEU.js";import{d as w}from"./chunk-NTKO4H2K.js";import{b as f,e as v,f as p}from"./chunk-KLEF5D3A.js";import{a as s}from"./chunk-ZLLER3HP.js";var W={process_eval:E,process_insights:I,process_launch:S,process_send_message:y,process_conversation:A,process_session_goal:H,distill_memories:R,memory_ab:M,process_announcement:T,process_run_cleanup:L,cron_suggest_instructions:_,cron_refresh_skills:k,cron_refresh_pricing:N,cron_eval_autorun:P,cron_instruction_evolution:b,process_judge_review:x},D=Object.keys(W),F=new Set(["process_announcement","process_run_cleanup","memory_ab"]);function J(e=process.env){return e.DATABASE_URL?D:D.filter(n=>!F.has(n))}s(J,"availableCapabilities");var U=3e4,K=3e4,G=3e4,V=250,B=5e3,q=`thin-agent-${process.pid}`,g=null;function Q(e,n,r,l){let c;try{let d=w();c={claude:d.claudeBin!=null,codex:d.codexBin!=null,codexModel:d.codexConfiguredModel}}catch{}let i=s(d=>{p("/api/workers/heartbeat",{workerType:"cli-worker",clientName:q,clientVersion:l,workerVersion:"0.1.0",currentJobId:null,inFlightCount:0,lastError:null,status:d,metadata:{capabilities:e,mode:"thin-agent",llmEngines:c}}).then(u=>{let t=u?.advisory;t&&t.message!==g?(g=t.message,a(r,{event:"worker_advisory",code:t.code,message:t.message})):t||(g=null)}).catch(u=>{a(r,{event:"presence_heartbeat_error",error:u instanceof Error?u.message:String(u)})})},"send");i("alive");let o=setInterval(()=>i("alive"),G);n.addEventListener("abort",()=>{clearInterval(o),i("shutting_down")},{once:!0})}s(Q,"startPresenceHeartbeat");function a(e,n){try{e(JSON.stringify({ts:new Date().toISOString(),...n}))}catch{e(`[agent-loop] log_error event=${n.event}`)}}s(a,"structuredLog");function O(e,n){return n.aborted?Promise.resolve(!1):e<=0?Promise.resolve(!0):new Promise(r=>{let l=setTimeout(()=>{n.removeEventListener("abort",c),r(!0)},e),c=s(()=>{clearTimeout(l),n.removeEventListener("abort",c),r(!1)},"onAbort");n.addEventListener("abort",c,{once:!0})})}s(O,"abortableSleep");async function X(e,n){let r=`capabilities=${encodeURIComponent(e.join(","))}&waitMs=${n}`,l=await v(`/api/work/next?${r}`);return l==null||typeof l=="string"?null:l}s(X,"pollForWork");function z(e,n){return{logger:{info:s(r=>n(r),"info"),warn:s(r=>n(r),"warn"),error:s(r=>n(r),"error")},job:{attempts:e}}}s(z,"makeHelpers");async function Y(e,n,r){let l=W[e.kind],c=Date.now();if(a(r,{event:"claim",jobId:e.id,kind:e.kind,attempts:e.attempts}),!l){let o=`unknown kind: ${e.kind}`;a(r,{event:"fail",jobId:e.id,kind:e.kind,terminal:!0,error:o}),await p(`/api/work/${e.id}/fail`,{leaseToken:e.leaseToken,error:o,terminal:!0}).catch(()=>{});return}let i=setInterval(()=>{a(r,{event:"heartbeat",jobId:e.id}),p(`/api/work/${e.id}/heartbeat`,{leaseToken:e.leaseToken}).catch(o=>{a(r,{event:"heartbeat_error",jobId:e.id,error:o instanceof Error?o.message:String(o)})})},n);try{let o=z(e.attempts,r),d=await l(e.payload,o)??{};clearInterval(i),a(r,{event:"complete",jobId:e.id,kind:e.kind,durationMs:Date.now()-c}),await p(`/api/work/${e.id}/complete`,{leaseToken:e.leaseToken,result:d})}catch(o){clearInterval(i);let d=h(o),u=o instanceof Error?o.message:String(o);a(r,{event:"fail",jobId:e.id,kind:e.kind,durationMs:Date.now()-c,terminal:d,error:u}),await p(`/api/work/${e.id}/fail`,{leaseToken:e.leaseToken,error:u,terminal:d}).catch(t=>{a(r,{event:"fail_post_error",jobId:e.id,error:t instanceof Error?t.message:String(t)})})}}s(Y,"runOne");async function we(e){let n=e.log??(()=>{}),r=e.pollWaitMs??U,l=e.heartbeatIntervalMs??K,c=e.capabilities??J(),i=V;a(n,{event:"agent_start",capabilities:c,pollWaitMs:r,heartbeatIntervalMs:l}),Q(c,e.signal,n,e.version),C({signal:e.signal,log:n}).catch(t=>{a(n,{event:"tt_heartbeat_fatal",error:t instanceof Error?t.message:String(t)})});let o=5*6e4,d=0,u=s(()=>{if(!e.readInstalledVersion||!e.version)return!1;let t=Date.now();if(t-d<o)return!1;d=t;let m=e.readInstalledVersion();return!!(m&&m!==e.version)},"versionDrifted");for(;!e.signal.aborted;){if(u()){a(n,{event:"agent_version_drift",bootVersion:e.version,installedVersion:e.readInstalledVersion?.()??null}),e.onVersionDrift?.();break}let t=null;try{t=await X(c,r)}catch(m){let $=m instanceof f?m.statusCode:void 0;if(a(n,{event:"poll_error",status:$,error:m instanceof Error?m.message:String(m)}),!await O(i,e.signal))break;i=Math.min(i*2,B);continue}if(!t){if(a(n,{event:"poll_204"}),!await O(i,e.signal))break;i=Math.min(i*2,B);continue}i=V,await Y(t,l,n)}a(n,{event:"agent_stop"})}s(we,"runAgentLoop");export{W as a,D as b,J as c,X as d,we as e};
1
+ import{c as C}from"./chunk-5XUN743A.js";import{b as S}from"./chunk-BLCMXTIK.js";import{a as M}from"./chunk-KZZ2MUQQ.js";import{a as L}from"./chunk-DGH4FBMM.js";import{a as y}from"./chunk-RSKQRVPJ.js";import{a as H}from"./chunk-HXZM2UHO.js";import{d as _}from"./chunk-PRKJFYVF.js";import{b as R}from"./chunk-YW3JQKGY.js";import{a as T}from"./chunk-RWF75MTD.js";import{a as A}from"./chunk-O2BKBW7Z.js";import{a as E}from"./chunk-KGQ5W54Y.js";import{a as I}from"./chunk-O7PSLZO6.js";import{b as h}from"./chunk-5RBLIVBF.js";import{a as x}from"./chunk-MOAJLSYV.js";import{a as P}from"./chunk-EN43UYBN.js";import{a as N}from"./chunk-FAXV5AAG.js";import{a as k}from"./chunk-UF6US7VU.js";import{j as b}from"./chunk-2RCWYVEU.js";import{d as w}from"./chunk-NTKO4H2K.js";import{b as f,e as v,f as p}from"./chunk-KLEF5D3A.js";import{a as s}from"./chunk-ZLLER3HP.js";var W={process_eval:E,process_insights:I,process_launch:S,process_send_message:y,process_conversation:A,process_session_goal:H,distill_memories:R,memory_ab:M,process_announcement:T,process_run_cleanup:L,cron_suggest_instructions:_,cron_refresh_skills:k,cron_refresh_pricing:N,cron_eval_autorun:P,cron_instruction_evolution:b,process_judge_review:x},D=Object.keys(W),F=new Set(["process_announcement","process_run_cleanup","memory_ab"]);function J(e=process.env){return e.DATABASE_URL?D:D.filter(n=>!F.has(n))}s(J,"availableCapabilities");var U=3e4,K=3e4,G=3e4,V=250,B=5e3,q=`thin-agent-${process.pid}`,g=null;function Q(e,n,r,l){let c;try{let d=w();c={claude:d.claudeBin!=null,codex:d.codexBin!=null,codexModel:d.codexConfiguredModel}}catch{}let i=s(d=>{p("/api/workers/heartbeat",{workerType:"cli-worker",clientName:q,clientVersion:l,workerVersion:"0.1.0",currentJobId:null,inFlightCount:0,lastError:null,status:d,metadata:{capabilities:e,mode:"thin-agent",llmEngines:c}}).then(u=>{let t=u?.advisory;t&&t.message!==g?(g=t.message,a(r,{event:"worker_advisory",code:t.code,message:t.message})):t||(g=null)}).catch(u=>{a(r,{event:"presence_heartbeat_error",error:u instanceof Error?u.message:String(u)})})},"send");i("alive");let o=setInterval(()=>i("alive"),G);n.addEventListener("abort",()=>{clearInterval(o),i("shutting_down")},{once:!0})}s(Q,"startPresenceHeartbeat");function a(e,n){try{e(JSON.stringify({ts:new Date().toISOString(),...n}))}catch{e(`[agent-loop] log_error event=${n.event}`)}}s(a,"structuredLog");function O(e,n){return n.aborted?Promise.resolve(!1):e<=0?Promise.resolve(!0):new Promise(r=>{let l=setTimeout(()=>{n.removeEventListener("abort",c),r(!0)},e),c=s(()=>{clearTimeout(l),n.removeEventListener("abort",c),r(!1)},"onAbort");n.addEventListener("abort",c,{once:!0})})}s(O,"abortableSleep");async function X(e,n){let r=`capabilities=${encodeURIComponent(e.join(","))}&waitMs=${n}`,l=await v(`/api/work/next?${r}`);return l==null||typeof l=="string"?null:l}s(X,"pollForWork");function z(e,n){return{logger:{info:s(r=>n(r),"info"),warn:s(r=>n(r),"warn"),error:s(r=>n(r),"error")},job:{attempts:e}}}s(z,"makeHelpers");async function Y(e,n,r){let l=W[e.kind],c=Date.now();if(a(r,{event:"claim",jobId:e.id,kind:e.kind,attempts:e.attempts}),!l){let o=`unknown kind: ${e.kind}`;a(r,{event:"fail",jobId:e.id,kind:e.kind,terminal:!0,error:o}),await p(`/api/work/${e.id}/fail`,{leaseToken:e.leaseToken,error:o,terminal:!0}).catch(()=>{});return}let i=setInterval(()=>{a(r,{event:"heartbeat",jobId:e.id}),p(`/api/work/${e.id}/heartbeat`,{leaseToken:e.leaseToken}).catch(o=>{a(r,{event:"heartbeat_error",jobId:e.id,error:o instanceof Error?o.message:String(o)})})},n);try{let o=z(e.attempts,r),d=await l(e.payload,o)??{};clearInterval(i),a(r,{event:"complete",jobId:e.id,kind:e.kind,durationMs:Date.now()-c}),await p(`/api/work/${e.id}/complete`,{leaseToken:e.leaseToken,result:d})}catch(o){clearInterval(i);let d=h(o),u=o instanceof Error?o.message:String(o);a(r,{event:"fail",jobId:e.id,kind:e.kind,durationMs:Date.now()-c,terminal:d,error:u}),await p(`/api/work/${e.id}/fail`,{leaseToken:e.leaseToken,error:u,terminal:d}).catch(t=>{a(r,{event:"fail_post_error",jobId:e.id,error:t instanceof Error?t.message:String(t)})})}}s(Y,"runOne");async function we(e){let n=e.log??(()=>{}),r=e.pollWaitMs??U,l=e.heartbeatIntervalMs??K,c=e.capabilities??J(),i=V;a(n,{event:"agent_start",capabilities:c,pollWaitMs:r,heartbeatIntervalMs:l}),Q(c,e.signal,n,e.version),C({signal:e.signal,log:n}).catch(t=>{a(n,{event:"tt_heartbeat_fatal",error:t instanceof Error?t.message:String(t)})});let o=5*6e4,d=0,u=s(()=>{if(!e.readInstalledVersion||!e.version)return!1;let t=Date.now();if(t-d<o)return!1;d=t;let m=e.readInstalledVersion();return!!(m&&m!==e.version)},"versionDrifted");for(;!e.signal.aborted;){if(u()){a(n,{event:"agent_version_drift",bootVersion:e.version,installedVersion:e.readInstalledVersion?.()??null}),e.onVersionDrift?.();break}let t=null;try{t=await X(c,r)}catch(m){let $=m instanceof f?m.statusCode:void 0;if(a(n,{event:"poll_error",status:$,error:m instanceof Error?m.message:String(m)}),!await O(i,e.signal))break;i=Math.min(i*2,B);continue}if(!t){if(a(n,{event:"poll_204"}),!await O(i,e.signal))break;i=Math.min(i*2,B);continue}i=V,await Y(t,l,n)}a(n,{event:"agent_stop"})}s(we,"runAgentLoop");export{W as a,D as b,J as c,X as d,we as e};
@@ -1,4 +1,4 @@
1
- import{a as S,b as z,c as T}from"./chunk-QFVGUZDO.js";import{a as j}from"./chunk-5RBLIVBF.js";import{a as O}from"./chunk-5R5RGKOW.js";import{c as A,d as C,f as b}from"./chunk-B3BHB26P.js";import{e as _,f as I,h as u}from"./chunk-KLEF5D3A.js";import{a as $}from"./chunk-ZLLER3HP.js";async function D(f,m){let{mirrorId:o,projectPath:s,projectId:i,config:p}=f,e=$(n=>m.logger.info(n),"log");if(p?.sessionId)return M({mirrorId:o,sessionId:p.sessionId},e);e(`Processing insights job ${o}...`),await u(`/api/insights-jobs/${o}/progress`,{status:"running",progress:{step:"reading_data"}});try{let{repaired:n}=await I("/api/sessions/repair-analyzed-at",{});n>0&&e(` Repaired analyzed_at on ${n} orphan session(s).`)}catch(n){e(` Warning: analyzed_at repair failed: ${n instanceof Error?n.message:String(n)}`)}let a=await J(s,i);if(!a)throw new j("No session data found \u2014 ensure sessions are captured and enriched.");e(` Found ${a.stats.sessions} sessions, generating recommendations...`);let w=20,c=200;if(C()!=="none"){let n=0,t=0;try{for(;n<c;){let l=await _(`/api/sessions?hasAnalysis=false&limit=${w}&offset=${t}`);if(l.length===0)break;e(` Generating facets for ${l.length} un-analyzed sessions (drained ${n} so far)...`);for(let g of l){if(n>=c)break;try{let d=await _(`/api/sessions/${g.id}/events?limit=100`);if(d.length<2){n++,t++;continue}let P=d.filter(h=>h.eventType==="user_message"||h.eventType==="human").map(h=>h.content?.slice(0,200)??"").filter(Boolean).join(`
1
+ import{a as S,b as z,c as T}from"./chunk-QFVGUZDO.js";import{a as O}from"./chunk-5R5RGKOW.js";import{a as j}from"./chunk-5RBLIVBF.js";import{c as A,d as C,f as b}from"./chunk-B3BHB26P.js";import{e as _,f as I,h as u}from"./chunk-KLEF5D3A.js";import{a as $}from"./chunk-ZLLER3HP.js";async function D(f,m){let{mirrorId:o,projectPath:s,projectId:i,config:p}=f,e=$(n=>m.logger.info(n),"log");if(p?.sessionId)return M({mirrorId:o,sessionId:p.sessionId},e);e(`Processing insights job ${o}...`),await u(`/api/insights-jobs/${o}/progress`,{status:"running",progress:{step:"reading_data"}});try{let{repaired:n}=await I("/api/sessions/repair-analyzed-at",{});n>0&&e(` Repaired analyzed_at on ${n} orphan session(s).`)}catch(n){e(` Warning: analyzed_at repair failed: ${n instanceof Error?n.message:String(n)}`)}let a=await J(s,i);if(!a)throw new j("No session data found \u2014 ensure sessions are captured and enriched.");e(` Found ${a.stats.sessions} sessions, generating recommendations...`);let w=20,c=200;if(C()!=="none"){let n=0,t=0;try{for(;n<c;){let l=await _(`/api/sessions?hasAnalysis=false&limit=${w}&offset=${t}`);if(l.length===0)break;e(` Generating facets for ${l.length} un-analyzed sessions (drained ${n} so far)...`);for(let g of l){if(n>=c)break;try{let d=await _(`/api/sessions/${g.id}/events?limit=100`);if(d.length<2){n++,t++;continue}let P=d.filter(h=>h.eventType==="user_message"||h.eventType==="human").map(h=>h.content?.slice(0,200)??"").filter(Boolean).join(`
2
2
  ---
3
3
  `);if(!P){n++,t++;continue}let E=await b(T,P,4096);if(E){let h=d.filter(R=>R.eventType==="user_message"||R.eventType==="human").length;await u(`/api/sessions/${g.id}/enrich`,{analysis:{source:"generated_facets",...E},analyzedEventCount:d.length,analyzedTurnCount:h}),e(` Generated facets for session ${g.id} (${g.tool})`)}else t++;n++}catch(d){e(` Failed to generate facets for session ${g.id}: ${d instanceof Error?d.message:String(d)}`),n++,t++}}if(l.length<w)break}}catch(l){e(` Warning: facet generation failed after ${n} sessions: ${l instanceof Error?l.message:String(l)}`)}}let r={},y=S.length+1;for(let n=0;n<S.length;n++){let t=S[n];e(` [${n+1}/${y}] Generating ${t.name}...`);try{await u(`/api/insights-jobs/${o}/progress`,{status:"running",progress:{step:t.name,current:n+1,total:y,partial:{...r}}})}catch(g){e(` Warning: progress update failed for ${t.name}: ${g instanceof Error?g.message:String(g)}`)}e(` Running LLM prompt for ${t.name}...`);let l=await b(t.prompt,a.summary,t.maxTokens);l?(r[t.name]=l,e(` Got result for ${t.name}`)):e(` No result for ${t.name} (LLM returned null)`)}e(` [${y}/${y}] Generating at_a_glance...`),await u(`/api/insights-jobs/${o}/progress`,{status:"running",progress:{step:"at_a_glance",current:y,total:y,partial:{...r}}});let N=[a.summary,r.what_works?`
4
4
  ## What Works
@@ -0,0 +1 @@
1
+ import{b as x,c as M}from"./chunk-5R5RGKOW.js";import{b as L}from"./chunk-GIRPEMTW.js";import{a as E}from"./chunk-MODXEGCU.js";import{d as A,f as N}from"./chunk-B3BHB26P.js";import{e as m,f as j}from"./chunk-KLEF5D3A.js";import{a as d}from"./chunk-ZLLER3HP.js";import{readFileSync as J,realpathSync as F}from"node:fs";import P from"node:path";import _ from"node:os";function B(s){let o=P.resolve(s);if(o===P.resolve(_.homedir()))return!1;let a=P.parse(o).root;if(o===a)return!1;try{let n=F(_.tmpdir());if(F(o)===n)return!1}catch{}return!0}d(B,"isScorableProjectPath");var D=5,X=Number(process.env.RULEMETRIC_MAX_SUGGESTION_PROJECTS??10),V=48,z=.5,C=400,K=3,W=.6,Y=1;function q(s){let o=s.bloated??[],a=new Set([...s.harmful.map(n=>n.id),...s.candidates.map(n=>n.id)]);return o.filter(n=>!a.has(n.id)).slice(0,Y).map(n=>({instructionId:n.id,estimatedTokens:n.estimatedTokens,topProjectId:n.topProjectId??null,score:.55,reason:`Costs ~${n.estimatedTokens} tokens every session and measures neutral across ${n.exposures} exposed session(s) \u2014 enough data to detect an effect, and none found. Consider shortening "${n.name}" rather than removing it.`+(n.containsSafetyLanguage?" CAUTION: it contains guardrail language (destructive-command or credential rules) \u2014 preserve those lines when shortening.":"")}))}d(q,"buildTrimProposals");function Q(s){let o=[];for(let n of s.harmful){let l=n.verdict.delta;o.push({instructionId:n.id,score:Math.min(.95,.75+Math.abs(l)),topProjectId:n.topProjectId??null,reason:`Measured harmful: sessions using "${n.name}" scored ${(l*100).toFixed(1)}pp worse across ${n.exposures} exposed session(s). Observational \u2014 review before archiving.`})}let a=new Set(s.harmful.map(n=>n.id));for(let n of s.candidates)a.has(n.id)||o.push({instructionId:n.id,score:W,topProjectId:n.topProjectId??null,reason:`Unused: "${n.name}" is ${n.reason} (${n.totalExposures} lifetime exposure(s)) but still costs context budget every session.`});return o.slice(0,K)}d(Q,"buildRemovalProposals");async function Z(){let s=P.join(_.homedir(),".config","rulemetric","skills-registry.json");try{let o=J(s,"utf-8"),a=JSON.parse(o);return Date.now()-new Date(a.generatedAt).getTime()>V*60*60*1e3}catch{return!0}}d(Z,"checkSkillsRegistryStale");var ct=d(async(s,o)=>{let a=A();if(a==="none"){o.logger.warn("No LLM backend available (claude CLI missing and ANTHROPIC_API_KEY unset); skipping suggestion compute");return}o.logger.info(`Scoring backend: ${a}`);let n;try{n=(await m("/api/sessions/project-paths?limit="+X)).projectPaths}catch(t){o.logger.warn(`Failed to fetch project paths: ${t instanceof Error?t.message:String(t)}`);return}if(n.length===0){o.logger.info("No recent project paths; nothing to score");return}let l=new Map;try{let t=await m("/api/projects?limit=200");for(let e of t.projects??[])e.primaryCheckoutPath&&l.set(E(e.primaryCheckoutPath),e.id)}catch(t){o.logger.warn(`Failed to fetch projects for id resolution: ${t instanceof Error?t.message:String(t)}`)}let w=new Map;try{let t=await m(`/api/catalog?limit=200&contentPreview=${C}`);for(let e of t)w.set(e.id,{id:e.id,name:e.name,description:e.description??"",tags:e.tags??[],contentPreview:(e.contentPreview??"").slice(0,C)})}catch(t){o.logger.warn(`Failed to fetch catalog: ${t instanceof Error?t.message:String(t)}`)}try{let t=await m("/api/instructions?limit=100");for(let e of t.instructions??[])w.has(e.id)||w.set(e.id,{id:e.id,name:e.name,description:e.description??"",tags:e.tags??[],contentPreview:(e.content??"").slice(0,C)})}catch(t){o.logger.warn(`Failed to fetch personal instructions: ${t instanceof Error?t.message:String(t)}`)}let f=[],g=[];try{let t=await m("/api/insights/groom-candidates");if(!t.captureHealthy)o.logger.info(`Grooming paused: ${t.reason??"capture unhealthy"}`);else{f=Q(t),g=q(t);let e=t.safetyGuarded+t.harmfulSafetyGuarded;o.logger.info(`Removal proposals: ${f.length} (${t.harmful.length} measured-harmful, ${t.candidates.length} never-used, ${e} withheld by the safety allowlist); trim proposals: ${g.length} (${(t.bloated??[]).length} measured-neutral and expensive, ${t.trimSafetyFlagged??0} flagged as containing guardrail language)`)}}catch(t){o.logger.warn(`Failed to fetch groom candidates: ${t instanceof Error?t.message:String(t)}`)}let R=[...w.values()];if(R.length===0&&f.length===0&&g.length===0){o.logger.info("No candidate instructions and nothing to retire; nothing to score");return}o.logger.info(`Scoring ${R.length} candidates across ${n.length} project(s)`);let T=0,c=null,$=new Set;for(let t of n)try{let e=E(t);if(!B(e)){o.logger.info(`Skipping ${e}: not a project directory (home/root)`);continue}let h=L(e);if(h.length===0){o.logger.info(`Skipping ${e}: insufficient language signals`);continue}let G={name:P.basename(e),description:null,languages:h,topics:[],dependencies:[]},I=M(R);o.logger.info(`Scoring ${R.length} candidates for ${e} in ${I.length} batch(es)`);let b=[],y=0;for(let r of I)try{let i=await N(x(G,r),"",4096);if(!i){y++;continue}let v=i.recommendations??[];for(let p of v)typeof p.instructionId=="string"&&typeof p.score=="number"&&typeof p.reason=="string"&&b.push({instructionId:p.instructionId,score:p.score,reason:p.reason})}catch(i){y++,o.logger.warn(`Batch failed for ${e}: ${i instanceof Error?i.message:String(i)}`)}y>0&&o.logger.warn(`${y}/${I.length} batch(es) failed for ${e} (backend ${a}); suggestions are partial`),b.length===0&&o.logger.warn(`No usable LLM output for ${e} (backend ${a})`);let U=b.filter(r=>r.score>=z).sort((r,i)=>i.score-r.score).slice(0,D),k=l.get(e),H=c===null||c===e;c===null&&(c=e);let O=d(r=>r.topProjectId?r.topProjectId===k:H,"placeHere"),u=[...U.map(r=>({instructionId:r.instructionId,score:r.score,reason:r.reason,kind:"add"})),...f.filter(O).map(({topProjectId:r,...i})=>({...i,kind:"remove"})),...g.filter(O).map(({estimatedTokens:r,topProjectId:i,...v})=>({...v,kind:"trim"}))];if(u.length===0){o.logger.info(`Nothing to suggest for ${e}`);continue}await j("/api/instruction-suggestions/batch-upsert",{projectPath:e,...k?{projectId:k}:{},suggestions:u}),o.logger.info(`${e}: ${u.filter(r=>r.kind==="add").length} add + ${u.filter(r=>r.kind==="remove").length} remove + ${u.filter(r=>r.kind==="trim").length} trim`);for(let r of u)r.kind!=="add"&&$.add(r.instructionId);T++}catch(e){o.logger.warn(`Failed to score ${t}: ${e instanceof Error?e.message:String(e)}`)}let S=[...f.filter(t=>!$.has(t.instructionId)),...g.filter(t=>!$.has(t.instructionId)).map(({estimatedTokens:t,...e})=>e)];if(S.length>0&&c)try{let t=new Set(g.map(e=>e.instructionId));await j("/api/instruction-suggestions/batch-upsert",{projectPath:c,...l.get(c)?{projectId:l.get(c)}:{},suggestions:S.map(({topProjectId:e,...h})=>({...h,kind:t.has(h.instructionId)?"trim":"remove"}))}),o.logger.info(`Orphan sweep: ${S.length} proposal(s) whose project was not scored this run placed on ${c}`)}catch(t){o.logger.warn(`Orphan sweep failed: ${t instanceof Error?t.message:String(t)}`)}if(await Z())try{await j("/api/instruction-suggestions/mark-stale",{}),o.logger.warn("Skills registry is stale (>48h); marked all suggestions stale")}catch{}o.logger.info(`Done: scored ${T}/${n.length} projects`)},"cronSuggestInstructions");export{B as a,q as b,Q as c,ct as d};
@@ -1,2 +1,2 @@
1
- import{b as B}from"./chunk-N7TGRFVZ.js";import{a as v,f as d,g as n,h as m,i as U}from"./chunk-45DOTNQM.js";import{a as R}from"./chunk-5RBLIVBF.js";import{a as $}from"./chunk-ZLLER3HP.js";import{and as L,asc as j,eq as l,gt as q,isNotNull as F,sql as O}from"drizzle-orm";var _=100,C=10;async function G(I,s={}){let t=s.db??U(),D=s.sendEmail??B,p=s.log??(o=>process.stderr.write(`[process_announcement] ${o}
1
+ import{b as B}from"./chunk-N7TGRFVZ.js";import{a as v,f as d,g as n,h as m,i as U}from"./chunk-7G6T5C7J.js";import{a as R}from"./chunk-5RBLIVBF.js";import{a as $}from"./chunk-ZLLER3HP.js";import{and as L,asc as j,eq as l,gt as q,isNotNull as F,sql as O}from"drizzle-orm";var _=100,C=10;async function G(I,s={}){let t=s.db??U(),D=s.sendEmail??B,p=s.log??(o=>process.stderr.write(`[process_announcement] ${o}
2
2
  `)),b=s.webBaseUrl??process.env.RULEMETRIC_WEB_URL??process.env.WEB_URL??"https://rulemetric.com",{announcementId:r}=I,[i]=await t.select().from(d).where(l(d.id,r)).limit(1);if(!i)throw new R(`Announcement ${r} not found`);if(i.status!=="queued"&&i.status!=="sending")throw new R(`Announcement ${r} is in status='${i.status}'; expected 'queued' or 'sending'.`);await t.update(d).set({status:"sending",updatedAt:new Date}).where(l(d.id,r)),p(`Sending announcement ${r} (${i.subject??""})`);let w=0,f=0,h=0,y=0,k=null;try{for(;;){let c=await t.select({userId:m.userId,email:v.email,displayName:v.displayName,unsubscribeToken:m.unsubscribeToken}).from(m).innerJoin(v,l(v.id,m.userId)).where(L(l(m.productAnnouncements,!0),F(v.email),k?q(m.userId,k):void 0)).orderBy(j(m.userId)).limit(_);if(c.length===0)break;k=c[c.length-1].userId;for(let A=0;A<c.length;A+=C){let P=c.slice(A,A+C),S=await Promise.allSettled(P.map(g=>W({recipient:g,announcement:i,webBaseUrl:b,sendEmail:D,db:t})));for(let g=0;g<S.length;g++){let u=S[g];if(u.status==="fulfilled")u.value.ok==="sent"?w++:u.value.ok==="skipped"?h++:(f++,u.value.provider==="noop"&&y++,p(` recipient ${P[g].userId}: send failed \u2014 ${u.value.error}`));else{f++;let T=u.reason instanceof Error?u.reason.message:String(u.reason);p(` recipient ${P[g].userId}: send failed \u2014 ${T}`)}}}if(c.length<_)break}y>0&&p(`WARNING: ${y} recipient(s) hit the noop email provider and were recorded as FAILED \u2014 no email provider is configured on this worker (set RESEND_API_KEY in ~/.config/rulemetric/env and reinstall the service)`);let o=await t.select({status:n.status,count:O`count(*)::int`}).from(n).where(l(n.announcementId,r)).groupBy(n.status),e={};for(let c of o)e[c.status]=c.count;let a=e.sent??0,E=e.failed??0,N=a===0&&E>0?"failed":"sent",x=E>0?`${E} of ${a+E} recipient(s) failed; see announcement_deliveries`:null;return await t.update(d).set({status:N,recipientCount:a,...N==="sent"?{sentAt:new Date}:{},error:x,updatedAt:new Date}).where(l(d.id,r)),p(`Done: status=${N} sent=${a} failed=${E} (this attempt: sent=${w} failed=${f} skipped=${h})`),{sent:w,failed:f,skipped:h}}catch(o){let e=o instanceof Error?o.message:String(o);throw await t.update(d).set({status:"failed",error:e.slice(0,1e3),updatedAt:new Date}).where(l(d.id,r)).catch(()=>{}),o}}$(G,"processAnnouncement");function K(I){return I.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}$(K,"escapeHtml");async function W(I){let{recipient:s,announcement:t,webBaseUrl:D,sendEmail:p,db:b}=I;if(!s.email)return{ok:"skipped",reason:"no-email"};let r=await b.insert(n).values({announcementId:t.id,userId:s.userId,email:s.email,status:"pending"}).onConflictDoNothing({target:[n.announcementId,n.userId]}).returning({id:n.id});if(r.length===0)return{ok:"skipped",reason:"already-claimed"};let i=r[0].id,w=D.replace(/\/$/,""),f=encodeURIComponent(s.unsubscribeToken),h=`${w}/unsubscribe/${f}`,y=s.displayName?.trim().split(/\s+/)[0]||"there",k=t.htmlBody.replaceAll("{{unsubscribe_url}}",h).replaceAll("{{recipient_name}}",K(y)),o=t.textBody.replaceAll("{{unsubscribe_url}}",h).replaceAll("{{recipient_name}}",y);try{let e=await p({to:s.email,subject:t.subject,html:k,text:o,fromName:"RuleMetric",idempotencyKey:i,headers:{"List-Unsubscribe":`<${w}/api/unsubscribe/${f}>`,"List-Unsubscribe-Post":"List-Unsubscribe=One-Click"}});if(e.provider==="noop"){let a="no email provider configured (RESEND_API_KEY unset on the worker)";return await b.update(n).set({status:"failed",error:a}).where(l(n.id,i)),{ok:"failed",error:a,provider:e.provider}}return await b.update(n).set({status:"sent",providerId:e.id,sentAt:new Date}).where(l(n.id,i)),{ok:"sent",providerId:e.id,provider:e.provider}}catch(e){let a=e instanceof Error?e.message:String(e);return await b.update(n).set({status:"failed",error:a.slice(0,1e3)}).where(l(n.id,i)).catch(()=>{}),{ok:"failed",error:a}}}$(W,"sendOne");export{G as a};
@@ -1 +1 @@
1
- import{b as T}from"./chunk-ZXF5NE54.js";import{d as l,e as s,h as E}from"./chunk-NJ5UED3H.js";import{a as g}from"./chunk-ZLLER3HP.js";import{useState as a}from"react";import{Box as c,Text as r,useInput as _}from"ink";import L from"ink-text-input";import G from"ink-select-input";import{jsx as t,jsxs as m}from"react/jsx-runtime";var p=["tool","project","mode","prompt","submit"];function U({launchers:f,defaultProjectPath:w,defaultTool:A,defaultPrompt:D,defaultResumeSessionId:v,focused:i,onSubmit:R}){let[b,C]=a(A??f[0]?.tool??"claude_code"),[u,M]=a(w),[P,O]=a("interactive"),[d,S]=a(D??""),[o,F]=a("tool"),[j,I]=a(!1),[y,h]=a(null),B=d.trim().length>0&&u.trim().length>0&&!j;_((e,x)=>{if(i)if(x.upArrow){let n=p.indexOf(o);n>0&&F(p[n-1])}else if(x.downArrow){let n=p.indexOf(o);n<p.length-1&&F(p[n+1])}else x.return&&o==="submit"&&B?N():o==="mode"&&(e===" "||x.return)&&O(n=>n==="interactive"?"headless":"interactive")});async function N(){I(!0),h(null);try{await R({tool:b,config:{projectPath:u,prompt:d,mode:P,...v?{resumeSessionId:v}:{}}}),S(""),h(null)}catch(e){h(e instanceof Error?e.message:String(e))}finally{I(!1)}}return g(N,"doSubmit"),m(c,{flexDirection:"column",paddingX:1,children:[t(r,{bold:!0,color:l,children:"\u25BC New launch"}),m(c,{children:[t(r,{color:o==="tool"&&i?l:s,children:" Tool: "}),o==="tool"&&i?t(G,{items:f.map(e=>({label:T(e.tool),value:e.tool})),initialIndex:Math.max(0,f.findIndex(e=>e.tool===b)),onSelect:e=>C(e.value)}):t(r,{children:T(b)})]}),m(c,{children:[t(r,{color:o==="project"&&i?l:s,children:" Project: "}),o==="project"&&i?t(L,{value:u,onChange:M}):t(r,{children:u})]}),m(c,{children:[t(r,{color:o==="mode"&&i?l:s,children:" Mode: "}),t(r,{children:P==="interactive"?"(\u2022) interactive ( ) headless":"( ) interactive (\u2022) headless"})]}),m(c,{children:[t(r,{color:o==="prompt"&&i?l:s,children:" Prompt: "}),o==="prompt"&&i?t(L,{value:d,onChange:S}):t(r,{children:d||"(empty)"})]}),t(c,{marginTop:1,children:m(r,{color:o==="submit"&&i?l:s,children:[B?" [ Submit ]":" [ Submit (disabled) ]",j?" \u2026submitting":""]})}),y&&m(r,{color:E,children:[" \u2717 ",y]})]})}g(U,"NewLaunchForm");export{U as a};
1
+ import{d as l,e as s,h as E}from"./chunk-NJ5UED3H.js";import{b as T}from"./chunk-ZXF5NE54.js";import{a as g}from"./chunk-ZLLER3HP.js";import{useState as a}from"react";import{Box as c,Text as r,useInput as _}from"ink";import L from"ink-text-input";import G from"ink-select-input";import{jsx as t,jsxs as m}from"react/jsx-runtime";var p=["tool","project","mode","prompt","submit"];function U({launchers:f,defaultProjectPath:w,defaultTool:A,defaultPrompt:D,defaultResumeSessionId:v,focused:i,onSubmit:R}){let[b,C]=a(A??f[0]?.tool??"claude_code"),[u,M]=a(w),[P,O]=a("interactive"),[d,S]=a(D??""),[o,F]=a("tool"),[j,I]=a(!1),[y,h]=a(null),B=d.trim().length>0&&u.trim().length>0&&!j;_((e,x)=>{if(i)if(x.upArrow){let n=p.indexOf(o);n>0&&F(p[n-1])}else if(x.downArrow){let n=p.indexOf(o);n<p.length-1&&F(p[n+1])}else x.return&&o==="submit"&&B?N():o==="mode"&&(e===" "||x.return)&&O(n=>n==="interactive"?"headless":"interactive")});async function N(){I(!0),h(null);try{await R({tool:b,config:{projectPath:u,prompt:d,mode:P,...v?{resumeSessionId:v}:{}}}),S(""),h(null)}catch(e){h(e instanceof Error?e.message:String(e))}finally{I(!1)}}return g(N,"doSubmit"),m(c,{flexDirection:"column",paddingX:1,children:[t(r,{bold:!0,color:l,children:"\u25BC New launch"}),m(c,{children:[t(r,{color:o==="tool"&&i?l:s,children:" Tool: "}),o==="tool"&&i?t(G,{items:f.map(e=>({label:T(e.tool),value:e.tool})),initialIndex:Math.max(0,f.findIndex(e=>e.tool===b)),onSelect:e=>C(e.value)}):t(r,{children:T(b)})]}),m(c,{children:[t(r,{color:o==="project"&&i?l:s,children:" Project: "}),o==="project"&&i?t(L,{value:u,onChange:M}):t(r,{children:u})]}),m(c,{children:[t(r,{color:o==="mode"&&i?l:s,children:" Mode: "}),t(r,{children:P==="interactive"?"(\u2022) interactive ( ) headless":"( ) interactive (\u2022) headless"})]}),m(c,{children:[t(r,{color:o==="prompt"&&i?l:s,children:" Prompt: "}),o==="prompt"&&i?t(L,{value:d,onChange:S}):t(r,{children:d||"(empty)"})]}),t(c,{marginTop:1,children:m(r,{color:o==="submit"&&i?l:s,children:[B?" [ Submit ]":" [ Submit (disabled) ]",j?" \u2026submitting":""]})}),y&&m(r,{color:E,children:[" \u2717 ",y]})]})}g(U,"NewLaunchForm");export{U as a};
@@ -1,2 +1,2 @@
1
- import{a as v,b as u,e as y,g as d}from"../../chunk-IQCE4VBP.js";import{a as h}from"../../chunk-LWI5K6T4.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-6VKQT2J3.js";import"../../chunk-NIRD7ETU.js";import"../../chunk-QY3UKLDE.js";import"../../chunk-3AV3GTMP.js";import"../../chunk-KLEF5D3A.js";import"../../chunk-JZ5Z2BRO.js";import{a as p}from"../../chunk-ZLLER3HP.js";import{Args as k,Flags as o}from"@oclif/core";import{existsSync as T}from"node:fs";import{homedir as P}from"node:os";import{join as I}from"node:path";var A=I(P(),".gemini","antigravity-ide","brain"),g=class x extends h{static{p(this,"AntigravityBackfill")}static description="Backfill historical events from an Antigravity conversation transcript into a RuleMetric session. Useful for seeding a conversation that existed before hooks were installed \u2014 the live hook intentionally only captures forward.";static examples=["<%= config.bin %> antigravity backfill 26fd215d-f43b-4ea5-b177-dc2c0e696f97 --session 158db9aa-68ee-43fc-961b-f3a180578694","<%= config.bin %> antigravity backfill 26fd215d-f43b-4ea5-b177-dc2c0e696f97 --dry-run"];static args={conversationId:k.string({description:"Antigravity conversationId (UUID) \u2014 the directory name under ~/.gemini/antigravity-ide/brain/",required:!0})};static flags={session:o.string({char:"s",description:"RuleMetric session UUID to POST events into. If omitted, resolved from the hook tmp file ($TMPDIR/rulemetric/<conversationId>) \u2014 fails if neither is present."}),transcript:o.string({description:"Path to the transcript.jsonl file. Defaults to ~/.gemini/antigravity-ide/brain/<conversationId>/.system_generated/logs/transcript.jsonl"}),"after-step":o.integer({description:"Only emit records with step_index > this value. Default: read from existing state file, else -1 (everything)."}),limit:o.integer({description:"Cap on the number of records to process this run."}),"dry-run":o.boolean({default:!1,description:"Classify records without POSTing. Reports counts only."}),"save-state":o.boolean({default:!0,allowNo:!0,description:"After backfill, persist the highest step_index so the live hook resumes from there."})};async run(){let{args:b,flags:e}=await this.parse(x),t=b.conversationId;d.loadEnvFile(),process.env.RULEMETRIC_API_URL||this.error("RULEMETRIC_API_URL is not set. Configure it via env or ~/.config/rulemetric/env.");let l=e.transcript??I(A,t,".system_generated","logs","transcript.jsonl");T(l)||this.error(`Transcript not found: ${l}`);let m=e.session??d.resolveRwSessionId(t);m||this.error(`No RuleMetric session resolved. Pass --session <uuid>, or run the Antigravity hook at least once so $TMPDIR/rulemetric/${t} is populated.`);let n=e["after-step"];n===void 0&&(n=d.load(t)?.lastStepIdx??-1);let i=v(l,n);e.limit!==void 0&&i.length>e.limit&&(i=i.slice(0,e.limit));let R=u(l);if(this.log(`Conversation ${t}: transcript max step = ${R}, after-step = ${n}, records to process = ${i.length}`),i.length===0){this.log("Nothing to backfill.");return}if(e["dry-run"]){let r=0,a=0,c={};for(let S of i){let f=(await import("../../lib/antigravity-transcript.js")).classifyRecord(S,0);f?(r++,c[f.eventType]=(c[f.eventType]??0)+1):a++}this.log(`Dry run: would emit ${r}, skip ${a}. By eventType: ${JSON.stringify(c)}`);return}let w=Date.now(),s=await y(i,m,t,n,{onProgress:p(({attempted:r,total:a})=>{(r%100===0||r===a)&&process.stderr.write(` \u2026${r}/${a}
1
+ import{a as v,b as u,e as y,g as d}from"../../chunk-IQCE4VBP.js";import{a as h}from"../../chunk-2DXBC2JQ.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-NIRD7ETU.js";import"../../chunk-6VKQT2J3.js";import"../../chunk-QY3UKLDE.js";import"../../chunk-3AV3GTMP.js";import"../../chunk-KLEF5D3A.js";import"../../chunk-JZ5Z2BRO.js";import{a as p}from"../../chunk-ZLLER3HP.js";import{Args as k,Flags as o}from"@oclif/core";import{existsSync as T}from"node:fs";import{homedir as P}from"node:os";import{join as I}from"node:path";var A=I(P(),".gemini","antigravity-ide","brain"),g=class x extends h{static{p(this,"AntigravityBackfill")}static description="Backfill historical events from an Antigravity conversation transcript into a RuleMetric session. Useful for seeding a conversation that existed before hooks were installed \u2014 the live hook intentionally only captures forward.";static examples=["<%= config.bin %> antigravity backfill 26fd215d-f43b-4ea5-b177-dc2c0e696f97 --session 158db9aa-68ee-43fc-961b-f3a180578694","<%= config.bin %> antigravity backfill 26fd215d-f43b-4ea5-b177-dc2c0e696f97 --dry-run"];static args={conversationId:k.string({description:"Antigravity conversationId (UUID) \u2014 the directory name under ~/.gemini/antigravity-ide/brain/",required:!0})};static flags={session:o.string({char:"s",description:"RuleMetric session UUID to POST events into. If omitted, resolved from the hook tmp file ($TMPDIR/rulemetric/<conversationId>) \u2014 fails if neither is present."}),transcript:o.string({description:"Path to the transcript.jsonl file. Defaults to ~/.gemini/antigravity-ide/brain/<conversationId>/.system_generated/logs/transcript.jsonl"}),"after-step":o.integer({description:"Only emit records with step_index > this value. Default: read from existing state file, else -1 (everything)."}),limit:o.integer({description:"Cap on the number of records to process this run."}),"dry-run":o.boolean({default:!1,description:"Classify records without POSTing. Reports counts only."}),"save-state":o.boolean({default:!0,allowNo:!0,description:"After backfill, persist the highest step_index so the live hook resumes from there."})};async run(){let{args:b,flags:e}=await this.parse(x),t=b.conversationId;d.loadEnvFile(),process.env.RULEMETRIC_API_URL||this.error("RULEMETRIC_API_URL is not set. Configure it via env or ~/.config/rulemetric/env.");let l=e.transcript??I(A,t,".system_generated","logs","transcript.jsonl");T(l)||this.error(`Transcript not found: ${l}`);let m=e.session??d.resolveRwSessionId(t);m||this.error(`No RuleMetric session resolved. Pass --session <uuid>, or run the Antigravity hook at least once so $TMPDIR/rulemetric/${t} is populated.`);let n=e["after-step"];n===void 0&&(n=d.load(t)?.lastStepIdx??-1);let i=v(l,n);e.limit!==void 0&&i.length>e.limit&&(i=i.slice(0,e.limit));let R=u(l);if(this.log(`Conversation ${t}: transcript max step = ${R}, after-step = ${n}, records to process = ${i.length}`),i.length===0){this.log("Nothing to backfill.");return}if(e["dry-run"]){let r=0,a=0,c={};for(let S of i){let f=(await import("../../lib/antigravity-transcript.js")).classifyRecord(S,0);f?(r++,c[f.eventType]=(c[f.eventType]??0)+1):a++}this.log(`Dry run: would emit ${r}, skip ${a}. By eventType: ${JSON.stringify(c)}`);return}let w=Date.now(),s=await y(i,m,t,n,{onProgress:p(({attempted:r,total:a})=>{(r%100===0||r===a)&&process.stderr.write(` \u2026${r}/${a}
2
2
  `)},"onProgress")}),$=((Date.now()-w)/1e3).toFixed(1);this.log(`Backfill complete in ${$}s. attempted=${s.attempted} emitted=${s.emitted} skipped=${s.skipped} failed=${s.failed} highestStepIdx=${s.highestStepIdx}`),e["save-state"]?(d.save(t,{lastStepIdx:s.highestStepIdx}),this.log(`State saved \u2192 live hook will resume from step_index > ${s.highestStepIdx}.`)):this.log("State NOT saved (--no-save-state). Live hook will re-emit any new records from after-step.")}};export{g as default};
@@ -1 +1 @@
1
- import{a as n}from"../../chunk-LWI5K6T4.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-6VKQT2J3.js";import"../../chunk-NIRD7ETU.js";import"../../chunk-QY3UKLDE.js";import"../../chunk-3AV3GTMP.js";import{f as r}from"../../chunk-KLEF5D3A.js";import{i as o,l as s}from"../../chunk-JZ5Z2BRO.js";import{a}from"../../chunk-ZLLER3HP.js";import*as c from"node:path";import{Flags as l}from"@oclif/core";var t=class g extends n{static{a(this,"AuthCreateKey")}static description="Create a long-lived API key for CLI and proxy authentication";static examples=['<%= config.bin %> auth create-key --name "laptop"','<%= config.bin %> auth create-key --name "ci token" --no-save'];static flags={name:l.string({char:"n",description:"Name for this key",required:!0}),save:l.boolean({char:"s",description:"Save key to ~/.config/rulemetric/env for hooks/proxy",default:!0,allowNo:!0})};async run(){let{flags:i}=await this.parse(g),e=await r("/api/auth/api-keys",{name:i.name});this.log(""),this.log("API key created successfully:"),this.log(""),this.log(` Name: ${e.name}`),this.log(` Key: ${e.key}`),this.log(` Prefix: ${e.keyPrefix}`),this.log(""),this.warn("Save this key now \u2014 it will not be shown again."),i.save&&(o(e.key,process.env.RULEMETRIC_API_URL),this.log(""),this.log(`Key saved to ${c.join(s(),"env")} (RULEMETRIC_API_KEY)`),this.log("Hooks and proxy will use this key automatically."))}};export{t as default};
1
+ import{a as n}from"../../chunk-2DXBC2JQ.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-NIRD7ETU.js";import"../../chunk-6VKQT2J3.js";import"../../chunk-QY3UKLDE.js";import"../../chunk-3AV3GTMP.js";import{f as r}from"../../chunk-KLEF5D3A.js";import{i as o,l as s}from"../../chunk-JZ5Z2BRO.js";import{a}from"../../chunk-ZLLER3HP.js";import*as c from"node:path";import{Flags as l}from"@oclif/core";var t=class g extends n{static{a(this,"AuthCreateKey")}static description="Create a long-lived API key for CLI and proxy authentication";static examples=['<%= config.bin %> auth create-key --name "laptop"','<%= config.bin %> auth create-key --name "ci token" --no-save'];static flags={name:l.string({char:"n",description:"Name for this key",required:!0}),save:l.boolean({char:"s",description:"Save key to ~/.config/rulemetric/env for hooks/proxy",default:!0,allowNo:!0})};async run(){let{flags:i}=await this.parse(g),e=await r("/api/auth/api-keys",{name:i.name});this.log(""),this.log("API key created successfully:"),this.log(""),this.log(` Name: ${e.name}`),this.log(` Key: ${e.key}`),this.log(` Prefix: ${e.keyPrefix}`),this.log(""),this.warn("Save this key now \u2014 it will not be shown again."),i.save&&(o(e.key,process.env.RULEMETRIC_API_URL),this.log(""),this.log(`Key saved to ${c.join(s(),"env")} (RULEMETRIC_API_KEY)`),this.log("Hooks and proxy will use this key automatically."))}};export{t as default};
@@ -1,4 +1,4 @@
1
- import{a as f}from"../../chunk-RJLAAKEN.js";import{a as w}from"../../chunk-LWI5K6T4.js";import"../../chunk-IZTIYR5Q.js";import{c}from"../../chunk-6VKQT2J3.js";import"../../chunk-NIRD7ETU.js";import{b as n}from"../../chunk-QY3UKLDE.js";import"../../chunk-3AV3GTMP.js";import{b as r,d as a}from"../../chunk-KLEF5D3A.js";import{b as m,d,h as u,i as g}from"../../chunk-JZ5Z2BRO.js";import{a as l}from"../../chunk-ZLLER3HP.js";import{Flags as p}from"@oclif/core";var h=class y extends w{static{l(this,"AuthLogin")}static description="Log in to RuleMetric";static examples=["<%= config.bin %> auth login","<%= config.bin %> auth login -e user@example.com"];static flags={email:p.string({char:"e",description:"Email address"}),password:p.string({char:"p",description:"Password (for non-interactive use)"}),"api-key":p.string({description:"Authenticate with an API key from https://rulemetric.com/connect (required for Google/GitHub sign-ins, which have no password)",exclusive:["password"]})};async run(){let{flags:s}=await this.parse(y);if(s["api-key"]){await this.loginWithApiKey(s["api-key"]);return}let e=s.email,t=s.password;if(!e||!t){process.stdin.isTTY||this.error("Missing credentials in a non-interactive shell. Pass --email/-e and --password/-p, or set RULEMETRIC_API_KEY (create a key at https://rulemetric.com/connect).");let{input:o,password:k}=await import("@inquirer/prompts");this.log("Signed up with Google or GitHub? You have no password \u2014 press Ctrl-C and run:"),this.log(" rulemetric auth login --api-key <key> (create one at https://rulemetric.com/connect)"),this.log(""),e||(e=await o({message:"Email:"})),t||(t=await k({message:"Password:"}))}let i;try{i=await a("/auth/login",{method:"POST",body:{email:e,password:t},timeoutMs:2e4})}catch(o){throw o instanceof r&&o.statusCode===401&&this.error(`Invalid email or password.
1
+ import{a as f}from"../../chunk-RJLAAKEN.js";import{a as w}from"../../chunk-2DXBC2JQ.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-NIRD7ETU.js";import{c}from"../../chunk-6VKQT2J3.js";import{b as n}from"../../chunk-QY3UKLDE.js";import"../../chunk-3AV3GTMP.js";import{b as r,d as a}from"../../chunk-KLEF5D3A.js";import{b as m,d,h as u,i as g}from"../../chunk-JZ5Z2BRO.js";import{a as l}from"../../chunk-ZLLER3HP.js";import{Flags as p}from"@oclif/core";var h=class y extends w{static{l(this,"AuthLogin")}static description="Log in to RuleMetric";static examples=["<%= config.bin %> auth login","<%= config.bin %> auth login -e user@example.com"];static flags={email:p.string({char:"e",description:"Email address"}),password:p.string({char:"p",description:"Password (for non-interactive use)"}),"api-key":p.string({description:"Authenticate with an API key from https://rulemetric.com/connect (required for Google/GitHub sign-ins, which have no password)",exclusive:["password"]})};async run(){let{flags:s}=await this.parse(y);if(s["api-key"]){await this.loginWithApiKey(s["api-key"]);return}let e=s.email,t=s.password;if(!e||!t){process.stdin.isTTY||this.error("Missing credentials in a non-interactive shell. Pass --email/-e and --password/-p, or set RULEMETRIC_API_KEY (create a key at https://rulemetric.com/connect).");let{input:o,password:k}=await import("@inquirer/prompts");this.log("Signed up with Google or GitHub? You have no password \u2014 press Ctrl-C and run:"),this.log(" rulemetric auth login --api-key <key> (create one at https://rulemetric.com/connect)"),this.log(""),e||(e=await o({message:"Email:"})),t||(t=await k({message:"Password:"}))}let i;try{i=await a("/auth/login",{method:"POST",body:{email:e,password:t},timeoutMs:2e4})}catch(o){throw o instanceof r&&o.statusCode===401&&this.error(`Invalid email or password.
2
2
 
3
3
  If you signed up with Google or GitHub, you have no password \u2014 that is why this cannot work. Create an API key at https://rulemetric.com/connect, then run:
4
4
  rulemetric auth login --api-key <key>`),o}let v=i.expiresAt??new Date(Date.now()+3600*1e3).toISOString();d({accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:v,email:i.email}),u(i.accessToken,process.env.RULEMETRIC_API_URL),await n(),await f(this.log.bind(this),this.warn.bind(this),this.config.version),c("auth_login",{},this.config.version),this.log(`Logged in as ${i.email}`)}async loginWithApiKey(s){let e=s.trim();e||this.error("Empty --api-key. Create one at https://rulemetric.com/connect"),process.env.RULEMETRIC_API_KEY=e;try{await a("/api/setup/status",{timeoutMs:2e4})}catch(t){throw delete process.env.RULEMETRIC_API_KEY,t instanceof r&&(t.statusCode===401||t.statusCode===403)&&this.error("That API key was rejected. Check you copied it whole (it is shown only once at creation) or mint a new one at https://rulemetric.com/connect"),t}g(e,process.env.RULEMETRIC_API_URL),m(),await n(),c("auth_login",{method:"api_key"},this.config.version),this.log(`Authenticated with API key ${e.slice(0,11)}...`),this.log("Verify any time with: rulemetric auth status")}};export{h as default};
@@ -1 +1 @@
1
- import{a as s}from"../../chunk-LWI5K6T4.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-6VKQT2J3.js";import"../../chunk-NIRD7ETU.js";import"../../chunk-QY3UKLDE.js";import"../../chunk-3AV3GTMP.js";import"../../chunk-KLEF5D3A.js";import{f as i,j as r}from"../../chunk-JZ5Z2BRO.js";import{a as o}from"../../chunk-ZLLER3HP.js";var e=class t extends s{static{o(this,"AuthLogout")}static description="Log out of RuleMetric";static examples=["<%= config.bin %> auth logout"];async run(){await this.parse(t),i(),r(),this.log("Logged out successfully.")}};export{e as default};
1
+ import{a as s}from"../../chunk-2DXBC2JQ.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-NIRD7ETU.js";import"../../chunk-6VKQT2J3.js";import"../../chunk-QY3UKLDE.js";import"../../chunk-3AV3GTMP.js";import"../../chunk-KLEF5D3A.js";import{f as i,j as r}from"../../chunk-JZ5Z2BRO.js";import{a as o}from"../../chunk-ZLLER3HP.js";var e=class t extends s{static{o(this,"AuthLogout")}static description="Log out of RuleMetric";static examples=["<%= config.bin %> auth logout"];async run(){await this.parse(t),i(),r(),this.log("Logged out successfully.")}};export{e as default};
@@ -1,4 +1,4 @@
1
- import{a as k}from"../../chunk-LWI5K6T4.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-6VKQT2J3.js";import"../../chunk-NIRD7ETU.js";import"../../chunk-QY3UKLDE.js";import"../../chunk-3AV3GTMP.js";import{e as n,i as c}from"../../chunk-KLEF5D3A.js";import"../../chunk-JZ5Z2BRO.js";import{a as s}from"../../chunk-ZLLER3HP.js";import{Args as y}from"@oclif/core";var a=class m extends k{static{s(this,"AuthRevokeKey")}static description="Revoke an API key (run with no argument to list active keys)";static examples=["<%= config.bin %> auth revoke-key","<%= config.bin %> auth revoke-key rm_abc12345",'<%= config.bin %> auth revoke-key "my-laptop (auto)"'];static args={id:y.string({description:"API key ID, prefix (rm_xxxxxxxx), or name"})};async run(){let{args:o}=await this.parse(m),r=(await n("/api/auth/api-keys")).filter(e=>!e.revokedAt);if(!o.id){if(r.length===0){this.log("No active API keys.");return}this.log(`Active API keys \u2014 pass an id, prefix, or name to revoke one:
1
+ import{a as k}from"../../chunk-2DXBC2JQ.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-NIRD7ETU.js";import"../../chunk-6VKQT2J3.js";import"../../chunk-QY3UKLDE.js";import"../../chunk-3AV3GTMP.js";import{e as n,i as c}from"../../chunk-KLEF5D3A.js";import"../../chunk-JZ5Z2BRO.js";import{a as s}from"../../chunk-ZLLER3HP.js";import{Args as y}from"@oclif/core";var a=class m extends k{static{s(this,"AuthRevokeKey")}static description="Revoke an API key (run with no argument to list active keys)";static examples=["<%= config.bin %> auth revoke-key","<%= config.bin %> auth revoke-key rm_abc12345",'<%= config.bin %> auth revoke-key "my-laptop (auto)"'];static args={id:y.string({description:"API key ID, prefix (rm_xxxxxxxx), or name"})};async run(){let{args:o}=await this.parse(m),r=(await n("/api/auth/api-keys")).filter(e=>!e.revokedAt);if(!o.id){if(r.length===0){this.log("No active API keys.");return}this.log(`Active API keys \u2014 pass an id, prefix, or name to revoke one:
2
2
  `);for(let e of r)this.log(` ${e.id} ${e.keyPrefix}... ${e.name}`);return}let i=o.id,t=r.filter(e=>e.id===i||e.name===i||i.startsWith("rm_")&&i.startsWith(e.keyPrefix));t.length===0&&this.error(`No active API key matches "${i}". Run \`rulemetric auth revoke-key\` with no argument to list keys.`),t.length>1&&this.error(`"${i}" matches ${t.length} keys \u2014 use the exact key ID:
3
3
  `+t.map(e=>` ${e.id} ${e.keyPrefix}... ${e.name}`).join(`
4
4
  `)),await c(`/api/auth/api-keys/${t[0].id}`),this.log(`API key ${t[0].keyPrefix}... ("${t[0].name}") revoked.`)}};export{a as default};
@@ -1 +1 @@
1
- import{a as g}from"../../chunk-RJLAAKEN.js";import{a as h}from"../../chunk-LWI5K6T4.js";import"../../chunk-IZTIYR5Q.js";import{c as d}from"../../chunk-6VKQT2J3.js";import"../../chunk-NIRD7ETU.js";import{b as l}from"../../chunk-QY3UKLDE.js";import"../../chunk-3AV3GTMP.js";import{b as m,d as p}from"../../chunk-KLEF5D3A.js";import{d as n,h as c}from"../../chunk-JZ5Z2BRO.js";import{a as o}from"../../chunk-ZLLER3HP.js";import{Flags as u}from"@oclif/core";var t=class f extends h{static{o(this,"AuthSignup")}static description="Create a RuleMetric account from the CLI";static examples=["<%= config.bin %> auth signup","<%= config.bin %> auth signup -e user@example.com"];static flags={email:u.string({char:"e",description:"Email address"}),password:u.string({char:"p",description:"Password (min 8 chars; for non-interactive use)"})};async run(){let{flags:a}=await this.parse(f),i=a.email,r=a.password;if(!i||!r){process.stdin.isTTY||this.error("Missing credentials in a non-interactive shell. Pass --email/-e and --password/-p.");let{input:s,password:v}=await import("@inquirer/prompts");i||(i=await s({message:"Email:"})),r||(r=await v({message:"Password (min 8 chars):"}))}let e;try{e=await p("/auth/signup",{method:"POST",body:{email:i,password:r},timeoutMs:2e4})}catch(s){throw s instanceof m&&s.statusCode===409&&this.error(`An account with ${i} already exists. Run: rulemetric auth login -e ${i}`),s}if(e.confirmationRequired||!e.accessToken||!e.refreshToken){this.log(`Account created for ${e.email}.`),this.log("Check your email and click the confirmation link, then run:"),this.log(` rulemetric auth login -e ${e.email}`);return}let w=e.expiresAt??new Date(Date.now()+3600*1e3).toISOString();n({accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:w,email:e.email}),c(e.accessToken,process.env.RULEMETRIC_API_URL),await l(),await g(this.log.bind(this),this.warn.bind(this),this.config.version),d("auth_signup",{},this.config.version),this.log(`Signed up and logged in as ${e.email}`)}};export{t as default};
1
+ import{a as g}from"../../chunk-RJLAAKEN.js";import{a as h}from"../../chunk-2DXBC2JQ.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-NIRD7ETU.js";import{c as d}from"../../chunk-6VKQT2J3.js";import{b as l}from"../../chunk-QY3UKLDE.js";import"../../chunk-3AV3GTMP.js";import{b as m,d as p}from"../../chunk-KLEF5D3A.js";import{d as n,h as c}from"../../chunk-JZ5Z2BRO.js";import{a as o}from"../../chunk-ZLLER3HP.js";import{Flags as u}from"@oclif/core";var t=class f extends h{static{o(this,"AuthSignup")}static description="Create a RuleMetric account from the CLI";static examples=["<%= config.bin %> auth signup","<%= config.bin %> auth signup -e user@example.com"];static flags={email:u.string({char:"e",description:"Email address"}),password:u.string({char:"p",description:"Password (min 8 chars; for non-interactive use)"})};async run(){let{flags:a}=await this.parse(f),i=a.email,r=a.password;if(!i||!r){process.stdin.isTTY||this.error("Missing credentials in a non-interactive shell. Pass --email/-e and --password/-p.");let{input:s,password:v}=await import("@inquirer/prompts");i||(i=await s({message:"Email:"})),r||(r=await v({message:"Password (min 8 chars):"}))}let e;try{e=await p("/auth/signup",{method:"POST",body:{email:i,password:r},timeoutMs:2e4})}catch(s){throw s instanceof m&&s.statusCode===409&&this.error(`An account with ${i} already exists. Run: rulemetric auth login -e ${i}`),s}if(e.confirmationRequired||!e.accessToken||!e.refreshToken){this.log(`Account created for ${e.email}.`),this.log("Check your email and click the confirmation link, then run:"),this.log(` rulemetric auth login -e ${e.email}`);return}let w=e.expiresAt??new Date(Date.now()+3600*1e3).toISOString();n({accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:w,email:e.email}),c(e.accessToken,process.env.RULEMETRIC_API_URL),await l(),await g(this.log.bind(this),this.warn.bind(this),this.config.version),d("auth_signup",{},this.config.version),this.log(`Signed up and logged in as ${e.email}`)}};export{t as default};
@@ -1 +1 @@
1
- import{a as c}from"../../chunk-W2MV25SB.js";import{a as g}from"../../chunk-LWI5K6T4.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-6VKQT2J3.js";import"../../chunk-NIRD7ETU.js";import"../../chunk-QY3UKLDE.js";import"../../chunk-3AV3GTMP.js";import"../../chunk-KLEF5D3A.js";import{a,e as l,l as t}from"../../chunk-JZ5Z2BRO.js";import{a as r}from"../../chunk-ZLLER3HP.js";import*as u from"node:path";var o=class h extends g{static{r(this,"AuthStatus")}static description="Show current authentication status";static examples=["<%= config.bin %> auth status"];async run(){await this.parse(h);let e=l(),i=process.env.RULEMETRIC_API_KEY,s=a().apiKey;if(i||s){let m=i||s,p=i?"RULEMETRIC_API_KEY env var":u.join(t(),"env");this.log(`Authenticated via API key ${m.slice(0,11)}... (${p})`),e&&this.log(`Logged in as: ${e.email}`),this.log(`Config: ${t()}`);return}if(!e){this.log("Not logged in. Run `rulemetric auth login` to authenticate.");return}let n=new Date(e.expiresAt).getTime();if(Number.isNaN(n)||Date.now()>=n){this.log("Session expired. Run `rulemetric auth login` to re-authenticate.");return}this.log(`Logged in as: ${e.email}`),this.log(`Session expires: ${c(e.expiresAt)}`),this.log(`Config: ${t()}`)}};export{o as default};
1
+ import{a as c}from"../../chunk-W2MV25SB.js";import{a as g}from"../../chunk-2DXBC2JQ.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-NIRD7ETU.js";import"../../chunk-6VKQT2J3.js";import"../../chunk-QY3UKLDE.js";import"../../chunk-3AV3GTMP.js";import"../../chunk-KLEF5D3A.js";import{a,e as l,l as t}from"../../chunk-JZ5Z2BRO.js";import{a as r}from"../../chunk-ZLLER3HP.js";import*as u from"node:path";var o=class h extends g{static{r(this,"AuthStatus")}static description="Show current authentication status";static examples=["<%= config.bin %> auth status"];async run(){await this.parse(h);let e=l(),i=process.env.RULEMETRIC_API_KEY,s=a().apiKey;if(i||s){let m=i||s,p=i?"RULEMETRIC_API_KEY env var":u.join(t(),"env");this.log(`Authenticated via API key ${m.slice(0,11)}... (${p})`),e&&this.log(`Logged in as: ${e.email}`),this.log(`Config: ${t()}`);return}if(!e){this.log("Not logged in. Run `rulemetric auth login` to authenticate.");return}let n=new Date(e.expiresAt).getTime();if(Number.isNaN(n)||Date.now()>=n){this.log("Session expired. Run `rulemetric auth login` to re-authenticate.");return}this.log(`Logged in as: ${e.email}`),this.log(`Session expires: ${c(e.expiresAt)}`),this.log(`Config: ${t()}`)}};export{o as default};
@@ -1,2 +1,2 @@
1
- import{a as f,b as k,c as S,d as x,e as R,f as n,g as y}from"../../chunk-SHYP27B7.js";import{b as C,c as w,f as v,g as b}from"../../chunk-QXPYGN7I.js";import{a as u}from"../../chunk-LWI5K6T4.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-6VKQT2J3.js";import"../../chunk-NIRD7ETU.js";import"../../chunk-QY3UKLDE.js";import"../../chunk-3AV3GTMP.js";import"../../chunk-KLEF5D3A.js";import{l as m}from"../../chunk-JZ5Z2BRO.js";import{a as h}from"../../chunk-ZLLER3HP.js";import{existsSync as O}from"node:fs";import{Flags as c}from"@oclif/core";var g=class E extends u{static{h(this,"CaptureScope")}static description="Show or set which projects RuleMetric captures \u2014 the Codex sweep and hook-driven sessions each have their own scope";static examples=["<%= config.bin %> <%= command.id %>","<%= config.bin %> <%= command.id %> --add ~/work/client-a --add ~/work/client-b","<%= config.bin %> <%= command.id %> --tool hooks --add ~/work/client-a","<%= config.bin %> <%= command.id %> --tool hooks --off","<%= config.bin %> <%= command.id %> --remove ~/work/client-a","<%= config.bin %> <%= command.id %> --off","<%= config.bin %> <%= command.id %> --all"];static flags={tool:c.string({description:'Which capture path to edit: "codex" (the worker transcript sweep, the default) or "hooks" (Claude Code / Cursor / Copilot / Antigravity hook sessions).',options:["codex","hooks"],default:"codex"}),add:c.string({description:"Capture sessions under this path (repeatable). Implies an allowlist.",multiple:!0}),remove:c.string({description:"Stop capturing under this path (repeatable).",multiple:!0}),off:c.boolean({description:"Turn this capture path off entirely.",exclusive:["all"]}),all:c.boolean({description:"Capture every project (the default).",exclusive:["off"]}),clear:c.boolean({description:"Remove this scope, restoring the default."})};async run(){let{flags:o}=await this.parse(E),s=m(),d=f(s);if(!((o.add?.length??0)>0||(o.remove?.length??0)>0||o.off||o.all||o.clear)){await this.show(s,d);return}for(let t of[...o.add??[],...o.remove??[]])R(t)||this.error(`Not an absolute path: ${t}
1
+ import{a as f,b as k,c as S,d as x,e as R,f as n,g as y}from"../../chunk-SHYP27B7.js";import{b as C,c as w,f as v,g as b}from"../../chunk-QXPYGN7I.js";import{a as u}from"../../chunk-2DXBC2JQ.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-NIRD7ETU.js";import"../../chunk-6VKQT2J3.js";import"../../chunk-QY3UKLDE.js";import"../../chunk-3AV3GTMP.js";import"../../chunk-KLEF5D3A.js";import{l as m}from"../../chunk-JZ5Z2BRO.js";import{a as h}from"../../chunk-ZLLER3HP.js";import{existsSync as O}from"node:fs";import{Flags as c}from"@oclif/core";var g=class E extends u{static{h(this,"CaptureScope")}static description="Show or set which projects RuleMetric captures \u2014 the Codex sweep and hook-driven sessions each have their own scope";static examples=["<%= config.bin %> <%= command.id %>","<%= config.bin %> <%= command.id %> --add ~/work/client-a --add ~/work/client-b","<%= config.bin %> <%= command.id %> --tool hooks --add ~/work/client-a","<%= config.bin %> <%= command.id %> --tool hooks --off","<%= config.bin %> <%= command.id %> --remove ~/work/client-a","<%= config.bin %> <%= command.id %> --off","<%= config.bin %> <%= command.id %> --all"];static flags={tool:c.string({description:'Which capture path to edit: "codex" (the worker transcript sweep, the default) or "hooks" (Claude Code / Cursor / Copilot / Antigravity hook sessions).',options:["codex","hooks"],default:"codex"}),add:c.string({description:"Capture sessions under this path (repeatable). Implies an allowlist.",multiple:!0}),remove:c.string({description:"Stop capturing under this path (repeatable).",multiple:!0}),off:c.boolean({description:"Turn this capture path off entirely.",exclusive:["all"]}),all:c.boolean({description:"Capture every project (the default).",exclusive:["off"]}),clear:c.boolean({description:"Remove this scope, restoring the default."})};async run(){let{flags:o}=await this.parse(E),s=m(),d=f(s);if(!((o.add?.length??0)>0||(o.remove?.length??0)>0||o.off||o.all||o.clear)){await this.show(s,d);return}for(let t of[...o.add??[],...o.remove??[]])R(t)||this.error(`Not an absolute path: ${t}
2
2
  Use an absolute path or ~/\u2026 \u2014 relative paths cannot be matched against a session's cwd.`);for(let t of o.add??[]){let a=x(t);O(a)||this.warn(`${a} does not exist yet \u2014 added anyway, but nothing will match until it does.`)}let e;try{e=k(s)}catch(t){o.clear||this.error(t instanceof Error?t.message:String(t));let a=y(s);this.warn(`${f(s)} was not valid JSON \u2014 saved it to ${a} and starting fresh.`),e={}}let i=o.tool??"codex",r=void 0,l=!1;if(o.clear&&({config:e}=n(e,{op:"clear"},r,i)),o.off&&({config:e}=n(e,{op:"mode",mode:"off"},r,i)),o.all&&({config:e}=n(e,{op:"mode",mode:"all"},r,i)),o.remove?.length){let t=n(e,{op:"remove",roots:o.remove},r,i);e=t.config,l=t.emptiedToOff}o.add?.length&&({config:e}=n(e,{op:"add",roots:o.add},r,i)),S(s,e),l&&(this.log(`Removed the last root \u2014 ${i==="hooks"?"hook":"Codex"} capture is now OFF rather than silently capturing everything.`),this.log("Use --all to go back to capturing every project.")),await this.show(s,d),this.log(""),this.log(i==="hooks"?"Takes effect on the next hook fire. No restart needed.":"Takes effect on the next sweep (within ~30s). No restart needed.")}async show(o,s){let d=await C({configDir:o}),p=await w({configDir:o}),e=h((i,r,l,t)=>{if(this.log(`${i}: ${l}`),r.roots.length)for(let a of r.roots)this.log(` \u2022 ${a}`);r.error&&(this.log(" This scope is FAILING CLOSED \u2014 nothing is being captured on this path."),this.log(` Fix the file, or run \`rulemetric capture scope ${i==="Hook capture"?"--tool hooks ":""}--clear\` to start over.`)),r.source==="env"&&this.log(` Set by environment variable, which outranks the config file (${t}).`)},"print");e("Codex capture",d,v(d),"RULEMETRIC_CODEX_CAPTURE / RULEMETRIC_CODEX_ROOTS"),e("Hook capture",p,b(p),"RULEMETRIC_HOOKS_CAPTURE / RULEMETRIC_HOOKS_ROOTS"),this.log(`Config: ${s}`)}};export{g as default};
@@ -1,2 +1,2 @@
1
- import{a as g,b as d,c as p}from"../../chunk-W2MV25SB.js";import{a as c}from"../../chunk-LWI5K6T4.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-6VKQT2J3.js";import"../../chunk-NIRD7ETU.js";import"../../chunk-QY3UKLDE.js";import"../../chunk-3AV3GTMP.js";import{e as n}from"../../chunk-KLEF5D3A.js";import"../../chunk-JZ5Z2BRO.js";import{a}from"../../chunk-ZLLER3HP.js";import{Flags as i}from"@oclif/core";var o=class m extends c{static{a(this,"Catalog")}static description="Browse the org instruction catalog";static flags={badge:i.string({description:"Filter by badge",options:["recommended","required"]}),scope:i.string({description:"Filter by scope",options:["org","team"]}),search:i.string({description:"Search by name or description"})};async run(){let{flags:e}=await this.parse(m);this.requireAuth();let s=new URLSearchParams;e.badge&&s.set("badge",e.badge),e.scope&&s.set("scope",e.scope),e.search&&s.set("search",e.search);let r=await n(`/api/catalog?${s.toString()}`);if(r.length===0){this.log("No instructions found in catalog.");return}for(let t of r){let l=t.badge?` [${t.badge}]`:"",f=t.tags?.length?` (${t.tags.join(", ")})`:"";this.log(` ${d(t.name,40)} \u2014 ${p(t.scope)}${l} v${t.version}${f} ${g(t.updatedAt)}`)}this.log(`
1
+ import{a as g,b as d,c as p}from"../../chunk-W2MV25SB.js";import{a as c}from"../../chunk-2DXBC2JQ.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-NIRD7ETU.js";import"../../chunk-6VKQT2J3.js";import"../../chunk-QY3UKLDE.js";import"../../chunk-3AV3GTMP.js";import{e as n}from"../../chunk-KLEF5D3A.js";import"../../chunk-JZ5Z2BRO.js";import{a}from"../../chunk-ZLLER3HP.js";import{Flags as i}from"@oclif/core";var o=class m extends c{static{a(this,"Catalog")}static description="Browse the org instruction catalog";static flags={badge:i.string({description:"Filter by badge",options:["recommended","required"]}),scope:i.string({description:"Filter by scope",options:["org","team"]}),search:i.string({description:"Search by name or description"})};async run(){let{flags:e}=await this.parse(m);this.requireAuth();let s=new URLSearchParams;e.badge&&s.set("badge",e.badge),e.scope&&s.set("scope",e.scope),e.search&&s.set("search",e.search);let r=await n(`/api/catalog?${s.toString()}`);if(r.length===0){this.log("No instructions found in catalog.");return}for(let t of r){let l=t.badge?` [${t.badge}]`:"",f=t.tags?.length?` (${t.tags.join(", ")})`:"";this.log(` ${d(t.name,40)} \u2014 ${p(t.scope)}${l} v${t.version}${f} ${g(t.updatedAt)}`)}this.log(`
2
2
  ${r.length} instruction(s) found.`)}};export{o as default};
@@ -1,3 +1,3 @@
1
- import{a as i}from"../../chunk-LWI5K6T4.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-6VKQT2J3.js";import"../../chunk-NIRD7ETU.js";import"../../chunk-QY3UKLDE.js";import"../../chunk-3AV3GTMP.js";import{f as n}from"../../chunk-KLEF5D3A.js";import"../../chunk-JZ5Z2BRO.js";import{a as t}from"../../chunk-ZLLER3HP.js";import{Args as c}from"@oclif/core";var o=class s extends i{static{t(this,"CatalogRecommend")}static description="Get AI-powered instruction recommendations for a project";static args={projectId:c.string({description:"ID of the project",required:!0})};async run(){let{args:a}=await this.parse(s);this.requireAuth(),this.log(`Analyzing project and generating recommendations...
1
+ import{a as i}from"../../chunk-2DXBC2JQ.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-NIRD7ETU.js";import"../../chunk-6VKQT2J3.js";import"../../chunk-QY3UKLDE.js";import"../../chunk-3AV3GTMP.js";import{f as n}from"../../chunk-KLEF5D3A.js";import"../../chunk-JZ5Z2BRO.js";import{a as t}from"../../chunk-ZLLER3HP.js";import{Args as c}from"@oclif/core";var o=class s extends i{static{t(this,"CatalogRecommend")}static description="Get AI-powered instruction recommendations for a project";static args={projectId:c.string({description:"ID of the project",required:!0})};async run(){let{args:a}=await this.parse(s);this.requireAuth(),this.log(`Analyzing project and generating recommendations...
2
2
  `);let r=await n(`/api/projects/${a.projectId}/recommendations`,{});if(r.error&&this.warn(`Note: ${r.error}`),r.recommendations.length===0){this.log("No recommendations found.");return}for(let e of r.recommendations)this.log(` ${(e.score*100).toFixed(0)}% \u2014 ${e.instructionId}`),this.log(` ${e.reason}
3
3
  `)}};export{o as default};
@@ -1 +1 @@
1
- import{a as l}from"../chunk-WLVQJH4E.js";import{a as u}from"../chunk-LWI5K6T4.js";import"../chunk-IZTIYR5Q.js";import"../chunk-6VKQT2J3.js";import"../chunk-NIRD7ETU.js";import"../chunk-QY3UKLDE.js";import"../chunk-3AV3GTMP.js";import{a as n,f as c}from"../chunk-KLEF5D3A.js";import"../chunk-JZ5Z2BRO.js";import{a}from"../chunk-ZLLER3HP.js";import*as d from"node:fs";import{Args as p,Flags as i}from"@oclif/core";var e=class f extends u{static{a(this,"Convert")}static description="Convert an instruction to a target format";static examples=["<%= config.bin %> convert <id> --format claude-md","<%= config.bin %> convert <id> -f cursorrules --score","<%= config.bin %> convert <id> -f copilot -o .github/copilot-instructions.md"];static args={id:p.string({description:"Instruction ID",required:!0})};static flags={format:i.string({char:"f",description:"Target format (e.g., claude-md, cursorrules)",required:!0}),score:i.boolean({description:"Include quality score",default:!1}),output:i.string({char:"o",description:"Write output to file"})};async run(){let{args:s,flags:t}=await this.parse(f);this.requireAuth(),l(s.id,"instruction ID");let o=new URL(`${process.env.RULEMETRIC_API_URL??n}/api/instructions/${encodeURIComponent(s.id)}/convert`);o.searchParams.set("format",t.format),o.searchParams.set("score",String(t.score));let r=await c(`${o.pathname}${o.search}`,{});t.output?(d.writeFileSync(t.output,r.output,"utf-8"),this.log(`Written to ${t.output}`)):this.log(r.output),t.score&&r.score&&(this.log(""),this.log(`Quality Score: ${r.score.overall}/100`)),r.warnings.length>0&&this.warn(`Warnings: ${r.warnings.join(", ")}`)}};export{e as default};
1
+ import{a as l}from"../chunk-WLVQJH4E.js";import{a as u}from"../chunk-2DXBC2JQ.js";import"../chunk-IZTIYR5Q.js";import"../chunk-NIRD7ETU.js";import"../chunk-6VKQT2J3.js";import"../chunk-QY3UKLDE.js";import"../chunk-3AV3GTMP.js";import{a as n,f as c}from"../chunk-KLEF5D3A.js";import"../chunk-JZ5Z2BRO.js";import{a}from"../chunk-ZLLER3HP.js";import*as d from"node:fs";import{Args as p,Flags as i}from"@oclif/core";var e=class f extends u{static{a(this,"Convert")}static description="Convert an instruction to a target format";static examples=["<%= config.bin %> convert <id> --format claude-md","<%= config.bin %> convert <id> -f cursorrules --score","<%= config.bin %> convert <id> -f copilot -o .github/copilot-instructions.md"];static args={id:p.string({description:"Instruction ID",required:!0})};static flags={format:i.string({char:"f",description:"Target format (e.g., claude-md, cursorrules)",required:!0}),score:i.boolean({description:"Include quality score",default:!1}),output:i.string({char:"o",description:"Write output to file"})};async run(){let{args:s,flags:t}=await this.parse(f);this.requireAuth(),l(s.id,"instruction ID");let o=new URL(`${process.env.RULEMETRIC_API_URL??n}/api/instructions/${encodeURIComponent(s.id)}/convert`);o.searchParams.set("format",t.format),o.searchParams.set("score",String(t.score));let r=await c(`${o.pathname}${o.search}`,{});t.output?(d.writeFileSync(t.output,r.output,"utf-8"),this.log(`Written to ${t.output}`)):this.log(r.output),t.score&&r.score&&(this.log(""),this.log(`Quality Score: ${r.score.overall}/100`)),r.warnings.length>0&&this.warn(`Warnings: ${r.warnings.join(", ")}`)}};export{e as default};
@@ -1 +1 @@
1
- import{a as s}from"../chunk-LWI5K6T4.js";import"../chunk-IZTIYR5Q.js";import"../chunk-6VKQT2J3.js";import"../chunk-NIRD7ETU.js";import"../chunk-QY3UKLDE.js";import"../chunk-3AV3GTMP.js";import{e as a}from"../chunk-KLEF5D3A.js";import"../chunk-JZ5Z2BRO.js";import{a as o}from"../chunk-ZLLER3HP.js";import{Flags as m}from"@oclif/core";import{printTable as c}from"@oclif/table";var e=class n extends s{static{o(this,"Converters")}static description="List all supported conversion formats";static examples=["<%= config.bin %> converters","<%= config.bin %> converters --tier 1"];static enableJsonFlag=!0;static flags={tier:m.string({char:"t",description:"Filter by tier",options:["1","2","3"]})};async run(){let{flags:i}=await this.parse(n);this.requireAuth();let r=await a("/api/converters");if(i.tier){let t=Number.parseInt(i.tier,10);r=r.filter(p=>p.tier===t)}return c({data:r.map(t=>({ID:t.id,Name:t.name,Tier:String(t.tier),"Output Path":t.outputPath})),columns:["ID","Name","Tier","Output Path"]}),r}};export{e as default};
1
+ import{a as s}from"../chunk-2DXBC2JQ.js";import"../chunk-IZTIYR5Q.js";import"../chunk-NIRD7ETU.js";import"../chunk-6VKQT2J3.js";import"../chunk-QY3UKLDE.js";import"../chunk-3AV3GTMP.js";import{e as a}from"../chunk-KLEF5D3A.js";import"../chunk-JZ5Z2BRO.js";import{a as o}from"../chunk-ZLLER3HP.js";import{Flags as m}from"@oclif/core";import{printTable as c}from"@oclif/table";var e=class n extends s{static{o(this,"Converters")}static description="List all supported conversion formats";static examples=["<%= config.bin %> converters","<%= config.bin %> converters --tier 1"];static enableJsonFlag=!0;static flags={tier:m.string({char:"t",description:"Filter by tier",options:["1","2","3"]})};async run(){let{flags:i}=await this.parse(n);this.requireAuth();let r=await a("/api/converters");if(i.tier){let t=Number.parseInt(i.tier,10);r=r.filter(p=>p.tier===t)}return c({data:r.map(t=>({ID:t.id,Name:t.name,Tier:String(t.tier),"Output Path":t.outputPath})),columns:["ID","Name","Tier","Output Path"]}),r}};export{e as default};
@@ -1 +1 @@
1
- import{a as o}from"../../chunk-GY5IJ4RS.js";import{a as n}from"../../chunk-LWI5K6T4.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-6VKQT2J3.js";import"../../chunk-NIRD7ETU.js";import"../../chunk-QY3UKLDE.js";import"../../chunk-3AV3GTMP.js";import"../../chunk-KLEF5D3A.js";import"../../chunk-JZ5Z2BRO.js";import{a as i}from"../../chunk-ZLLER3HP.js";import{printTable as t}from"@oclif/table";var a=class s extends n{static{i(this,"CronsList")}static description="List manually-runnable maintenance tasks";static examples=["<%= config.bin %> crons list"];async run(){await this.parse(s),t({data:o.map(e=>({Name:e.name,"Scheduled by":e.scheduledBy,Description:e.description})),columns:["Name","Scheduled by","Description"]}),this.log(""),this.log("Scheduled crons run in Supabase pg_cron \u2014 audit them with:"),this.log(` psql "$DATABASE_URL" -c 'select jobname, schedule, active from cron.job;'`),this.log("Run any task above on demand with: rulemetric crons run <name>")}};export{a as default};
1
+ import{a as o}from"../../chunk-GY5IJ4RS.js";import{a as n}from"../../chunk-2DXBC2JQ.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-NIRD7ETU.js";import"../../chunk-6VKQT2J3.js";import"../../chunk-QY3UKLDE.js";import"../../chunk-3AV3GTMP.js";import"../../chunk-KLEF5D3A.js";import"../../chunk-JZ5Z2BRO.js";import{a as i}from"../../chunk-ZLLER3HP.js";import{printTable as t}from"@oclif/table";var a=class s extends n{static{i(this,"CronsList")}static description="List manually-runnable maintenance tasks";static examples=["<%= config.bin %> crons list"];async run(){await this.parse(s),t({data:o.map(e=>({Name:e.name,"Scheduled by":e.scheduledBy,Description:e.description})),columns:["Name","Scheduled by","Description"]}),this.log(""),this.log("Scheduled crons run in Supabase pg_cron \u2014 audit them with:"),this.log(` psql "$DATABASE_URL" -c 'select jobname, schedule, active from cron.job;'`),this.log("Run any task above on demand with: rulemetric crons run <name>")}};export{a as default};
@@ -1,2 +1,2 @@
1
- import{a as u}from"../../chunk-GY5IJ4RS.js";import{a as c}from"../../chunk-LWI5K6T4.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-6VKQT2J3.js";import"../../chunk-NIRD7ETU.js";import"../../chunk-QY3UKLDE.js";import"../../chunk-3AV3GTMP.js";import"../../chunk-KLEF5D3A.js";import"../../chunk-JZ5Z2BRO.js";import{a as l}from"../../chunk-ZLLER3HP.js";import{Args as g,Flags as f}from"@oclif/core";var i=class m extends c{static{l(this,"CronsRun")}static description="Run a maintenance task synchronously, right now";static examples=["<%= config.bin %> crons run cron_check_changelog","<%= config.bin %> crons run cron_suggest_instructions --quiet"];static args={name:g.string({description:"Task name (run `rulemetric crons list` to see all)",required:!0})};static flags={quiet:f.boolean({char:"q",description:"Suppress per-line log output; print summary only"})};async run(){let{args:s,flags:d}=await this.parse(m);this.requireAuth();let n=u.find(e=>e.name===s.name);n||this.error(`Unknown task: ${s.name}
1
+ import{a as u}from"../../chunk-GY5IJ4RS.js";import{a as c}from"../../chunk-2DXBC2JQ.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-NIRD7ETU.js";import"../../chunk-6VKQT2J3.js";import"../../chunk-QY3UKLDE.js";import"../../chunk-3AV3GTMP.js";import"../../chunk-KLEF5D3A.js";import"../../chunk-JZ5Z2BRO.js";import{a as l}from"../../chunk-ZLLER3HP.js";import{Args as g,Flags as f}from"@oclif/core";var i=class m extends c{static{l(this,"CronsRun")}static description="Run a maintenance task synchronously, right now";static examples=["<%= config.bin %> crons run cron_check_changelog","<%= config.bin %> crons run cron_suggest_instructions --quiet"];static args={name:g.string({description:"Task name (run `rulemetric crons list` to see all)",required:!0})};static flags={quiet:f.boolean({char:"q",description:"Suppress per-line log output; print summary only"})};async run(){let{args:s,flags:d}=await this.parse(m);this.requireAuth();let n=u.find(e=>e.name===s.name);n||this.error(`Unknown task: ${s.name}
2
2
  Run \`rulemetric crons list\` to see available tasks.`);let o;try{({runManualTask:o}=await import("../../lib/manual-tasks.js"))}catch(e){let r=e?.code;throw(r==="ERR_MODULE_NOT_FOUND"||r==="MODULE_NOT_FOUND")&&this.error("`crons run` needs the worker runtime, which isn't available in this install.\nThese maintenance tasks connect to the database directly \u2014 run them from a full RuleMetric checkout with DATABASE_URL and the worker dependencies installed."),e}this.log(`\u25B6 Running ${n.name} \u2026`);let h=Date.now(),t=await o(s.name);if(!d.quiet)for(let e of t.logs){let r=e.level==="error"||e.level==="warn"?`[${e.level}]`:"";this.log(` ${r} ${e.message}`)}let a=((t.durationMs??Date.now()-h)/1e3).toFixed(1);t.ok?this.log(`\u2713 ${n.name} completed in ${a}s (${t.logs.length} log line${t.logs.length===1?"":"s"})`):this.error(`\u2717 ${n.name} failed after ${a}s: ${t.error}`)}};export{i as default};
@@ -1 +1 @@
1
- import{a as o}from"../chunk-LWI5K6T4.js";import"../chunk-IZTIYR5Q.js";import"../chunk-6VKQT2J3.js";import"../chunk-NIRD7ETU.js";import"../chunk-QY3UKLDE.js";import"../chunk-3AV3GTMP.js";import"../chunk-KLEF5D3A.js";import"../chunk-JZ5Z2BRO.js";import{a as i}from"../chunk-ZLLER3HP.js";import{Flags as r}from"@oclif/core";var a=class s extends o{static{i(this,"Dashboard")}static description="Interactive TUI dashboard showing session analytics, outcomes, friction, and insights";static examples=["<%= config.bin %> dashboard","<%= config.bin %> dashboard --period 30days","<%= config.bin %> dashboard --launcher"];static flags={period:r.string({char:"p",default:"week",options:["today","week","30days","month","all"],description:"Initial time period"}),launcher:r.boolean({char:"l",default:!1,description:"Open the launcher overlay immediately"})};async run(){let{flags:e}=await this.parse(s),{renderDashboard:t}=await import("../dashboard/Dashboard.js");await t(e.period,{openLauncher:e.launcher})}};export{a as default};
1
+ import{a as o}from"../chunk-2DXBC2JQ.js";import"../chunk-IZTIYR5Q.js";import"../chunk-NIRD7ETU.js";import"../chunk-6VKQT2J3.js";import"../chunk-QY3UKLDE.js";import"../chunk-3AV3GTMP.js";import"../chunk-KLEF5D3A.js";import"../chunk-JZ5Z2BRO.js";import{a as i}from"../chunk-ZLLER3HP.js";import{Flags as r}from"@oclif/core";var a=class s extends o{static{i(this,"Dashboard")}static description="Interactive TUI dashboard showing session analytics, outcomes, friction, and insights";static examples=["<%= config.bin %> dashboard","<%= config.bin %> dashboard --period 30days","<%= config.bin %> dashboard --launcher"];static flags={period:r.string({char:"p",default:"week",options:["today","week","30days","month","all"],description:"Initial time period"}),launcher:r.boolean({char:"l",default:!1,description:"Open the launcher overlay immediately"})};async run(){let{flags:e}=await this.parse(s),{renderDashboard:t}=await import("../dashboard/Dashboard.js");await t(e.period,{openLauncher:e.launcher})}};export{a as default};