toolroll 0.9.108 → 0.9.109

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 (88) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/dist/advanced-view.js +0 -1
  3. package/dist/agent-fence.js +35 -4
  4. package/dist/agent-state.js +5 -2
  5. package/dist/assignment-ui.js +5 -5
  6. package/dist/assignment.js +5 -2
  7. package/dist/browser/terminal.js +1 -1
  8. package/dist/browser/workspace.css +1 -1
  9. package/dist/browser/workspace.js +37 -34
  10. package/dist/browser-crew.js +4 -4
  11. package/dist/browser-workspace.js +4 -11
  12. package/dist/builder.js +9 -1
  13. package/dist/chat-controls.js +6 -5
  14. package/dist/chat-decide.js +1 -1
  15. package/dist/chat-quiet.js +3 -3
  16. package/dist/chat-voice.js +2 -2
  17. package/dist/cli-help.js +12 -13
  18. package/dist/cli.js +4 -3
  19. package/dist/console-chrome.js +10 -3
  20. package/dist/contracts/console-api.js +4 -3
  21. package/dist/contracts/handoff.js +4 -0
  22. package/dist/decision.js +17 -0
  23. package/dist/demo-chat.js +1 -1
  24. package/dist/demo.js +6 -0
  25. package/dist/design/kit.js +4 -3
  26. package/dist/dispatch.js +3 -8
  27. package/dist/flexible-available.js +1 -0
  28. package/dist/flexible-schema.js +32 -0
  29. package/dist/flexible-thread-schema.js +30 -0
  30. package/dist/flexible-thread.js +526 -0
  31. package/dist/flexible-ui.js +44 -0
  32. package/dist/flexible.js +359 -0
  33. package/dist/git-views.js +38 -38
  34. package/dist/guides.js +11 -10
  35. package/dist/keymap.js +1 -1
  36. package/dist/lead-context.js +1 -1
  37. package/dist/limits-ui.js +1 -1
  38. package/dist/live-bus.js +70 -13
  39. package/dist/needs-you.js +3 -3
  40. package/dist/nightly-github.js +2 -2
  41. package/dist/operate.js +111 -3
  42. package/dist/project-delete-ui.js +2 -1
  43. package/dist/project-delete.js +1 -0
  44. package/dist/provider-auth.js +1 -1
  45. package/dist/release.js +1 -0
  46. package/dist/result-actions.js +3 -0
  47. package/dist/result-evidence-readers.js +8 -2
  48. package/dist/result-review.js +20 -9
  49. package/dist/serve.js +32 -29
  50. package/dist/server/chat.js +9 -9
  51. package/dist/server/chrome.js +16 -16
  52. package/dist/server/guards.js +10 -4
  53. package/dist/server/home.js +37 -5
  54. package/dist/server/http.js +4 -2
  55. package/dist/server/in-place.js +5 -4
  56. package/dist/server/kit.js +2 -2
  57. package/dist/server/live.js +100 -10
  58. package/dist/server/pages.js +79 -53
  59. package/dist/server/render-chat.js +1 -1
  60. package/dist/server/render-history.js +18 -4
  61. package/dist/server/render-new-task.js +2 -2
  62. package/dist/server/render-pages.js +21 -39
  63. package/dist/server/render-people.js +2 -2
  64. package/dist/server/render-projects.js +5 -5
  65. package/dist/server/render-results.js +26 -10
  66. package/dist/server/render-tasks.js +26 -17
  67. package/dist/server/retired-routes.js +37 -4
  68. package/dist/server/route-policy.js +8 -0
  69. package/dist/server/route-table.js +13 -4
  70. package/dist/server/settings-computers.js +140 -0
  71. package/dist/server/settings-scripts.js +15 -0
  72. package/dist/server/settings-section-table.js +56 -0
  73. package/dist/server/settings-sections.js +258 -0
  74. package/dist/server/settings.js +164 -19
  75. package/dist/server/task-views.js +47 -13
  76. package/dist/server/tasks.js +143 -90
  77. package/dist/server/welcome.js +6 -5
  78. package/dist/settings-groups-ui.js +24 -105
  79. package/dist/settings-proofs.js +5 -2
  80. package/dist/sqlite-telemetry.js +70 -21
  81. package/dist/store.js +108 -9
  82. package/dist/task-link.js +64 -0
  83. package/dist/tui.js +1 -1
  84. package/dist/typed-words-schema.js +18 -0
  85. package/dist/welcome-facts.js +3 -2
  86. package/dist/work-index.js +126 -29
  87. package/dist/work-reads.js +279 -0
  88. package/package.json +4 -2
@@ -1,4 +1,3 @@
1
- import { ACCENT_PRESETS, accentNote } from "./accent-colors.js";
2
1
  import {} from "./browser-workspace.js";
3
2
  import { SETTINGS_GROUP_ICONS, SETTINGS_GROUPS, plural } from "./design/kit.js";
4
3
  import { digestTimes } from "./digest-times.js";
@@ -8,11 +7,11 @@ import {} from "./scope.js";
8
7
  import { qualityModeTitle } from "./quality.js";
9
8
  import {} from "./store.js";
10
9
  import { kitSectionForm, SECRET_OPT_OUTS } from "./settings-kit.js";
11
- import { ADVANCED_PAGES } from "./advanced-view.js";
10
+ import { START_BUILDER_HREF } from "./needs-you.js";
12
11
  import { btn, chip, codeLine, disclose, formRow, infoLine, input, needsPanel, note, notice, radios, select, settingsLink, settingsLinks, settingsRecord, settingsSection, settingsShell, switchInput, } from "./server/kit.js";
13
12
  export const GROUP_PATHS = {
14
- "/settings": "hub", "/settings/general": "general", "/settings/agents": "agents", "/settings/alerts": "alerts",
15
- "/settings/projects": "projects", "/settings/access": "access", "/settings/system": "system", "/settings/advanced": "advanced",
13
+ "/settings": "hub", "/settings/agents": "agents", "/settings/alerts": "alerts",
14
+ "/settings/projects": "projects", "/settings/access": "access", "/settings/system": "system",
16
15
  };
17
16
  const CHAT_APPS = [["telegram", "Telegram"], ["slack", "Slack"], ["discord", "Discord"], ["teams", "Teams"]];
18
17
  const and = (names) => names.length > 1 ? `${names.slice(0, -1).join(", ")} and ${names.at(-1)}` : names[0] ?? "";
@@ -23,8 +22,8 @@ const answered = (facts) => facts.problem ? notice(sentence(facts.problem)) : fa
23
22
  export function settingsNeeds(facts) {
24
23
  const out = [];
25
24
  if (facts.workers !== null && facts.approver && !facts.workers.some(one => one.tone === "ok")) {
26
- out.push({ group: "agents", title: facts.workers.length === 0 ? "Nothing is taking work" : "Nothing is taking work right now",
27
- text: "Approved work waits until a computer builds it. Run toolroll up on the computer with your projects.", action: ["Start taking work", "/settings/agents#workers"] });
25
+ out.push({ group: "computers", title: facts.workers.length === 0 ? "Nothing is taking work" : "Nothing is taking work right now",
26
+ text: "Approved work waits until a computer builds it. Run toolroll up on the computer with your projects.", action: ["Start taking work", START_BUILDER_HREF] });
28
27
  }
29
28
  if (facts.telegram.failing)
30
29
  out.push({ group: "alerts", title: "Telegram isn’t delivering", text: facts.telegram.delivery ?? "Alerts to your phone are failing.", action: ["Open Telegram", "/settings/telegram"] });
@@ -38,13 +37,17 @@ export function needsByGroup(items) {
38
37
  out[item.group] = (out[item.group] ?? 0) + 1;
39
38
  return out;
40
39
  }
41
- const flagsOf = (counts) => Object.fromEntries(Object.keys(counts).map(key => [key, true]));
40
+ export const flagsOf = (counts) => Object.fromEntries(Object.keys(counts).map(key => [key, true]));
42
41
  const themeWords = (theme) => theme === "light" ? "Light" : theme === "dark" ? "Dark" : "Match this device";
43
42
  function agentsWords(facts) {
44
43
  const signed = facts.providers?.find(one => one.connection !== null && one.tone === "ok") ?? facts.providers?.find(one => one.tone === "ok");
45
- const builders = facts.workers === null ? null : facts.workers.filter(one => one.tone === "ok").length;
46
- return [signed ? `${signed.name}: ${signed.words}` : facts.providers === null ? "Models, chat and tools" : "No agent signed in yet",
47
- builders === null ? null : builders === 0 ? "not taking work yet" : "taking work"].filter(Boolean).join(" · ");
44
+ return signed ? `${signed.name}: ${signed.words}` : facts.providers === null ? "Models, chat and tools" : "No agent signed in yet";
45
+ }
46
+ function computersWords(facts) {
47
+ if (facts.workers === null)
48
+ return "Connect a builder: the computer that does the work";
49
+ const taking = facts.workers.filter(one => one.tone === "ok").length;
50
+ return taking === 0 ? "Nothing is taking work yet" : `${plural(taking, "computer", "computers")} taking work`;
48
51
  }
49
52
  function alertsWords(facts) {
50
53
  const configured = facts.messaging?.configured ?? [];
@@ -71,26 +74,19 @@ function systemWords(facts) {
71
74
  }
72
75
  function localModeSection(facts) {
73
76
  const local = facts.local;
74
- if (local === undefined || local === null)
75
- return html ``;
76
- if (local.owner) {
77
- return local.passwordSet ? html `` : settingsSection({ id: "set-password", title: "Let agents work on their own",
78
- lead: "Agents can work on their own, merge and release only after you set a password.",
79
- body: html `<div class="k-acts">${btn("Set a password", { sm: true, href: "/password/set?next=%2Fsettings" })}</div>` });
80
- }
81
- if (!local.canTurnOff)
77
+ if (local === undefined || local === null || !local.owner || local.passwordSet)
82
78
  return html ``;
83
- return settingsSection({ id: "local-mode", title: "Local mode", state: " · on",
84
- lead: "A browser on this computer can file tasks, approve plans and add projects without your password.",
85
- body: kitSectionForm({ proof: "local-mode-off", action: "/settings/local-mode/off", id: "local-mode-form", save: { label: "Turn off", variant: "outline" },
86
- confirm: "Turn off local mode", body: html `` }) });
79
+ return settingsSection({ id: "set-password", title: "Let agents work on their own",
80
+ lead: "Agents can work on their own, merge and release only after you set a password.",
81
+ body: html `<div class="k-acts">${btn("Set a password", { sm: true, href: "/password/set?next=%2Fsettings" })}</div>` });
87
82
  }
88
83
  export function settingsHub(facts) {
89
84
  const items = settingsNeeds(facts);
90
85
  const counts = needsByGroup(items);
91
86
  const words = {
92
- general: [`Theme: ${themeWords(facts.theme).toLowerCase()}`, facts.version === null ? null : `Toolroll ${facts.version}`].filter(Boolean).join(" · "),
87
+ general: [`Theme: ${themeWords(facts.theme).toLowerCase()}`, facts.version === null ? null : `Toolroll ${facts.version}`, `advanced features ${advancedOn(facts) ? "on" : "off"}`].filter(Boolean).join(" · "),
93
88
  agents: agentsWords(facts),
89
+ computers: computersWords(facts),
94
90
  alerts: alertsWords(facts),
95
91
  approval: approvalWords(facts),
96
92
  projects: facts.projects.length === 0 ? "No projects yet" : `${plural(facts.projects.length, "project", "projects")} · network, checks, pull requests and tools for each`,
@@ -100,7 +96,6 @@ export function settingsHub(facts) {
100
96
  };
101
97
  const shown = SETTINGS_GROUPS.filter(([, slug]) => slug !== "spend" || facts.operator).filter(([, slug]) => slug !== "system" || facts.operator || facts.approver)
102
98
  .filter(([, slug]) => slug !== "spend" || advancedOn(facts));
103
- words["advanced"] = advancedWords(facts);
104
99
  const panel = needsPanel(items.map((item, index) => ({ title: item.title, text: item.text, action: btn(item.action[0], { variant: index === 0 ? "primary" : "outline", href: item.action[1] }) })));
105
100
  return settingsShell({
106
101
  group: "hub", title: "Settings", flags: flagsOf(counts),
@@ -113,53 +108,11 @@ export function settingsHub(facts) {
113
108
  });
114
109
  }
115
110
  export const HUB_ANCHORS = {
116
- providers: "/settings/agents#providers", workers: "/settings/agents#workers", email: "/settings/alerts#email", "settings-chat-apps": "/settings/alerts#chat-apps",
111
+ providers: "/settings/agents#providers", workers: "/settings/computers#workers", email: "/settings/alerts#email", "settings-chat-apps": "/settings/alerts#chat-apps",
117
112
  "telegram-token": "/settings/alerts#telegram-token", phone: "/settings/alerts#phone", notifications: "/settings/alerts#notifications",
118
113
  updates: "/settings/system#updates", accent: "/settings/general#appearance", appearance: "/settings/general#appearance",
119
114
  };
120
115
  export const HUB_ANCHOR_SCRIPT = `(function(){var m=${JSON.stringify(HUB_ANCHORS)};var h=decodeURIComponent(location.hash.slice(1));if(Object.prototype.hasOwnProperty.call(m,h))location.replace(m[h]);})();`;
121
- const ACCENT_CHOICES = ACCENT_PRESETS.slice(0, 6);
122
- export function generalGroup(facts, flags) {
123
- const themeButton = (value, label) => html `<button type="submit" name="theme" value="${value}" aria-pressed="${String(facts.theme === value)}">${label}</button>`;
124
- const custom = ACCENT_CHOICES.some(one => one.hex === facts.accent) ? null : facts.accent;
125
- const accentNoteWords = accentNote(facts.accent);
126
- const appearance = settingsSection({
127
- id: "appearance", title: "Appearance", state: " · saved for this browser",
128
- body: joinHtml([
129
- formRow("Theme", "Light, dark, or whatever this device uses.", postForm("/settings/appearance", html `<div class="k-seg" role="group" aria-label="Theme">${themeButton("system", "Match device")}${themeButton("light", "Light")}${themeButton("dark", "Dark")}</div>`, { returnTo: "/settings/general" })),
130
- kitSectionForm({ proof: "appearance", action: "/settings/appearance", id: "accent", gate: true, hidden: { return: "/settings/general" },
131
- body: joinHtml([
132
- formRow("Accent", "Buttons, focus and what needs you.", select({ name: "accent", label: "Accent", current: facts.accent, items: [...ACCENT_CHOICES.map(one => [one.hex, one.id === "ink" ? "Ink (default)" : one.name]), ...(custom === null ? [] : [[custom, `Your own colour (${custom})`]])] })),
133
- accentNoteWords === null ? "" : note(accentNoteWords),
134
- ]) }),
135
- disclose("Use your own colour", kitSectionForm({ proof: "appearance", action: "/settings/appearance", id: "accent-own", gate: true, hidden: { return: "/settings/general" },
136
- body: formRow("Your own colour", "Six hex digits, like #6e56cf.", input({ id: "accent-hex", name: "accent", value: custom ?? "", attrs: { placeholder: "#6e56cf", spellcheck: "false", autocomplete: "off", "aria-label": "Your own colour", pattern: "#?[0-9a-fA-F]{6}", required: true } })) }), custom !== null),
137
- ]),
138
- });
139
- const browser = settingsSection({
140
- id: "this-browser", title: "This browser",
141
- body: joinHtml([
142
- formRow("Remembered password", "After you type your password, standard approvals skip it on this computer for 15 minutes. Forget ends that now.", facts.browser ? postForm("/session/forget-password", btn("Forget now", { sm: true, type: "submit" }), { returnTo: "/settings/general" }) : html ``, "inline"),
143
- ]),
144
- });
145
- const password = settingsSection({
146
- id: "your-password", title: "Your password",
147
- body: joinHtml([
148
- formRow("Where it is", "If you started Toolroll with toolroll up, your password is saved on the computer running Toolroll. Toolroll never shows it in a browser. To read it, run this there:", html ``, "wide"),
149
- codeLine("cat ~/.config/toolroll/.toolroll-secrets/up-login.txt"),
150
- facts.passwordless === null ? "" : formRow("Passwordless", "Sign in once; most approvals then need no password.", btn(`${facts.passwordless ? "On" : "Off"} · Change`, { sm: true, href: "/settings/passwordless" }), "inline"),
151
- ]),
152
- });
153
- const version = facts.version === null ? "" : settingsSection({
154
- id: "version", title: "Version",
155
- body: joinHtml([
156
- formRow("Toolroll", facts.firstResult ?? "Installed on this computer.", html `<span class="k-mono">${facts.version}</span>`, "inline"),
157
- facts.operator ? formRow("Updates", null, btn("Open updates", { sm: true, variant: "ghost", href: "/settings/updates" }), "inline") : "",
158
- ]),
159
- });
160
- const withPassword = passwordFree(facts) ? [] : [browser, password];
161
- return settingsShell({ group: "general", title: "General", lead: "How Toolroll looks and behaves in this browser.", flags, body: joinHtml([answered(facts), appearance, ...withPassword, version]) });
162
- }
163
116
  const toneChip = (tone, words) => chip(words, tone === "ok" ? "done" : tone === "warn" ? "failed" : "");
164
117
  function providerRecord(one) {
165
118
  const form = kitSectionForm({ proof: "provider-key", action: "/settings/provider-key", id: `provider-${one.provider}`, gate: true, hidden: { provider: one.provider }, save: { label: `Save ${one.name}` },
@@ -173,21 +126,6 @@ function providerRecord(one) {
173
126
  return settingsRecord({ title: html `${one.name} ${toneChip(one.tone, one.words)}`, sub: one.connection === null ? one.usage : `${one.connection.words}${one.connection.facts ? ` · ${one.connection.facts}` : ""}`,
174
127
  attrs: { "data-provider": one.provider }, more: disclose(`Manage ${one.name}`, joinHtml([form, remove])) });
175
128
  }
176
- function workersSection(workers) {
177
- return settingsSection({
178
- id: "workers", title: "Builders", lead: "The computers that build approved work, and what each runs now.",
179
- body: workers.length === 0
180
- ? joinHtml([note("No builder is connected. Run this on the computer with your projects:"), codeLine("toolroll up")])
181
- : joinHtml([
182
- ...workers.map(one => settingsRecord({
183
- title: html `<span class="k-mono">${one.name}</span> ${chip(one.state, one.tone === "ok" ? "done" : one.tone === "off" ? "failed" : "")}`,
184
- sub: one.running.length === 0 ? "Nothing running" : joinHtml(one.running.map(task => html `<a class="k-link" href="${task.href}">${task.title}</a>${task.project === null ? "" : html ` <span class="k-muted">${task.project}</span>`}`), " · "),
185
- when: html `<span class="k-num">${one.busy} of ${one.capacity}</span> running`, attrs: { "data-worker": one.name },
186
- })),
187
- note(html `To change how many a builder runs at once: <code class="k-mono">toolroll runner capacity &lt;name&gt; &lt;n&gt;</code>`),
188
- ]),
189
- });
190
- }
191
129
  export function agentsGroup(facts, flags) {
192
130
  const providers = facts.providers === null ? "" : settingsSection({
193
131
  id: "providers", title: "How agents are paid for", lead: "A plan first; an API key is used when the agent is set to it, or for agents without a plan. Keys stay on this computer.",
@@ -204,7 +142,7 @@ export function agentsGroup(facts, flags) {
204
142
  ]);
205
143
  return settingsShell({
206
144
  group: "agents", title: "Agents and models", lead: "Which agent does the work, how it’s paid for, and which model plans, builds and reviews.", flags,
207
- body: joinHtml([answered(facts), providers, facts.workers === null ? "" : workersSection(facts.workers), links]),
145
+ body: joinHtml([answered(facts), providers, facts.workers === null ? "" : html `<div id="workers">${settingsLinks(null, [settingsLink({ href: "/settings/computers?section=builders", title: "Computers that build", status: "In Settings → Computers" })], { label: "Computers" })}</div>`, links]),
208
146
  });
209
147
  }
210
148
  function chatAppsSection(facts) {
@@ -234,7 +172,7 @@ function reachSection(facts) {
234
172
  const projects = (chat.projects ?? []).length === 0 ? "" : joinHtml([
235
173
  ...chat.projects.map(one => kitSectionForm({ proof: "notifications-mute", action: "/settings/notifications/mute", id: `mute-${one.repo.replace(/[^a-z0-9]+/gi, "-")}`, gate: true, hidden: { repo: one.repo },
236
174
  body: formRow(one.name, one.muted ? "Muted: no pings" : "Pings on", switchInput({ id: `pings-${one.repo.replace(/[^a-z0-9]+/gi, "-")}`, name: "pings", label: "Pings", on: !one.muted, attrs: { "aria-label": `Pings for ${one.name}` } }), "inline") })),
237
- note("Muted projects still show in Tasks and the evening digest."),
175
+ note("Muted projects still show in Work and the evening digest."),
238
176
  ]);
239
177
  return settingsSection({ id: "notifications", title: "What reaches you", body: joinHtml([form, projects]) });
240
178
  }
@@ -429,9 +367,10 @@ export function accessGroup(facts, flags) {
429
367
  ...(facts.operator && (advancedOn(facts) || facts.passwordless === true) ? [
430
368
  settingsLink({ href: "/settings/passwordless", title: "Passwordless", status: facts.passwordless ? "On: signing in is the only password" : "Off: approvals ask for your password" })
431
369
  ] : []),
370
+ ...(facts.local?.canTurnOff === true ? [html `<div id="local-mode">${settingsLink({ href: "/settings/general?section=local-mode", title: "Local mode", status: "On · in General" })}</div>`] : []),
432
371
  ];
433
372
  return settingsShell({ group: "access", title: "People and sign-in", lead: "Who can get in, how they sign in, and the ways in they hold.", flags,
434
- body: joinHtml([answered(facts), localModeSection(facts), settingsLinks(null, links, { label: "People and sign-in" })]) });
373
+ body: joinHtml([answered(facts), settingsLinks(null, links, { label: "People and sign-in" })]) });
435
374
  }
436
375
  function updatesSection(updates) {
437
376
  const latest = updates.latest;
@@ -458,10 +397,8 @@ export function systemGroup(facts, flags) {
458
397
  ...(advancedOn(facts) ? [settingsLink({ href: "/settings/monitoring", title: "Monitoring", status: "Send the audit stream and traces to your own systems" })] : []),
459
398
  settingsLink({ href: "/settings/data", title: "Data export", status: "Everything except secrets, as one download" }),
460
399
  settingsLink({ href: "/settings/integrations", title: "Integrations", status: "Which connected services work" }),
461
- ...(advancedOn(facts) ? [settingsLink({ href: "/fleet", title: "Builders", status: "Every computer that builds, on Agents" })] : []),
462
400
  ]) : settingsLinks("In this group", [
463
401
  settingsLink({ href: "/settings/integrations", title: "Integrations", status: "Which connected services work" }),
464
- ...(advancedOn(facts) ? [settingsLink({ href: "/fleet", title: "Builders", status: "Every computer that builds" })] : []),
465
402
  ]);
466
403
  return settingsShell({ group: "system", title: "System", lead: "This Toolroll’s version, backups, storage and what leaves this computer.", flags,
467
404
  body: joinHtml([answered(facts), facts.updates === null ? "" : updatesSection(facts.updates), links]) });
@@ -470,13 +407,11 @@ export function settingsGroupPage(group, facts) {
470
407
  const flags = flagsOf(needsByGroup(settingsNeeds(facts)));
471
408
  switch (group) {
472
409
  case "hub": return settingsHub(facts);
473
- case "general": return generalGroup(facts, flags);
474
410
  case "agents": return agentsGroup(facts, flags);
475
411
  case "alerts": return alertsGroup(facts, flags);
476
412
  case "projects": return projectsGroup(facts, flags);
477
413
  case "access": return accessGroup(facts, flags);
478
414
  case "system": return systemGroup(facts, flags);
479
- case "advanced": return advancedGroup(facts, flags);
480
415
  case "approval": return settingsHub(facts);
481
416
  }
482
417
  }
@@ -616,19 +551,3 @@ function passwordFree(facts) {
616
551
  return facts.local?.owner === true && !facts.local.passwordSet;
617
552
  }
618
553
  function advancedOn(facts) { return facts.advanced === undefined || facts.advanced.on; }
619
- function advancedWords(facts) {
620
- return advancedOn(facts) ? "On: every page shows in the menus" : "Off: menus show only the main steps";
621
- }
622
- export function advancedGroup(facts, flags) {
623
- const on = advancedOn(facts);
624
- const change = facts.advanced?.canChange === true
625
- ? postForm("/settings/advanced", btn(on ? "Turn off" : "Turn on", { sm: true, type: "submit" }), { hidden: { advanced: on ? "off" : "on" } })
626
- : html ``;
627
- const toggle = settingsSection({ id: "show-advanced", title: "Show advanced features", state: on ? " · on" : " · off", right: change,
628
- lead: "Flows, other computers, spend limits, operating modes and the rest, in your menus. They keep working either way, and each opens from below.",
629
- body: html `` });
630
- const pages = ADVANCED_PAGES.filter(one => one.operator !== true || facts.operator)
631
- .map(one => settingsLink({ href: one.href, title: one.title, status: one.words }));
632
- return settingsShell({ group: "advanced", title: "Advanced", lead: "Everything beyond filing, approving and accepting work.", flags,
633
- body: joinHtml([answered(facts), toggle, settingsLinks("Advanced pages", pages)]) });
634
- }
@@ -50,12 +50,14 @@ export const PROOF_INVENTORY = [
50
50
  { id: "people-close", action: "Cancel an invite or remove a person", routes: ["/people/invite-revoke", "/people/revoke"], form: "peopleRevoke", field: "token", proof: "step-up", ...ACCEPT, role: "any", handlerRole: "an approver", secrets: [], terms: [] },
51
51
  { id: "project-setup", action: "Approve project setup", routes: ["/control/setup-approve"], form: "projectSetup", field: "token", proof: "step-up", ...ACCEPT, role: "any", handlerRole: "an approver of the project; models for a new installation need an instance operator", secrets: [], terms: ["repo", "nonce", "fingerprint", "provider", "model", "command", "seconds"], note: "the nonce is spent before the password is checked: after a refusal, review again; the reviewed inputs are previewed again and must match the fingerprint" },
52
52
  { id: "project-instructions", action: "Add the agent instructions", routes: ["/control/instructions-approve"], form: "projectSetup", field: "token", proof: "step-up", ...ACCEPT, role: "any", handlerRole: "an approver of the project", secrets: [], terms: ["repo", "nonce", "fingerprint"], note: "the nonce is spent before the password is checked" },
53
+ { id: "runner-retire", action: "Retire a computer that builds", routes: ["/fleet/runner/retire"], form: "runnerRetire", field: "token", proof: "step-up", ...ACCEPT, role: "any", handlerRole: "an approver, from a browser", secrets: [], terms: ["name"] },
53
54
  { id: "local-mode-off", action: "Turn off local mode", routes: ["/settings/local-mode/off"], form: "localModeOff", field: "password", proof: "step-up", ...ACCEPT, role: "operator", handlerRole: "a full session (never the local owner)", secrets: [], terms: [] },
54
55
  { id: "mode-sign", action: "Sign an operating mode", routes: ["/mode/sign"], form: "mode", field: "token", proof: "step-up", ...ACCEPT, role: "any", handlerRole: "an approver of the project", secrets: [], terms: MODE_TERMS },
55
56
  { id: "mode-sign-chat-approve", action: "Sign an operating mode that lets your chat app approve", routes: ["/mode/sign"], select: { field: "chat-approve", value: "1" }, form: "mode", field: "token", proof: "credential", ...CREDENTIAL, role: "any", handlerRole: "an approver of the project", secrets: [], terms: MODE_TERMS },
56
57
  { id: "mode-sign-repair", action: "Sign an operating mode that repairs failed checks by itself", routes: ["/mode/sign"], select: { field: "repair-auto", value: "1" }, form: "mode", field: "token", proof: "credential", ...CREDENTIAL, role: "any", handlerRole: "an approver of the project", secrets: [], terms: MODE_TERMS },
57
58
  { id: "passwordless-on", action: "Turn Passwordless on", routes: ["/settings/passwordless"], form: "passwordless", field: "password", proof: "credential", when: "only to turn it on (off needs nothing)", ...CREDENTIAL, role: "operator", secrets: [], terms: [] },
58
59
  { id: "sign-in", action: "Change sign-in (SSO)", routes: ["/settings/sign-in"], form: "signIn", field: "password", proof: "credential", when: "every action except Test", ...CREDENTIAL, role: "operator", secrets: ["client-secret"], terms: [] },
60
+ { id: "project-flexible", action: "Turn on Flexible", routes: ["/settings/project/flexible"], form: "projectFlexible", field: "password", proof: "credential", when: "only to turn it on (lowering and turning off need nothing)", ...CREDENTIAL, role: "approver", handlerRole: "an approver of the project", secrets: [], terms: ["repo", "action", "digest"], note: "`digest` is the terms the page showed; the handler rebuilds them and refuses a difference" },
59
61
  { id: "release-approval", action: "Approve releases automatically", routes: ["/settings/release-approval"], form: "releaseApproval", field: "password", proof: "credential", when: "only to approve automatically (Ask me needs nothing)", ...CREDENTIAL, role: "approver", handlerRole: "an approver of the project", secrets: [], terms: ["repo"] },
60
62
  { id: "project-network", action: "Change what builds may reach", routes: ["/settings/project/network"], form: "projectNetwork", field: "password", proof: "credential", ...CREDENTIAL, role: "any", handlerRole: "an approver of the project", secrets: [], terms: ["repo"] },
61
63
  { id: "project-fallback", action: "Change a project's fallback agents", routes: ["/settings/project/fallback"], form: "projectFallback", field: "password", proof: "credential", ...CREDENTIAL, role: "any", handlerRole: "an approver of the project", secrets: [], terms: [] },
@@ -64,8 +66,9 @@ export const PROOF_INVENTORY = [
64
66
  { id: "project-check-access", action: "Narrow how far checks reach", routes: ["/settings/project/check-access"], form: "projectCheckAccess", field: "password", proof: "credential", ...CREDENTIAL, role: "any", handlerRole: "an approver of the project", secrets: [], terms: ["repo"], note: "for a form that can only narrow; one that offers a wider level uses project-check-access-widen" },
65
67
  { id: "project-check-access-widen", action: "Widen how far checks reach", routes: ["/settings/project/check-access"], explicit: true, form: "projectCheckAccess", field: "password", proof: "typed-now-operator", ...TYPED, role: "any", handlerRole: "an instance operator", secrets: [], terms: ["repo"], note: "the server decides whether a choice widens; a form offering any wider level asks for this proof" },
66
68
  ...CHAT_APPS.map(([app, name, form, secrets]) => ({ id: `${app}-open`, action: `Connect or pair ${name}`, routes: [`/settings/${app}/connect`, `/settings/${app}/pair`], form, field: "password", proof: "credential", ...CREDENTIAL, role: "approver", secrets, terms: [] })),
67
- { id: "sessions-token", action: "Make an API token", routes: ["/settings/sessions"], form: "sessions", field: "password", proof: "credential", when: "only to make a token (ending sessions and revoking tokens need nothing)", ...CREDENTIAL, role: "any", secrets: [], notProof: ["token"], terms: [], note: "`token` here names an API token to revoke" },
68
- { id: "people-invite", action: "Invite someone", routes: ["/people/invite"], form: "peopleInvite", field: "token", proof: "credential", ...CREDENTIAL, role: "any", handlerRole: "an approver", secrets: [], terms: [] },
69
+ { id: "sessions-token", action: "Make an API token", routes: ["/settings/sessions"], form: "sessions", field: "password", proof: "credential", when: "only to make a token (ending sessions and revoking tokens need nothing)", ...CREDENTIAL, role: "any", secrets: [], notProof: ["token"], terms: [], reveal: "once", note: "`token` here names an API token to revoke" },
70
+ { id: "people-invite", action: "Invite someone", routes: ["/people/invite"], form: "peopleInvite", field: "token", proof: "credential", ...CREDENTIAL, role: "any", handlerRole: "an approver", secrets: [], terms: [], reveal: "once" },
71
+ { id: "runner-register", action: "Register a computer that builds", routes: ["/fleet/runner/register"], form: "runnerRegister", field: "token", proof: "credential", ...CREDENTIAL, role: "any", handlerRole: "an approver, from a browser", secrets: [], terms: ["nonce"], reveal: "once", note: "`token` is the person's own password; `nonce` is the register document's one-use form token (spent before the password is checked: after a refusal, register again from the document); the worker's new token is shown once on the answer and only its hash is kept" },
69
72
  { id: "people-projects", action: "Change a person's projects", routes: ["/people/projects"], form: "peopleProjects", field: "token", proof: "credential", ...CREDENTIAL, role: "operator", secrets: [], terms: ["name"] },
70
73
  { id: "telegram-pair", action: "Pair your phone with Telegram", routes: ["/settings/telegram/pair"], form: "telegramPair", field: "password", proof: "typed-password", ...TYPED, role: "approver", secrets: [], terms: [] },
71
74
  { id: "chat-approval-save", action: "Turn on approving from chat", routes: ["/settings/chat-approval/save"], form: "chatApproval", field: "token", proof: "typed-password", ...TYPED, role: "approver", secrets: [], terms: ["nonce", "digest", "scope", "full-access", "cap-usd"] },
@@ -1,3 +1,9 @@
1
+ let writes = 0;
2
+ export const writesSoFar = () => writes;
3
+ const ownTemp = (op) => /^(?:CREATE\s+TEMP\s+TABLE\s+"so_work_ranked_\d+"|DROP\s+TABLE\s+IF\s+EXISTS\s+temp\."so_work_ranked_\d+"$)/i.test(op);
4
+ const opening = (op) => /^(?:BEGIN(?:\s+(?:DEFERRED|IMMEDIATE|EXCLUSIVE))?(?:\s+TRANSACTION)?|SAVEPOINT\s+\w+)\s*;?$/i.test(op);
5
+ const settingOnly = (op) => /^PRAGMA\s+busy_timeout\s*=\s*\d+\s*;?$/i.test(op);
6
+ const ending = (op) => /^(?:COMMIT|END|ROLLBACK|RELEASE)\b[^;]*;?\s*$/i.test(op);
1
7
  const states = new WeakMap();
2
8
  export function measureWriteWait(db, body) {
3
9
  const state = states.get(db);
@@ -34,34 +40,77 @@ export function instrumentDatabase(db, telemetry) {
34
40
  telemetry.writeHold.observe(elapsed(heldAt));
35
41
  heldAt = null;
36
42
  } };
43
+ let openedAt = null;
44
+ const native = db;
45
+ const counted = (counts, body) => {
46
+ if (counts)
47
+ writes++;
48
+ try {
49
+ return body();
50
+ }
51
+ catch (error) {
52
+ writes++;
53
+ throw error;
54
+ }
55
+ };
56
+ const execNow = (sql, op) => {
57
+ if (/^BEGIN\s+(?:IMMEDIATE|EXCLUSIVE)\b/i.test(op)) {
58
+ const at = telemetry.clock();
59
+ try {
60
+ db.exec(sql);
61
+ heldAt = telemetry.clock();
62
+ }
63
+ finally {
64
+ if (!state.measuringWait)
65
+ telemetry.writeWait.observe(elapsed(at));
66
+ }
67
+ }
68
+ else if (/^(?:COMMIT|END|ROLLBACK(?!\s+TO))\b/i.test(op)) {
69
+ db.exec(sql);
70
+ finish();
71
+ }
72
+ else
73
+ standalone(writing(op), () => db.exec(sql));
74
+ };
75
+ const counts = (op, path, write) => {
76
+ if (ownTemp(op) || settingOnly(op))
77
+ return false;
78
+ if (opening(op)) {
79
+ if (openedAt === null && native.isTransaction !== true)
80
+ openedAt = writes;
81
+ return false;
82
+ }
83
+ if (ending(op))
84
+ return openedAt === null || writes !== openedAt;
85
+ return path !== 'read' || write;
86
+ };
87
+ const settled = (op) => {
88
+ if (native.isTransaction === false || (native.isTransaction === undefined && /^(?:COMMIT|END|ROLLBACK(?!\s+TO))\b/i.test(op)))
89
+ openedAt = null;
90
+ };
91
+ const tracked = (op, path, write, body) => {
92
+ try {
93
+ return counted(counts(op, path, write), body);
94
+ }
95
+ finally {
96
+ settled(op);
97
+ }
98
+ };
37
99
  const methods = {
38
100
  exec(sql) {
39
101
  const op = operation(sql);
40
- if (/^BEGIN\s+(?:IMMEDIATE|EXCLUSIVE)\b/i.test(op)) {
41
- const at = telemetry.clock();
42
- try {
43
- db.exec(sql);
44
- heldAt = telemetry.clock();
45
- }
46
- finally {
47
- if (!state.measuringWait)
48
- telemetry.writeWait.observe(elapsed(at));
49
- }
50
- }
51
- else if (/^(?:COMMIT|END|ROLLBACK(?!\s+TO))\b/i.test(op)) {
52
- db.exec(sql);
53
- finish();
54
- }
55
- else
56
- standalone(writing(op), () => db.exec(sql));
102
+ tracked(op, 'exec', true, () => execNow(sql, op));
57
103
  },
58
104
  prepare(sql) {
59
- const statement = db.prepare(sql), write = writing(operation(sql));
105
+ const op = operation(sql), statement = db.prepare(sql), write = writing(op);
60
106
  const methods = {
61
- run: (...params) => standalone(write, () => statement.run(...params)),
62
- get: (...params) => standalone(write, () => statement.get(...params)),
63
- all: (...params) => standalone(write, () => statement.all(...params)),
107
+ run: (...params) => tracked(op, 'run', write, () => standalone(write, () => statement.run(...params))),
108
+ get: (...params) => tracked(op, 'read', write, () => standalone(write, () => statement.get(...params))),
109
+ all: (...params) => tracked(op, 'read', write, () => standalone(write, () => statement.all(...params))),
64
110
  };
111
+ const rows = statement;
112
+ if (typeof rows.iterate === 'function')
113
+ Object.assign(methods, { iterate: (...params) => tracked(op, 'read', write, () => rows.iterate(...params)) });
65
114
  return preservingNative(statement, methods);
66
115
  },
67
116
  close() { try {
package/dist/store.js CHANGED
@@ -17,6 +17,10 @@ import { V158_ADDED_COLUMNS, V158_SCHEMA, V158_STEPS, LEAD_FAILURE_DETAILS, LEAD
17
17
  import { V157_SCHEMA, V157_STEPS } from "./chat-live-schema.js";
18
18
  import { V159_ADDED_COLUMNS, V159_SCHEMA, V159_STEPS } from "./one-step-chat-schema.js";
19
19
  import { V160_BACKFILL, V160_SCHEMA, V160_STEPS } from "./advanced-schema.js";
20
+ import { V161_SCHEMA, V161_STEPS } from "./flexible-schema.js";
21
+ import { V162_SCHEMA, V162_STEPS } from "./flexible-thread-schema.js";
22
+ import { V163_SCHEMA, V163_STEPS } from "./typed-words-schema.js";
23
+ import { endLapsedFlexible } from "./flexible.js";
20
24
  import { refArchived, taskArchived, taskCancelled } from "./task-archive.js";
21
25
  export { refArchived, taskArchived } from "./task-archive.js";
22
26
  import { CHAT_PROVIDERS, CHAT_SCHEMA } from "./contracts/chat-tables.js";
@@ -819,7 +823,7 @@ export function checkSuitesOf(value) {
819
823
  }
820
824
  }
821
825
  const REGISTERED_AT_FILING = "again, as it was filed";
822
- export const SCHEMA_VERSION = 160;
826
+ export const SCHEMA_VERSION = 163;
823
827
  export const V118_MERGED_TABLES = Object.freeze({ api_token: "person", coordinator_credential: "coordinator", lead_credential: "lead" });
824
828
  const V118_REFERENCES = /REFERENCES (?:coordinator_credential\(cid\)|api_token\(id\))/g;
825
829
  const V118_COORDINATOR_COLUMNS = [["task_ref", "coordinator_cid"], ["coordinator_event", "cid"], ["mcp_idempotency", "cid"], ["coordinator_proposal", "cid"]];
@@ -884,7 +888,7 @@ export const V115_DROPPED_TABLES = Object.freeze([
884
888
  "fallback_config", "fallback_cycle", "fallback_transition",
885
889
  ]);
886
890
  const V115_DROPPED_REFERENCES = /\s+REFERENCES (?:contestant|contest|tournament_terms|session_turn|attended_authorization|held_session|fallback_cycle|fallback_config|fallback_transition|routine|routine_fire)\(id\)(?: ON DELETE CASCADE)?/g;
887
- export const UPDATE_SAFE_MIGRATIONS = Object.freeze([108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160]);
891
+ export const UPDATE_SAFE_MIGRATIONS = Object.freeze([108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163]);
888
892
  export const V119_ADDED_COLUMNS = Object.freeze({
889
893
  task_ref: { planning_generation: { definition: "INTEGER NOT NULL DEFAULT 0", saved: "0" } },
890
894
  run: { planning_generation: { definition: "INTEGER NOT NULL DEFAULT 0", saved: "0" } },
@@ -1427,7 +1431,7 @@ export { V156_STEPS };
1427
1431
  export { V157_STEPS };
1428
1432
  export { V158_STEPS };
1429
1433
  export { V159_STEPS };
1430
- export { V160_STEPS };
1434
+ export { V160_STEPS, V161_STEPS, V162_STEPS, V163_STEPS };
1431
1435
  export const RELEASE_ONCE_SCHEMA = `
1432
1436
  CREATE TABLE IF NOT EXISTS release_authority (
1433
1437
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -4205,7 +4209,7 @@ function initializeStore(db, file, options = {}) {
4205
4209
  throw new Error(`${file}: ${problem}; refusing to move chat history it cannot name`);
4206
4210
  }
4207
4211
  if (preflight === SCHEMA_VERSION && !findingSourcesStale(db)) {
4208
- const missing = codeMapShapeProblem(db) ?? viewPreferenceShapeProblem(db);
4212
+ const missing = codeMapShapeProblem(db) ?? viewPreferenceShapeProblem(db) ?? flexibleTermsShapeProblem(db) ?? flexibleThreadShapeProblem(db) ?? typedByPersonShapeProblem(db);
4209
4213
  if (missing !== null)
4210
4214
  throw new Error(`${file}: refusing to open — ${missing}, though the schema says v${SCHEMA_VERSION}`);
4211
4215
  db.exec("PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON;");
@@ -4547,6 +4551,21 @@ CREATE INDEX IF NOT EXISTS run_checkpoint_by_task ON run_checkpoint (task_ref, i
4547
4551
  }
4548
4552
  }
4549
4553
  step("advanced-preference");
4554
+ db.exec(V161_SCHEMA);
4555
+ const flexibleDamaged = flexibleTermsShapeProblem(db);
4556
+ if (flexibleDamaged !== null)
4557
+ throw new Error(`${file}: refusing to open — ${flexibleDamaged}`);
4558
+ step("flexible-terms");
4559
+ db.exec(V162_SCHEMA);
4560
+ const threadDamaged = flexibleThreadShapeProblem(db);
4561
+ if (threadDamaged !== null)
4562
+ throw new Error(`${file}: refusing to open — ${threadDamaged}`);
4563
+ step("flexible-thread");
4564
+ db.exec(V163_SCHEMA);
4565
+ const typedDamaged = typedByPersonShapeProblem(db);
4566
+ if (typedDamaged !== null)
4567
+ throw new Error(`${file}: refusing to open — ${typedDamaged}`);
4568
+ step("typed-by-person");
4550
4569
  if (!fresh)
4551
4570
  reclaimDatabase(db, "migration");
4552
4571
  const expectedMarker = preflight < 0 ? preflight : -preflight;
@@ -7076,6 +7095,7 @@ export class Store {
7076
7095
  .map(row => Number(row["id"]));
7077
7096
  for (const id of subscriptions)
7078
7097
  this.retirePushSubscription(id, "credential-rotation", now);
7098
+ endLapsedFlexible(this, { signer: approver }, by, now);
7079
7099
  }
7080
7100
  listApprovers() {
7081
7101
  return this.db
@@ -7137,6 +7157,7 @@ export class Store {
7137
7157
  this.recordPolicy(by, repo, "approval rules changed", rulesWords(before), rulesWords(next), now);
7138
7158
  if (isProtectedWork(next, []))
7139
7159
  endUnattendedGrants(this, { repo }, by, "project protected", now);
7160
+ endLapsedFlexible(this, { repo }, by, now);
7140
7161
  });
7141
7162
  }
7142
7163
  taskFiler(taskId) {
@@ -10406,12 +10427,22 @@ export class Store {
10406
10427
  const hours = (iso) => Math.max(0, Math.round((now.getTime() - Date.parse(String(iso))) / 3_600_000));
10407
10428
  return this.transact(() => {
10408
10429
  const families = this.taskFamiliesAdmitted(admittedRepos, false, { limit: 61 });
10409
- const taskRows = families.slice(0, 61).map(family => {
10430
+ const shown = families.slice(0, 61);
10431
+ const refs = new Map(this.db.prepare("SELECT * FROM task_ref WHERE backend = ? AND external_id IN (SELECT value FROM json_each(?))")
10432
+ .all(BUILT_IN, JSON.stringify(shown.map(family => family.current.id))).map(row => [String(row["external_id"]), readTaskRef(row)]));
10433
+ const results = new Map(this.db.prepare(`SELECT * FROM run WHERE id IN (SELECT MAX(id) FROM run WHERE task_ref IN (SELECT value FROM json_each(?))
10434
+ AND finished_at IS NOT NULL AND role IN ('builder','scout') GROUP BY task_ref)`)
10435
+ .all(JSON.stringify([...refs.values()].map(ref => ref.id))).map(row => readRun(row)).map(run => [run.taskRef, run]));
10436
+ const resultIds = JSON.stringify([...results.values()].map(run => run.id));
10437
+ const verdicts = new Map(this.db.prepare("SELECT * FROM proof_verdict WHERE run IN (SELECT value FROM json_each(?))").all(resultIds)
10438
+ .map(row => readProofVerdict(row)).map(verdict => [verdict.run, verdict]));
10439
+ const acceptances = new Set(this.db.prepare("SELECT run FROM proof_acceptance WHERE run IN (SELECT value FROM json_each(?))").all(resultIds).map(row => Number(row["run"])));
10440
+ const taskRows = shown.map(family => {
10410
10441
  const current = family.current;
10411
- const ref = this.lookupRef(current.id);
10412
- const run = this.runsFor(ref.id).find(one => one.finishedAt !== null && (one.role === "builder" || one.role === "scout"));
10413
- const proof = current.state === "done" && run !== undefined ? this.proofVerdictFor(run.id) : null;
10414
- return { family, current, ref, proof, accepted: run !== undefined && this.proofAcceptance(run.id) !== null };
10442
+ const ref = refs.get(current.id);
10443
+ const run = results.get(ref.id);
10444
+ const proof = current.state === "done" && run !== undefined ? verdicts.get(run.id) ?? null : null;
10445
+ return { family, current, ref, proof, accepted: run !== undefined && acceptances.has(run.id) };
10415
10446
  });
10416
10447
  const decisionRows = this.db
10417
10448
  .prepare(`SELECT decision.id AS id, decision.question AS question, decision.options AS options, task_ref.repo AS repo,
@@ -11615,6 +11646,7 @@ export class Store {
11615
11646
  const words = { providers: "allowed providers", models: "allowed models", tools: "allowed tools", ceiling: "permission ceiling" };
11616
11647
  for (const rule of ["providers", "models", "tools", "ceiling"])
11617
11648
  this.recordPolicy(by, null, `organisation policy: ${words[rule]}`, before[rule], after[rule], now);
11649
+ endLapsedFlexible(this, "all", by, now);
11618
11650
  return this.orgPolicy();
11619
11651
  });
11620
11652
  }
@@ -15608,6 +15640,7 @@ export class Store {
15608
15640
  const after = this.projectNetwork(repo);
15609
15641
  const words = (one) => `${one.mode}${one.hosts.length === 0 ? "" : ` +${one.hosts.join(",")}`}${one.loopback === "proxy-only" ? " no-local" : ""}`;
15610
15642
  this.recordPolicy(by, repo, "network", words(before), words(after), now);
15643
+ endLapsedFlexible(this, { repo }, by, now);
15611
15644
  return { before, after };
15612
15645
  });
15613
15646
  }
@@ -18690,6 +18723,72 @@ export function resetAccountPassword(store, name, credentialHash, expectedGenera
18690
18723
  return { ok: true, generation: expectedGeneration + 1, leadTokens };
18691
18724
  });
18692
18725
  }
18726
+ function flexibleTermsShapeProblem(db) {
18727
+ const statements = V161_SCHEMA.split(/;\s*\n(?=CREATE )/).map(one => one.trim().replace(/;$/, "")).filter(one => one !== "");
18728
+ for (const [type, name] of [["table", "flexible_terms"], ["index", "flexible_terms_live"], ["trigger", "flexible_terms_written_once"]]) {
18729
+ const row = db.prepare("SELECT sql FROM sqlite_master WHERE type = ? AND name = ?").get(type, name);
18730
+ if (row === undefined)
18731
+ return `the flexible_terms ${type} ${name} is missing`;
18732
+ const want = statements.find(one => new RegExp(`^CREATE (?:UNIQUE )?${type.toUpperCase()} IF NOT EXISTS ${name}\\b`).test(one));
18733
+ if (want === undefined || canonicalDdl(String(row["sql"]).replace(/;$/, "")).trim() !== canonicalDdl(want).trim())
18734
+ return `the flexible_terms ${type} ${name} has an unknown shape`;
18735
+ }
18736
+ return null;
18737
+ }
18693
18738
  export function projectRowKnown(store, path) {
18694
18739
  return store.handle.prepare("SELECT 1 FROM project WHERE path = ?").get(path) !== undefined;
18695
18740
  }
18741
+ function flexibleThreadShapeProblem(db) {
18742
+ const statements = V162_SCHEMA.split(/;\s*\n(?=CREATE )/).map(one => one.trim().replace(/;$/, "")).filter(one => one !== "");
18743
+ for (const [type, name] of [["table", "flexible_thread"], ["index", "flexible_thread_repo"], ["trigger", "flexible_thread_written_once"]]) {
18744
+ const row = db.prepare("SELECT sql FROM sqlite_master WHERE type = ? AND name = ?").get(type, name);
18745
+ if (row === undefined)
18746
+ return `the flexible_thread ${type} ${name} is missing`;
18747
+ const want = statements.find(one => new RegExp(`^CREATE (?:UNIQUE )?${type.toUpperCase()} IF NOT EXISTS ${name}\\b`).test(one));
18748
+ if (want === undefined || canonicalDdl(String(row["sql"]).replace(/;$/, "")).trim() !== canonicalDdl(want).trim())
18749
+ return `the flexible_thread ${type} ${name} has an unknown shape`;
18750
+ }
18751
+ return null;
18752
+ }
18753
+ export function accountAccessOf(store, name) {
18754
+ const account = store.accountOf(name);
18755
+ return repo => account !== null && account.revokedAt === null && projectAccessAllows(account.projects, repo);
18756
+ }
18757
+ function typedByPersonShapeProblem(db) {
18758
+ const statements = V163_SCHEMA.split(/;\s*\n(?=CREATE )/).map(one => one.trim().replace(/;$/, "")).filter(one => one !== "");
18759
+ for (const [type, name] of [["table", "typed_by_person"], ["trigger", "typed_by_person_written_once"]]) {
18760
+ const row = db.prepare("SELECT sql FROM sqlite_master WHERE type = ? AND name = ?").get(type, name);
18761
+ if (row === undefined)
18762
+ return `the typed_by_person ${type} ${name} is missing`;
18763
+ const want = statements.find(one => new RegExp(`^CREATE (?:UNIQUE )?${type.toUpperCase()} IF NOT EXISTS ${name}\\b`).test(one));
18764
+ if (want === undefined || canonicalDdl(String(row["sql"]).replace(/;$/, "")).trim() !== canonicalDdl(want).trim())
18765
+ return `the typed_by_person ${type} ${name} has an unknown shape`;
18766
+ }
18767
+ return null;
18768
+ }
18769
+ export function markTypedByPerson(store, note, author, words, now, question = null) {
18770
+ const typed = (words ?? "").trim();
18771
+ if (typed === "" || typed.length > 8000)
18772
+ return false;
18773
+ const comment = "comment" in note ? note.comment : null, steer = "steer" in note ? note.steer : null;
18774
+ const saved = store.handle.prepare(comment !== null ? "SELECT note FROM diff_comment WHERE id = ?" : "SELECT note FROM task_steer WHERE id = ?").get(comment ?? steer);
18775
+ if (saved === undefined || !String(saved["note"]).includes(typed))
18776
+ return false;
18777
+ return Number(store.handle.prepare("INSERT INTO typed_by_person (comment, steer, author, words, question, typed_at) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING")
18778
+ .run(comment, steer, author, typed, question === null ? null : question.slice(0, 400) || null, now.toISOString()).changes) === 1;
18779
+ }
18780
+ export function typedNotesFor(store, taskId, cap) {
18781
+ const ref = store.handle.prepare("SELECT id FROM task_ref WHERE backend = ? AND external_id = ?").get(BUILT_IN, taskId);
18782
+ const rows = store.handle.prepare(`
18783
+ SELECT 'sent-back' AS kind, c.id AS id, c.author AS author, c.created_at AS at, t.words AS words, t.question AS question FROM diff_comment c
18784
+ JOIN diff_comment o ON (o.id = c.id OR o.superseded_by = c.id) AND o.note = c.note AND o.author = c.author
18785
+ JOIN typed_by_person t ON t.comment = o.id AND t.author = c.author
18786
+ WHERE c.consumed_by = ? AND c.reviewer_run IS NULL AND instr(c.note, t.words) > 0
18787
+ UNION ALL
18788
+ SELECT 'to-agent' AS kind, s.id AS id, s.author AS author, s.created_at AS at, t.words AS words, t.question AS question FROM task_steer s
18789
+ JOIN typed_by_person t ON t.steer = s.id AND t.author = s.author
18790
+ WHERE s.task_ref = ? AND s.authorship_state = 'verified' AND instr(s.note, t.words) > 0
18791
+ ORDER BY at DESC, id DESC LIMIT ?`).all(taskId, ref === undefined ? -1 : Number(ref["id"]), Math.max(0, cap));
18792
+ return rows.map(row => ({ kind: row["kind"] === "sent-back" ? "sent-back" : "to-agent", id: Number(row["id"]), author: String(row["author"]),
18793
+ at: String(row["at"]), note: String(row["words"]), question: row["question"] == null ? null : String(row["question"]) }));
18794
+ }