toolroll 0.9.107 → 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 (105) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/README.md +4 -3
  3. package/dist/advanced-view.js +0 -1
  4. package/dist/agent-fence.js +35 -4
  5. package/dist/agent-state.js +5 -2
  6. package/dist/assignment-ui.js +5 -5
  7. package/dist/assignment.js +5 -2
  8. package/dist/browser/terminal.js +1 -1
  9. package/dist/browser/workspace.css +1 -1
  10. package/dist/browser/workspace.js +38 -33
  11. package/dist/browser-crew.js +4 -4
  12. package/dist/browser-shell.js +1 -1
  13. package/dist/browser-workspace.js +4 -11
  14. package/dist/builder.js +9 -1
  15. package/dist/chat-controls.js +6 -5
  16. package/dist/chat-decide.js +1 -1
  17. package/dist/chat-quiet.js +3 -3
  18. package/dist/chat-voice.js +2 -2
  19. package/dist/cli-help.js +17 -13
  20. package/dist/cli.js +4 -3
  21. package/dist/console-chrome.js +10 -3
  22. package/dist/contracts/cli.js +2 -0
  23. package/dist/contracts/console-api.js +5 -4
  24. package/dist/contracts/handoff.js +4 -0
  25. package/dist/decision.js +17 -0
  26. package/dist/demo-chat.js +1 -1
  27. package/dist/demo.js +6 -0
  28. package/dist/design/kit.js +4 -3
  29. package/dist/dispatch.js +3 -8
  30. package/dist/flexible-available.js +1 -0
  31. package/dist/flexible-schema.js +32 -0
  32. package/dist/flexible-thread-schema.js +30 -0
  33. package/dist/flexible-thread.js +526 -0
  34. package/dist/flexible-ui.js +44 -0
  35. package/dist/flexible.js +359 -0
  36. package/dist/folder-look.js +65 -4
  37. package/dist/git-views.js +38 -38
  38. package/dist/guides.js +14 -11
  39. package/dist/keymap.js +1 -1
  40. package/dist/lead-cli.js +2 -1
  41. package/dist/lead-context.js +1 -1
  42. package/dist/limits-ui.js +1 -1
  43. package/dist/live-bus.js +82 -12
  44. package/dist/login-secrets.js +43 -0
  45. package/dist/needs-you.js +3 -3
  46. package/dist/nightly-github.js +2 -2
  47. package/dist/operate.js +278 -21
  48. package/dist/project-admission.js +60 -29
  49. package/dist/project-delete-ui.js +2 -1
  50. package/dist/project-delete.js +1 -0
  51. package/dist/project.js +73 -0
  52. package/dist/provider-auth.js +1 -1
  53. package/dist/release.js +1 -0
  54. package/dist/repos.js +37 -0
  55. package/dist/result-actions.js +3 -0
  56. package/dist/result-evidence-readers.js +8 -2
  57. package/dist/result-review.js +20 -9
  58. package/dist/route-hooks.js +1 -0
  59. package/dist/sample-project.js +167 -9
  60. package/dist/scope.js +17 -2
  61. package/dist/serve.js +47 -32
  62. package/dist/server/chat.js +9 -9
  63. package/dist/server/chrome.js +16 -16
  64. package/dist/server/guards.js +10 -4
  65. package/dist/server/home.js +37 -5
  66. package/dist/server/http.js +4 -2
  67. package/dist/server/in-place.js +5 -4
  68. package/dist/server/kit.js +2 -2
  69. package/dist/server/live.js +103 -10
  70. package/dist/server/login-help.js +67 -0
  71. package/dist/server/pages.js +258 -78
  72. package/dist/server/people-tokens.js +36 -24
  73. package/dist/server/render-chat.js +1 -1
  74. package/dist/server/render-history.js +18 -4
  75. package/dist/server/render-new-task.js +2 -2
  76. package/dist/server/render-pages.js +21 -39
  77. package/dist/server/render-people.js +16 -4
  78. package/dist/server/render-projects.js +63 -15
  79. package/dist/server/render-results.js +26 -10
  80. package/dist/server/render-tasks.js +26 -17
  81. package/dist/server/retired-routes.js +37 -4
  82. package/dist/server/route-policy.js +8 -0
  83. package/dist/server/route-table.js +15 -5
  84. package/dist/server/settings-computers.js +140 -0
  85. package/dist/server/settings-scripts.js +15 -0
  86. package/dist/server/settings-section-table.js +56 -0
  87. package/dist/server/settings-sections.js +258 -0
  88. package/dist/server/settings.js +167 -19
  89. package/dist/server/task-views.js +47 -13
  90. package/dist/server/tasks.js +143 -90
  91. package/dist/server/welcome.js +35 -23
  92. package/dist/settings-groups-ui.js +34 -106
  93. package/dist/settings-proofs.js +5 -2
  94. package/dist/sqlite-telemetry.js +70 -21
  95. package/dist/store.js +141 -9
  96. package/dist/surface.js +4 -1
  97. package/dist/task-link.js +64 -0
  98. package/dist/task-outcome-cli.js +99 -4
  99. package/dist/tui-source.js +11 -3
  100. package/dist/tui.js +39 -39
  101. package/dist/typed-words-schema.js +18 -0
  102. package/dist/welcome-facts.js +15 -7
  103. package/dist/work-index.js +126 -29
  104. package/dist/work-reads.js +279 -0
  105. package/package.json +4 -2
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
  }
@@ -18660,3 +18693,102 @@ export const CONTAINMENT_NOTICE_FACT = "containment-notice-shown";
18660
18693
  export function noticeDueOnce(store, key, now) {
18661
18694
  return Number(store.handle.prepare("INSERT OR IGNORE INTO installation_fact (key, value, created_at) VALUES (?, 'yes', ?)").run(key, now.toISOString()).changes) === 1;
18662
18695
  }
18696
+ export function passwordResetRefusal(store, name, passwordsOnlyForOperators) {
18697
+ const row = store.handle.prepare("SELECT credential_hash, password_set, revoked_at FROM approver WHERE name = ?").get(name);
18698
+ if (row === undefined)
18699
+ return "no-account";
18700
+ if (row["revoked_at"] !== null && row["revoked_at"] !== undefined)
18701
+ return "revoked";
18702
+ if (String(row["credential_hash"]).startsWith("sso-only$"))
18703
+ return "sso-only";
18704
+ if (Number(row["password_set"]) !== 1)
18705
+ return "no-password";
18706
+ if (passwordsOnlyForOperators && !store.isInstanceOperator(name))
18707
+ return "password-not-allowed";
18708
+ return null;
18709
+ }
18710
+ export function resetAccountPassword(store, name, credentialHash, expectedGeneration, passwordsOnlyForOperators, now) {
18711
+ return store.transact(() => {
18712
+ const refusal = passwordResetRefusal(store, name, passwordsOnlyForOperators);
18713
+ if (refusal !== null)
18714
+ return { ok: false, reason: refusal };
18715
+ const written = store.handle.prepare(`UPDATE approver SET credential_hash = ?, generation = generation + 1
18716
+ WHERE name = ? AND generation = ? AND password_set = 1 AND revoked_at IS NULL AND credential_hash NOT LIKE 'sso-only$%'`).run(credentialHash, name, expectedGeneration);
18717
+ if (Number(written.changes) !== 1)
18718
+ return { ok: false, reason: "changed" };
18719
+ store.revokeDerivedAuthority(name, "credential-rotation", now);
18720
+ const leadTokens = store.revokeLeadCredentials(name, name, now);
18721
+ store.recordAction({ at: now.toISOString(), actor: name, repo: null, taskId: null, runId: null, action: "password reset at this computer", outcome: "changed", source: "access",
18722
+ detail: `every session of ${name} ended (generation ${expectedGeneration + 1})${leadTokens > 0 ? `; ${leadTokens} lead token${leadTokens === 1 ? "" : "s"} ended` : ""}` });
18723
+ return { ok: true, generation: expectedGeneration + 1, leadTokens };
18724
+ });
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
+ }
18738
+ export function projectRowKnown(store, path) {
18739
+ return store.handle.prepare("SELECT 1 FROM project WHERE path = ?").get(path) !== undefined;
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
+ }
package/dist/surface.js CHANGED
@@ -455,7 +455,9 @@ const GUIDE_ROWS = [
455
455
  operator("stop", "stop this computer's Toolroll after its running work is saved: the background service (until the next login), or the `up` running in a terminal"),
456
456
  operator("open", "open this computer's Toolroll at a terminal, signed in: the terminal UI, or the browser with --web (starts it first when it isn't running); never prints a sign-in link"),
457
457
  { ...operatorRead("welcome", "the three steps to a first result (agent, project, first task) as the console's welcome shows them; at a terminal it walks them one at a time"), flags: [jsonFlag, dbFlag] },
458
+ { ...operator("welcome sample", "add the sample project (a tiny repository with one function and its test) in your projects folder, as this computer's password-free owner at a terminal: the console welcome's Try a sample project; takes no folder or name"), flags: [jsonFlag, dbFlag] },
458
459
  operator("password set", "set this computer's first password, typed twice at your own terminal (never a flag, file or environment variable); every session signs in again and local mode stays on"),
460
+ operator("password reset", "reset a forgotten password at the computer running Toolroll, typed twice at your own terminal (the one approver, or --as <name>); every session of that account ends and a saved first password that no longer works is removed. Anyone who can run commands as you on this computer can do this, as they could read the saved file"),
459
461
  { ...operatorRead("doctor", "check that Toolroll's service holds no key, token or password a build could read; names what it finds and the steps to fix it, never a value, and changes nothing"), flags: [jsonFlag] },
460
462
  ];
461
463
  const REMOTE_NO = [
@@ -466,7 +468,7 @@ const REMOTE_NO = [
466
468
  "assignment show", "assignment updates", "assignment claim", "assignment check", "assignment brief", "assignment inbox", "assignment ack",
467
469
  "claim", "heartbeat", "worker release", "reap", "tick", "build", "reconcile",
468
470
  "runner register", "runner retire", "runner bind", "runner capacity", "coordinator mint", "coordinator revoke", "mcp", "outbox deliver", "peek",
469
- "serve", "serve check-public", "watch", "up", "onboard", "daemon", "background on", "background off", "background show", "stop", "open", "welcome", "password set", "doctor", "bridge", "setup show", "setup clear",
471
+ "serve", "serve check-public", "watch", "up", "onboard", "daemon", "background on", "background off", "background show", "stop", "open", "welcome", "welcome sample", "password set", "password reset", "doctor", "bridge", "setup show", "setup clear",
470
472
  "providers", "keys status", "keys set", "keys clear", "keys verify", "keys auth", "models check", "models update", "models watch",
471
473
  "models results",
472
474
  "models suggestions", "models accept", "models dismiss", "models turn-off", "models keep", "models try", "models stop",
@@ -538,6 +540,7 @@ const LOCAL_ALLOW = {
538
540
  "task archive": "archive-task",
539
541
  "task restore": "archive-task",
540
542
  "repos add": "add-project",
543
+ "welcome sample": "add-project",
541
544
  "models suggestions": "read",
542
545
  "models turn-off": "routing-turn-off",
543
546
  "models dismiss": "dismiss-suggestion",
@@ -0,0 +1,64 @@
1
+ const SECTIONS = ["summary", "changes", "checks"];
2
+ const ANCHOR = /^[A-Za-z0-9_-][A-Za-z0-9_.:-]{0,159}$/;
3
+ const REFUSAL = /^[a-z][a-z-]{0,31}$/;
4
+ const ID = /^[A-Za-z0-9._~%-]{1,200}$/;
5
+ const validRun = (run) => typeof run === "number" && Number.isSafeInteger(run) && run > 0;
6
+ const hashOf = (anchor) => anchor != null && ANCHOR.test(anchor) ? `#${anchor}` : "";
7
+ export function taskLinkOf(link) {
8
+ const path = `/t/${encodeURIComponent(link.task)}`;
9
+ const hash = hashOf(link.anchor);
10
+ if (link.record === true) {
11
+ if (validRun(link.run))
12
+ return `/r/${link.run}?record=1${hash}`;
13
+ const query = new URLSearchParams();
14
+ if (link.revision != null && link.revision !== "")
15
+ query.set("version", link.revision);
16
+ query.set("tab", "record");
17
+ return `${path}?${query.toString()}${hash === "" ? "#record" : hash}`;
18
+ }
19
+ const query = [];
20
+ if (link.revision != null && link.revision !== "")
21
+ query.push(`version=${encodeURIComponent(link.revision)}`);
22
+ const section = link.section != null && SECTIONS.includes(link.section) ? link.section : null;
23
+ const result = validRun(link.run) || section !== null || link.result === true;
24
+ if (result) {
25
+ query.push("tab=result");
26
+ if (validRun(link.run))
27
+ query.push(`run=${link.run}`);
28
+ if (section !== null && section !== "summary")
29
+ query.push(`section=${section}`);
30
+ }
31
+ if (link.feedback?.noted === true)
32
+ query.push("noted=1");
33
+ if (link.feedback?.refused != null && REFUSAL.test(link.feedback.refused))
34
+ query.push(`refused=${link.feedback.refused}`);
35
+ return `${path}${query.length === 0 ? "" : `?${query.join("&")}`}${hash}`;
36
+ }
37
+ export function taskLinkFromLegacy(href) {
38
+ let url;
39
+ try {
40
+ url = new URL(href, "http://toolroll.local");
41
+ }
42
+ catch {
43
+ return null;
44
+ }
45
+ if (url.origin !== "http://toolroll.local" || !href.startsWith("/"))
46
+ return null;
47
+ const anchor = url.hash === "" ? null : decodeURIComponent(url.hash.slice(1));
48
+ const section = (raw) => raw !== null && SECTIONS.includes(raw) ? raw : null;
49
+ const runOf = (raw) => raw !== null && /^[1-9][0-9]{0,14}$/.test(raw) ? Number(raw) : null;
50
+ if (url.pathname === "/review") {
51
+ const task = url.searchParams.get("result");
52
+ if (task === null || !ID.test(encodeURIComponent(task)))
53
+ return null;
54
+ return taskLinkOf({ task, run: runOf(url.searchParams.get("run")), section: section(url.searchParams.get("tab")), anchor, result: true,
55
+ feedback: { noted: url.searchParams.get("noted") !== null, refused: url.searchParams.get("refused") } });
56
+ }
57
+ if (url.pathname === "/chat") {
58
+ const task = url.searchParams.get("task"), run = runOf(url.searchParams.get("result"));
59
+ if (task === null || run === null || !ID.test(encodeURIComponent(task)))
60
+ return null;
61
+ return taskLinkOf({ task, run, section: section(url.searchParams.get("tab")), anchor });
62
+ }
63
+ return null;
64
+ }
@@ -1,17 +1,20 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { assignmentOf, checkAssignmentAsOperator, completeAsLocalOwner } from './assignment.js';
3
- import { currentLocalOwner, localModeOn } from './local-owner.js';
3
+ import { currentLocalOwner, localActNow, localModeOn, LOCAL_OWNER_LAPSED } from './local-owner.js';
4
4
  import { validateNote } from './decision.js';
5
5
  import { assignmentForCoordinator, coordinatorToken } from './assignment-adapters.js';
6
6
  import { authenticateCoordinator } from './coordinator.js';
7
- import { reproveApprover } from './principal.js';
8
- import { authenticateApprover, machineActing, personProof } from './scope.js';
7
+ import { reproveApprover, verifyApproverStanding } from './principal.js';
8
+ import { authenticateApprover, localWorkEligible, machineActing, personProof } from './scope.js';
9
9
  import { currentActor } from './actor.js';
10
10
  import { requestResultChanges } from './result-actions.js';
11
11
  import { commentSourceKey, revisionSourceOf } from './result-review.js';
12
12
  import { envelopeJson } from './envelope.js';
13
13
  import { completeAndOpenPullRequest, mergeAsPerson, MERGE_NEEDS_PERSON, newestPullRequestOf, publishingOf, pullRequestViewOf } from './pull-request-flow.js';
14
14
  import { proveRunStopped } from './stop-proof.js';
15
+ import { familyChangedFiles } from './result-completion.js';
16
+ import { activeRemote } from './remote-run.js';
17
+ import { underAgent } from './prompt.js';
15
18
  export async function runTaskOutcomeCommand(action, positional, flags, context) {
16
19
  const command = context.command ?? `task ${action}`;
17
20
  const emit = (result, lines) => {
@@ -34,10 +37,13 @@ export async function runTaskOutcomeCommand(action, positional, flags, context)
34
37
  return fail('usage', 'Choose your lead\'s credential or your own sign-in, not both.');
35
38
  if (credential.token !== null && pullRequest)
36
39
  return fail('unauthenticated', 'Opening a pull request is an approver\'s act. Use your own sign-in (--as and --token), not your lead\'s credential.');
40
+ const key = action === 'complete' ? 'c' : 'b';
41
+ if (credential.token === null && passwordFreeShell(context.store))
42
+ return fail('local-owner', passwordFreeShellWords(key, shellCallerOf(context.json, context.caller)));
37
43
  const operator = credential.token === null ? await context.operator() : null;
38
44
  if (credential.token === null && operator === null) {
39
45
  return fail('unauthenticated', passwordFreeOwner(context.store)
40
- ? `Open \`toolroll\` and press ${action === 'complete' ? 'c' : 'b'} on the task.`
46
+ ? passwordFreeShellWords(key, shellCallerOf(context.json, context.caller))
41
47
  : 'Run this at a terminal to sign in when asked, or open `toolroll`. Your lead can use --token-file or --token-env with its own credential.');
42
48
  }
43
49
  const { store, now, evidenceRoot } = context;
@@ -228,6 +234,95 @@ export async function runLocalCompletion(positional, flags, context) {
228
234
  ...(assignment.readiness?.checksOff ? [] : [receipt.checks.detail]),
229
235
  ]);
230
236
  }
237
+ export function reviseAsLocalOwner(store, taskId, input, now, evidenceRoot) {
238
+ const fail = (reason, message) => ({ ok: false, reason, message });
239
+ try {
240
+ return store.transact(() => {
241
+ const local = localActNow(store, 'request-revision');
242
+ if (local === null)
243
+ return fail('local-owner', LOCAL_OWNER_LAPSED);
244
+ const standing = verifyApproverStanding(store, local.account, local.accountGeneration, store.knownRepos().filter(repo => store.accountCanAccess(local.account, repo)));
245
+ if (!standing.ok)
246
+ return fail('local-owner', LOCAL_OWNER_LAPSED);
247
+ const who = standing.who, repos = who.repos;
248
+ const current = assignmentOf(store, taskId, now, { principal: 'operator', repos }, evidenceRoot);
249
+ if (current === null || !store.accountCanAccess(who.name, current.repo))
250
+ return fail('not-found', 'That task is unavailable in your projects.');
251
+ const run = store.getRun(input.runId);
252
+ const runTask = run === null ? null : store.externalIdFor(run.taskRef);
253
+ const family = runTask === null ? null : store.taskFamilyOf(runTask, repos, false);
254
+ if (run === null || runTask === null || family?.root.id !== current.rootId || run.outcome === null)
255
+ return fail('not-found', 'That finished result is unavailable for this task.');
256
+ const changed = familyChangedFiles(store, runTask, run.id, evidenceRoot, { missing: 'unknown' });
257
+ for (const one of new Set([taskId, runTask, current.rootId])) {
258
+ const eligible = localWorkEligible(store, who.name, one, { act: 'revise', changed });
259
+ if (!eligible.ok)
260
+ return fail('local-owner', `${eligible.message} ${store.accountOf(who.name)?.passwordSet === true ? 'Sign in with your password to do this.' : 'Set a password first: run `toolroll password set`.'}`);
261
+ }
262
+ const source = revisionSourceOf(store.getScope(runTask)?.digest ?? null);
263
+ const key = createHash('sha256').update(JSON.stringify([who.name, run.id, source, input.feedback])).digest('hex').slice(0, 32);
264
+ const previous = store.diffCommentBySourceKey(commentSourceKey(who.name, key));
265
+ if ((family.current.id !== runTask || (current.receipt !== null && current.receipt.runId !== run.id)) && previous?.consumedBy == null)
266
+ return fail('stale-result', 'A newer version is current. Read its result before sending it back.');
267
+ const revised = requestResultChanges(store, evidenceRoot, { run: run.id, source, actor: who.name, repos,
268
+ batch: '', note: input.feedback, path: '', line: '', request: key, allowMode: true,
269
+ origin: 'person' }, now);
270
+ if (!revised.ok)
271
+ return fail(revised.status === 400 ? 'usage' : 'stale-result', revised.message);
272
+ const scope = store.getScope(revised.id);
273
+ return { ok: true, id: revised.id, rootId: current.rootId, sourceRun: run.id, source, key,
274
+ approved: scope?.approvedDigest != null && scope.approvedDigest === scope.digest, planning: store.lookupRef(revised.id)?.plan === 'requested' };
275
+ });
276
+ }
277
+ catch (error) {
278
+ if (error instanceof Error && error.message === LOCAL_OWNER_LAPSED)
279
+ return fail('local-owner', LOCAL_OWNER_LAPSED);
280
+ throw error;
281
+ }
282
+ }
283
+ export async function runLocalRevision(positional, flags, context) {
284
+ const command = 'task revise';
285
+ const emit = (result, lines) => {
286
+ context.write(context.json ? envelopeJson({ ...result, command }) : result.ok ? (lines ?? []).join('\n') : result.message ?? 'The action was refused.');
287
+ return result.ok ? 0 : result.reason === 'usage' ? 2 : 3;
288
+ };
289
+ const fail = (reason, message) => emit({ ok: false, reason, message });
290
+ const usage = 'Use task revise <task> --run <build> --feedback "requested change".';
291
+ const allowed = new Set(['json', 'db', 'run', 'feedback']);
292
+ for (const key of flags.keys())
293
+ if (!allowed.has(key))
294
+ return fail('usage', `--${key} is not a ${command} option here.`);
295
+ const task = positional[0];
296
+ if (positional.length !== 1 || !task || task.length > 64 || /[\x00-\x1f]/.test(task))
297
+ return fail('usage', usage);
298
+ const run = flags.get('run'), feedback = flags.get('feedback');
299
+ if (typeof run !== 'string' || !/^[1-9]\d{0,14}$/.test(run))
300
+ return fail('usage', `--run needs the exact build number of the result you read. ${usage}`);
301
+ if (typeof feedback !== 'string' || !feedback.trim())
302
+ return fail('usage', 'Describe the requested change with --feedback.');
303
+ const done = reviseAsLocalOwner(context.store, task, { runId: Number(run), feedback }, context.now, context.evidenceRoot);
304
+ if (!done.ok)
305
+ return emit(done);
306
+ const { ok: _ok, ...result } = done;
307
+ return emit({ ok: true, result }, [`${done.rootId} · Revision created`, `Execution: ${done.id}`,
308
+ done.approved ? 'Covered by your existing operating mode.' : done.planning ? 'Updating the plan with your notes; approve it when it is ready.' : 'The revision is waiting for approval.']);
309
+ }
310
+ export function shellCallerOf(json, seam) {
311
+ return seam?.() ?? { json, agent: underAgent(process.env), terminal: process.stdin.isTTY === true && process.stdout.isTTY === true };
312
+ }
313
+ export function passwordFreeShell(store) {
314
+ return currentLocalOwner() === null && activeRemote() === null && currentActor()?.lead !== true && passwordFreeOwner(store);
315
+ }
316
+ export function passwordFreeShellWords(key, caller) {
317
+ const fix = `Open \`toolroll\` in your own terminal and press ${key} on the task.`;
318
+ if (caller.agent)
319
+ return `Your coding agent can't do this for you. ${fix}`;
320
+ if (caller.json)
321
+ return `With --json nothing can ask you, and you haven't set a password. ${fix}`;
322
+ if (!caller.terminal)
323
+ return `This can't ask you when it runs piped or in the background, and you haven't set a password. ${fix}`;
324
+ return `You haven't set a password, so there's nothing to sign in with here. Open \`toolroll\` and press ${key} on the task.`;
325
+ }
231
326
  export function passwordFreeOwner(store) {
232
327
  try {
233
328
  if (!localModeOn(store))
@@ -15,7 +15,7 @@ import { flakyCount } from "./flaky.js";
15
15
  import { memoryWaiting } from "./lesson-notes.js";
16
16
  import { homeGroupOf } from "./home-groups.js";
17
17
  import { terminalText } from "./terminal-text.js";
18
- import { welcomeHere, welcomeLines } from "./welcome-facts.js";
18
+ import { sampleOffered, welcomeHere, welcomeLines } from "./welcome-facts.js";
19
19
  import { planSourceOf, retryPinsOf } from "./local-owner-acts.js";
20
20
  const record = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
21
21
  const words = (value, fallback = "") => typeof value === "string" ? value : fallback;
@@ -157,13 +157,17 @@ export function createTuiSource(options) {
157
157
  done = "Stopping. Its work so far is kept.";
158
158
  break;
159
159
  case "revise":
160
- argv = ["task", "revise", act.id, "--feedback", act.text];
160
+ argv = ["task", "revise", act.id, "--run", String(act.runId), "--feedback", act.text];
161
161
  done = "Sent back with your note.";
162
162
  break;
163
163
  case "answer":
164
164
  argv = ["decide", String(act.decision), "--choose", act.option];
165
165
  done = "Answered.";
166
166
  break;
167
+ case "sample":
168
+ argv = ["welcome", "sample"];
169
+ done = "Added the sample project. Press n to write a first task.";
170
+ break;
167
171
  case "retry":
168
172
  argv = ["task", "requeue", act.id, "--run", String(act.runId), "--digest", act.digest];
169
173
  done = "Retrying. It starts next.";
@@ -174,8 +178,11 @@ export function createTuiSource(options) {
174
178
  break;
175
179
  }
176
180
  const answer = await command(argv);
181
+ setupCache = null;
177
182
  if (answer.ok !== true)
178
183
  return refusalOf(answer);
184
+ if (act.kind === "sample")
185
+ return { ok: true, message: answer["added"] === false ? "The sample project is already added. Press n to write a first task." : done };
179
186
  if (act.kind === "complete" && answer["replayed"] === true)
180
187
  return { ok: true, message: "Already accepted. The task is done." };
181
188
  if (act.kind === "plan" && answer["replayed"] === true)
@@ -230,7 +237,8 @@ export function createTuiSource(options) {
230
237
  });
231
238
  if (here === null)
232
239
  return null;
233
- const value = here.model.left === 0 ? null : { left: here.model.left, lines: welcomeLines(here.model).map(line => terminalText(line)) };
240
+ const offered = sampleOffered(here.model, localModeOf(store)?.enabled === true, store.isDemo());
241
+ const value = here.model.left === 0 ? null : { left: here.model.left, lines: welcomeLines(here.model, offered ? "key" : null).map(line => terminalText(line)), sample: offered };
234
242
  setupCache = { at: Date.now(), value };
235
243
  return value;
236
244
  },