toolroll 0.9.106 → 0.9.108

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 (46) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.md +5 -4
  3. package/dist/browser/workspace.css +1 -1
  4. package/dist/browser/workspace.js +27 -25
  5. package/dist/browser-shell.js +1 -1
  6. package/dist/cli-help.js +5 -0
  7. package/dist/cli.js +18 -11
  8. package/dist/contracts/cli.js +3 -1
  9. package/dist/contracts/console-api.js +1 -1
  10. package/dist/demo-sign-in.js +1 -55
  11. package/dist/easy-start-args.js +4 -2
  12. package/dist/easy-start.js +78 -24
  13. package/dist/first-run.js +4 -1
  14. package/dist/folder-look.js +65 -4
  15. package/dist/git-floor.js +9 -2
  16. package/dist/guides.js +3 -1
  17. package/dist/lead-cli.js +2 -1
  18. package/dist/live-bus.js +14 -1
  19. package/dist/login-secrets.js +43 -0
  20. package/dist/operate.js +195 -27
  21. package/dist/project-admission.js +60 -29
  22. package/dist/project.js +73 -0
  23. package/dist/repos.js +37 -0
  24. package/dist/route-hooks.js +1 -0
  25. package/dist/sample-project.js +167 -9
  26. package/dist/sandbox-runtime.js +1 -1
  27. package/dist/scope.js +17 -2
  28. package/dist/serve.js +15 -3
  29. package/dist/server/live.js +5 -2
  30. package/dist/server/login-help.js +67 -0
  31. package/dist/server/pages.js +180 -26
  32. package/dist/server/people-tokens.js +36 -24
  33. package/dist/server/render-people.js +14 -2
  34. package/dist/server/render-projects.js +58 -10
  35. package/dist/server/route-table.js +2 -1
  36. package/dist/server/settings.js +3 -0
  37. package/dist/server/welcome.js +29 -18
  38. package/dist/settings-groups-ui.js +10 -1
  39. package/dist/sign-in-page.js +197 -0
  40. package/dist/store.js +33 -0
  41. package/dist/surface.js +4 -1
  42. package/dist/task-outcome-cli.js +99 -4
  43. package/dist/tui-source.js +11 -3
  44. package/dist/tui.js +46 -46
  45. package/dist/welcome-facts.js +17 -7
  46. package/package.json +1 -1
package/dist/operate.js CHANGED
@@ -89,7 +89,7 @@ import { runKnowledgeApply, runKnowledgeCommand } from "./knowledge-cli.js";
89
89
  import { FLOWS_VALUE_FLAGS, runFlowsCommand } from "./flows-cli.js";
90
90
  import { runAssignmentCommand } from "./assignment-adapters.js";
91
91
  import { applyProjectProfile, runProjectCommand } from "./project-cli.js";
92
- import { proveTaskBuildsStopped, pullRequestLines, runLocalCompletion, runTaskMergeCommand, runTaskOutcomeCommand } from "./task-outcome-cli.js";
92
+ import { passwordFreeOwner, passwordFreeShell, passwordFreeShellWords, proveTaskBuildsStopped, pullRequestLines, runLocalCompletion, runLocalRevision, runTaskMergeCommand, runTaskOutcomeCommand } from "./task-outcome-cli.js";
93
93
  import { requestPlanAsLocalOwner, retryAsLocalOwner } from "./local-owner-acts.js";
94
94
  import { withTaskAlias } from "./task-aliases.js";
95
95
  import { checklistLines, mergeChecklistOf } from "./merge-checklist.js";
@@ -100,7 +100,7 @@ import { releaseStalledUpdate, waitingUpdate } from "./toolroll-update.js";
100
100
  import { dur } from "./design/kit.js";
101
101
  import { requeueEligibility, checkoutIdle, setCheckoutIdle, leadQuickAnswersOn, setLeadQuickAnswers, openStore, openStoreNoMigrate, initLocalMode, localModeCandidate, consoleServingNow, consoleComponent, consoleRowForPort, openConsoleRows, enrollOwnerPassword, installationCreatedBy, laptopPortOf, recordLaptopPort, localModeOf, localOwnerBinding, archiveTaskFamily, restoreTaskFamily, shipChecksForTask, elapsedSeconds, CONCURRENT_WRITER_WAIT_MS, isDatabaseBusy, databasePath, BUILT_IN, parseCapabilityKey, verifiedAuthor, isDigestTime, predecessorWatches, RESULT_SCREENSHOTS, lifecycleOf, reportLifecycle, beatLifecycle, } from "./store.js";
102
102
  import { createHash, randomBytes, randomInt, randomUUID } from "node:crypto";
103
- import { claimInstance, clearInstance, openInstanceSocket, proveLiveConsole } from "./console-instance.js";
103
+ import { claimInstance, clearInstance, instanceRunDir, openInstanceSocket, prepareRunDir, proveLiveConsole } from "./console-instance.js";
104
104
  import { backgroundOff, backgroundOn, backgroundShow, laptopStatus, laptopStop, restartOwnBuilder } from "./laptop-background.js";
105
105
  import { authorizePlanUnderMode } from "./plan-auto.js";
106
106
  import { ghDispatchAdapter, mirrorTaskId, syncPass } from "./sync.js";
@@ -117,9 +117,10 @@ import { isWritesMode, writesWords } from "./writes-mode.js";
117
117
  import { linuxFenceAvailable, macosFenceAvailable } from "./agent-fence.js";
118
118
  import { parseMachLookup, parseReadDeny, readDenyWords } from "./project-sandbox.js";
119
119
  import { LOCAL_POLICY } from "./surface.js";
120
- import { asLocalOwner, currentLocalOwner, LOCAL_MODE_CONFINES, localModeOn, localOwnerRefusal, localOwnerRequested } from "./local-owner.js";
120
+ import { asLocalOwner, currentLocalOwner, localActNow, LOCAL_MODE_CONFINES, localModeOn, localOwnerRefusal, localOwnerRequested } from "./local-owner.js";
121
121
  import { CHECK_ACCESS_WARNINGS, checkAccessRunsAs, checkAccessWords, isCheckAccess, signInHostsMissing, signInsUnavailableWords, widerThan } from "./check-access.js";
122
122
  import { CLI_PASSWORD_SOURCE, withPasswordSource } from "./sign-in-guard.js";
123
+ import { ledgerSpent, NO_SAFE_OPENER, openSignInLink, platformOpener } from "./sign-in-page.js";
123
124
  import { admissionRecorded, admitProject, commandLineActor } from "./project-admission.js";
124
125
  import { leadClaim, leadSay, noteLeadWork } from "./lead-voice.js";
125
126
  import { createConnection as createNetConnection, createServer as createNetServer } from "node:net";
@@ -166,7 +167,7 @@ function planContractLines(store, evidenceRoot, taskId) {
166
167
  import { verdictWords as proofVerdictWords, matrixWords, plainReasonWords, semanticCoverage, coverageWords } from "./proof.js";
167
168
  import { probeRepo } from "./probe.js";
168
169
  import { agentlessFirstRun, diagnoseTaskDispatch, diagnosisIsDispatchable, NO_AGENT_TITLE, scopeApprovedForDispatch, } from "./dispatch.js";
169
- import { createDecisionServer } from "./serve.js";
170
+ import { createDecisionServer, SIGN_IN_LINK_MS } from "./serve.js";
170
171
  import { readTailnetNames } from "./tailnet.js";
171
172
  import { daemonLaunchCommand, daemonStatus, installReplacingLegacy, installedLegacyDaemon, planDaemon, uninstallDaemon, awaitFreshHeartbeat, } from "./daemon.js";
172
173
  import { bridgePass, clearBotToken, createTransport, followBridge, hashPairingCode, loadBotToken, mintPairingCode, networkFence, networkFenceLine, redactToken, saveBotToken, PAIRING_TTL_MS, TOKEN_ENV, telegramHookSecret, telegramPushUrl, } from "./telegram.js";
@@ -198,7 +199,7 @@ import { mintCoordinator, revokeCoordinator, listCoordinators } from "./coordina
198
199
  import { serveMcp } from "./mcp.js";
199
200
  import { createInterface } from "node:readline";
200
201
  import { hashPassword } from "./scope.js";
201
- import { noticeDueOnce, CONTAINMENT_NOTICE_FACT } from "./store.js";
202
+ import { noticeDueOnce, CONTAINMENT_NOTICE_FACT, passwordResetRefusal, resetAccountPassword } from "./store.js";
202
203
  import { propose, approve, addApprover, authenticateAccount, authenticateApprover as passwordApprover, describeScope, approvalOf, hashToken as hashApproverToken, modeFilingCoverage, acceptanceLinesToInput, parseAcceptanceCriteria, splitAcceptanceRubric, rubricIsPlaceholder, isCommitSha, credentialProof, rememberedLogin, personApprovalOf } from "./scope.js";
203
204
  import { CHAT_APPROVE_ALL, presetTerms, modeTermsJson, modeDigestOf, modeTermsFromJson, modeWords, MODE_MAX_DAYS } from "./modes.js";
204
205
  import { WorktreePool } from "./worktree.js";
@@ -266,7 +267,7 @@ import { reevaluateResultRecords } from "./route-results.js";
266
267
  import { holdRuleOff, routeRulesPass, taskEvidenceWords } from "./route-rules.js";
267
268
  import { ruleHoldOf } from "./route-store.js";
268
269
  import { wasInterrupted } from "./run-ending.js";
269
- import { loginFileOf, migrateLegacyLogin, savedLoginFile, writableLoginFile } from "./login-secrets.js";
270
+ import { loginFileOf, migrateLegacyLogin, removeStaleSavedLogin, savedLoginFile, writableLoginFile } from "./login-secrets.js";
270
271
  export const EXIT = { ok: 0, failed: 1, usage: 2, refused: 3 };
271
272
  const STATES = ["queued", "running", "done", "failed", "cancelled"];
272
273
  export const OPERATE_HELP = `toolroll — operating the queue
@@ -433,6 +434,14 @@ External trackers — build what a tracker nominates, under local approvals
433
434
  person say yes; the bootstrap for
434
435
  every approving act
435
436
  toolroll approver list
437
+ toolroll password reset [--as <name>]
438
+ a forgotten password: typed twice,
439
+ hidden, at this computer's own
440
+ terminal; every session of that
441
+ account ends. Anyone who can run
442
+ commands as you on this computer can
443
+ reset it, as they could read the
444
+ saved first password
436
445
  toolroll task scope <id> --goal <what success is>
437
446
  [--not <text>] [--touches a,b] [--budget-usd <n>]
438
447
  toolroll task approve <id> the yes — interactive, or
@@ -6171,6 +6180,7 @@ async function upCommand(flags, context) {
6171
6180
  explicitRoots.push(canonical);
6172
6181
  }
6173
6182
  const projectRoots = [...resolveCeiling([], addRepos(loadedRegistry.roots, explicitRoots)).ceiling.roots];
6183
+ const rootNotSaved = explicitRoots.length > 0 ? ". The projects folder wasn't saved, because this Toolroll didn't start: stop the one already running, then start it again with --project-root" : "";
6174
6184
  const repos = [];
6175
6185
  const proveRepo = async (input) => {
6176
6186
  return (await upProveSaved(gitRun, input))?.root ?? null;
@@ -6240,12 +6250,12 @@ async function upCommand(flags, context) {
6240
6250
  ours = null;
6241
6251
  }
6242
6252
  if (ours?.ok === true)
6243
- return fail(write, json, "up", "already-running", `Toolroll is already running at ${ours.url}`, EXIT.refused);
6253
+ return fail(write, json, "up", "already-running", `Toolroll is already running at ${ours.url}${rootNotSaved}`, EXIT.refused);
6244
6254
  if (ours === null || ours.state !== "none")
6245
6255
  break;
6246
6256
  const serving = consoleServingNow(store, clock(), await consolesProvenDown(store, clock()));
6247
6257
  if (serving !== null)
6248
- return fail(write, json, "up", "already-running", serving.port === null ? "Toolroll's console is already serving this database" : `Toolroll is already running at http://127.0.0.1:${serving.port}`, EXIT.refused);
6258
+ return fail(write, json, "up", "already-running", `${serving.port === null ? "Toolroll's console is already serving this database" : `Toolroll is already running at http://127.0.0.1:${serving.port}`}${rootNotSaved}`, EXIT.refused);
6249
6259
  }
6250
6260
  probe = createNetServer();
6251
6261
  port = candidate;
@@ -6264,8 +6274,8 @@ async function upCommand(flags, context) {
6264
6274
  if (!reserved) {
6265
6275
  const holder = consoleRowForPort(store, port);
6266
6276
  if (holder?.state === "draining")
6267
- return fail(write, json, "up", "port-busy", `Toolroll is restarting (draining): the console on port ${port} is stopping — try again in a few seconds`, EXIT.refused);
6268
- return fail(write, json, "up", "port-busy", `port ${port} is taken — another \`up\` or \`serve\` may already be running; stop it, or pick a different --port`, EXIT.refused);
6277
+ return fail(write, json, "up", "port-busy", `Toolroll is restarting (draining): the console on port ${port} is stopping — try again in a few seconds${rootNotSaved}`, EXIT.refused);
6278
+ return fail(write, json, "up", "port-busy", `port ${port} is taken — another \`up\` or \`serve\` may already be running; stop it, or pick a different --port${rootNotSaved}`, EXIT.refused);
6269
6279
  }
6270
6280
  const agentRunning = underAgent(context.upSeams?.env ?? process.env);
6271
6281
  const canPrompt = !json && !agentRunning && process.stdin.isTTY === true && process.stdout.isTTY === true;
@@ -6515,6 +6525,7 @@ async function upCommand(flags, context) {
6515
6525
  }
6516
6526
  }, RUNNER_HEARTBEAT_MS);
6517
6527
  runnerHeartbeat.unref?.();
6528
+ let removeSignInPageNow = () => { };
6518
6529
  const approverPlan2 = approver;
6519
6530
  const terminal = !agentRunning && (context.upSeams?.terminal ?? process.stdout.isTTY === true);
6520
6531
  const upHandoff = buildHandoff({
@@ -6547,7 +6558,11 @@ async function upCommand(flags, context) {
6547
6558
  const account = approverPlan2.approver;
6548
6559
  const localStart = approverPlan2.startAuthority === "local";
6549
6560
  const request = upLinkRequest(approverPlan2.startAuthority, account);
6550
- const link = request === null || flags.has("no-open") ? null : await new Promise(resolveLink => {
6561
+ const pageParent = instanceRunDir(context.databaseFile);
6562
+ const hasOpener = platformOpener(context.upSeams?.signInPlatform) !== null;
6563
+ const canOpen = hasOpener && prepareRunDir(pageParent) === null;
6564
+ const linkExpiresAt = Date.now() + SIGN_IN_LINK_MS;
6565
+ const link = request === null || flags.has("no-open") || !canOpen ? null : await new Promise(resolveLink => {
6551
6566
  const id = ++linkRequests;
6552
6567
  const timer = setTimeout(() => { pendingLinks.delete(id); resolveLink(null); }, 10_000);
6553
6568
  pendingLinks.set(id, value => { clearTimeout(timer); resolveLink(value); });
@@ -6558,28 +6573,40 @@ async function upCommand(flags, context) {
6558
6573
  const signInWords = account === null
6559
6574
  ? `sign in as one of ${approverPlan2.approvers.join(", ")}`
6560
6575
  : showCommand === null ? `sign in as ${account} with your password` : `sign in as ${account}`;
6576
+ const opened = link === null ? false : await (async () => {
6577
+ const outcome = localStart ? "local link" : "one-time link";
6578
+ const page = await openSignInLink(new URL(link, url).toString(), {
6579
+ parent: pageParent, spent: ledgerSpent(store, outcome, localStart ? null : account), expiresAt: linkExpiresAt,
6580
+ ...(context.upSeams?.signInOpener === undefined ? {} : { opener: context.upSeams.signInOpener }),
6581
+ ...(context.upSeams?.signInPlatform === undefined ? {} : { platform: context.upSeams.signInPlatform }),
6582
+ });
6583
+ removeSignInPageNow = page.stop;
6584
+ return page.opened;
6585
+ })();
6561
6586
  write("");
6562
6587
  write(`Toolroll is on ${url}`);
6563
6588
  if (localStart) {
6564
- if (link !== null) {
6589
+ if (opened) {
6565
6590
  write("Opening it in your browser now, already signed in.");
6566
6591
  write("If it doesn't open, stop it with Ctrl-C and run the same command again.");
6567
- (context.upSeams?.openBrowser ?? openBrowser)(new URL(link, url).toString());
6568
6592
  }
6569
- else
6593
+ else if (flags.has("no-open"))
6570
6594
  write("To sign in from this computer's browser, run the same command again without --no-open.");
6595
+ else if (!hasOpener)
6596
+ write(`${NO_SAFE_OPENER.charAt(0).toUpperCase()}${NO_SAFE_OPENER.slice(1)}.`);
6597
+ else
6598
+ write("Your browser didn't open. Stop it with Ctrl-C and run the same command again.");
6571
6599
  }
6572
- else if (link !== null) {
6600
+ else if (opened) {
6573
6601
  write("Opening it in your browser now, already signed in.");
6574
6602
  write(`If it doesn't open, go to that address and ${signInWords}.`);
6575
- (context.upSeams?.openBrowser ?? openBrowser)(new URL(link, url).toString());
6576
6603
  }
6577
6604
  else {
6578
6605
  write(`${signInWords.charAt(0).toUpperCase()}${signInWords.slice(1)}.`);
6579
6606
  }
6580
6607
  if (showCommand !== null)
6581
6608
  write(`Your password: run \`${showCommand}\``);
6582
- if (link === null)
6609
+ if (!opened)
6583
6610
  write("Ctrl-C stops it.");
6584
6611
  }
6585
6612
  }
@@ -6588,6 +6615,7 @@ async function upCommand(flags, context) {
6588
6615
  runTimer.unref?.();
6589
6616
  }
6590
6617
  await stopped;
6618
+ removeSignInPageNow();
6591
6619
  if (workerRole !== null)
6592
6620
  await Promise.race([workerRole.done, forced]);
6593
6621
  clearInterval(runnerHeartbeat);
@@ -7452,13 +7480,15 @@ function taskAction(action, rest, flags, context) {
7452
7480
  case "revise":
7453
7481
  if (action === "complete" && currentLocalOwner() !== null)
7454
7482
  return runLocalCompletion(rest, flags, context);
7483
+ if (action === "revise" && currentLocalOwner() !== null)
7484
+ return runLocalRevision(rest, flags, context);
7455
7485
  return runTaskOutcomeCommand(action, rest, flags, { ...context, operator: async () => {
7456
7486
  const acting = await askCredentials(flags, context);
7457
7487
  if (acting === null)
7458
7488
  return null;
7459
7489
  const authenticated = verifyApproverByPassword(context.store, acting.name, acting.token, context.store.knownRepos().filter(repo => context.store.accountCanAccess(acting.name, repo)));
7460
7490
  return authenticated.ok ? authenticated.who : null;
7461
- } });
7491
+ }, caller: () => shellCallerFacts(context) });
7462
7492
  case "merge":
7463
7493
  return runTaskMergeCommand(rest, flags, { store: context.store, json: context.json, write: context.write, clock: context.clock,
7464
7494
  demo: context.store.isDemo(), credentials: () => askCredentials(flags, context), ...(context.publishExec === undefined ? {} : { exec: context.publishExec }) });
@@ -8084,7 +8114,7 @@ async function acceptTaskProof(positional, flags, context) {
8084
8114
  return null;
8085
8115
  const authenticated = verifyApproverByPassword(context.store, acting.name, acting.token, context.store.knownRepos().filter(repo => context.store.accountCanAccess(acting.name, repo)));
8086
8116
  return authenticated.ok ? authenticated.who : null;
8087
- } });
8117
+ }, caller: () => shellCallerFacts(context) });
8088
8118
  }
8089
8119
  const id = positional[0];
8090
8120
  if (id === undefined)
@@ -8802,6 +8832,8 @@ async function approveTask(positional, flags, context) {
8802
8832
  const id = positional[0];
8803
8833
  if (id === undefined)
8804
8834
  return fail(write, json, "task approve", "usage", "which task?", EXIT.usage);
8835
+ if (passwordFreeShell(store))
8836
+ return fail(write, json, "task approve", "local-owner", passwordFreeShellWords("a", shellCallerFacts(context)), EXIT.refused);
8805
8837
  const scope = store.getScope(id);
8806
8838
  if (scope === null)
8807
8839
  return fail(write, json, "task approve", "no-scope", `${id} has no scope to approve — write one first`, EXIT.refused);
@@ -8965,7 +8997,7 @@ async function proposalsCommand(positional, flags, context) {
8965
8997
  return fail(write, json, "proposals confirm", outcome.reason, outcome.reason === "needs-confirm" ? `${outcome.said} — read the consequences above, then pass --yes` : outcome.said, EXIT.refused);
8966
8998
  return succeed(write, json, "proposals confirm", { proposal: id, kind: outcome.kind, said: outcome.said, ...(outcome.taskId === null ? {} : { task: outcome.taskId }) }, () => [
8967
8999
  outcome.said,
8968
- ...(outcome.kind === "scope" && outcome.taskId !== null ? [`approve it with your password: toolroll task approve ${outcome.taskId}`] : []),
9000
+ ...(outcome.kind === "scope" && outcome.taskId !== null ? [passwordFreeOwner(store) ? `approve it in \`toolroll\`: press a on ${outcome.taskId}` : `approve it with your password: toolroll task approve ${outcome.taskId}`] : []),
8969
9001
  ]);
8970
9002
  }
8971
9003
  async function chatCommand(flags, context) {
@@ -10604,7 +10636,7 @@ async function runUpConsoleRole(context, config, port, build) {
10604
10636
  admittedRepos: () => [...activeRepos],
10605
10637
  upConsole: true,
10606
10638
  registryPath: config.registryPath,
10607
- projectRoots: config.projectRoots,
10639
+ projectRoots: await (async () => { const saved = await loadProjectRegistry(config.registryPath); return "error" in saved ? config.projectRoots : saved.roots; })(),
10608
10640
  ...(config.editor ? { editorLinks: "vscode" } : {}),
10609
10641
  });
10610
10642
  }
@@ -11515,22 +11547,26 @@ async function openCommand(positional, flags, context) {
11515
11547
  async function welcomeCommand(positional, flags, context) {
11516
11548
  const { write, json } = context;
11517
11549
  const command = "welcome";
11550
+ if (positional[0] === "sample")
11551
+ return welcomeSampleCommand(positional.slice(1), flags, context);
11518
11552
  if (positional.length > 0)
11519
- return fail(write, json, command, "usage", "Use `toolroll welcome [--json]`.", EXIT.usage);
11553
+ return fail(write, json, command, "usage", "Use `toolroll welcome [--json]`, or `toolroll welcome sample`.", EXIT.usage);
11520
11554
  for (const name of flags.keys())
11521
11555
  if (!["db", "json"].includes(name))
11522
11556
  return fail(write, json, command, "usage", `--${name} is not a welcome option.`, EXIT.usage);
11523
- const { welcomeHere, welcomeLines, welcomeStepLines, WELCOME_STEPS } = await import("./welcome-facts.js");
11557
+ const { welcomeHere, welcomeLines, welcomeStepLines, WELCOME_STEPS, sampleOffered } = await import("./welcome-facts.js");
11524
11558
  const read = async () => (await welcomeHere(context.store, context.databaseFile, context.clock(), context.easySeams?.check === undefined ? {} : { check: context.easySeams.check })).model;
11525
11559
  let model = await read();
11560
+ const shellMayAdd = () => { const mode = localModeOf(context.store); return mode?.enabled === true && context.store.accountOf(mode.owner)?.passwordSet !== true; };
11561
+ const offer = () => sampleOffered(model, shellMayAdd(), context.store.isDemo()) ? "command" : null;
11526
11562
  if (json || !personAtTerminal(context) || localOwnerRequested())
11527
- return succeed(write, json, command, { ...model }, () => welcomeLines(model));
11563
+ return succeed(write, json, command, { ...model }, () => welcomeLines(model, offer()));
11528
11564
  const askNow = context.easySeams?.ask ?? ask;
11529
11565
  write(model.left === 0 ? "Setup is done." : `Welcome to Toolroll. ${model.left} ${model.left === 1 ? "step" : "steps"} to your first result.`);
11530
11566
  for (const key of WELCOME_STEPS) {
11531
11567
  for (;;) {
11532
11568
  write("");
11533
- for (const line of welcomeStepLines(model, key))
11569
+ for (const line of welcomeStepLines(model, key, offer()))
11534
11570
  write(line);
11535
11571
  if (model[key].done)
11536
11572
  break;
@@ -11550,8 +11586,10 @@ async function passwordCommand(positional, flags, context) {
11550
11586
  const { write, json, store } = context;
11551
11587
  const [action, ...rest] = positional;
11552
11588
  const command = action === undefined ? "password" : `password ${action}`;
11589
+ if (action === "reset")
11590
+ return passwordResetCommand(rest, flags, context);
11553
11591
  if (action !== "set" || rest.length > 0)
11554
- return fail(write, json, command, "usage", "Use `toolroll password set`.", EXIT.usage);
11592
+ return fail(write, json, command, "usage", "Use `toolroll password set` (a first password) or `toolroll password reset` (a forgotten one).", EXIT.usage);
11555
11593
  for (const name of flags.keys())
11556
11594
  if (!["db", "json"].includes(name))
11557
11595
  return fail(write, json, command, "usage", `--${name} is not a password set option: the password is only ever typed.`, EXIT.usage);
@@ -11816,7 +11854,7 @@ async function keepGrownCommand(positional, flags, context) {
11816
11854
  const kept = keepGrownChange(store, id, clock());
11817
11855
  if (!kept.ok)
11818
11856
  return fail(write, json, "task keep", "refused", kept.message, EXIT.refused);
11819
- return succeed(write, json, "task keep", { id, digest: kept.digest }, () => [`Its plan now names the exact commit. Approve it with \`toolroll task approve ${id}\`.`]);
11857
+ return succeed(write, json, "task keep", { id, digest: kept.digest }, () => [`Its plan now names the exact commit. ${passwordFreeOwner(store) ? "Approve it in `toolroll`: press a on the task." : `Approve it with \`toolroll task approve ${id}\`.`}`]);
11820
11858
  }
11821
11859
  let resumingReleases = false;
11822
11860
  async function resumeHeldReleases(store, stateDir, now) {
@@ -12323,3 +12361,133 @@ export async function consolesProvenDown(store, now, probe = probeConsoleAddress
12323
12361
  async function closeServedConsole(server) {
12324
12362
  await new Promise(resolve => { server.close(() => resolve()); server.closeAllConnections?.(); });
12325
12363
  }
12364
+ async function welcomeSampleCommand(positional, flags, context) {
12365
+ const { write, json, store } = context;
12366
+ const command = "welcome sample";
12367
+ if (positional.length > 0)
12368
+ return fail(write, json, command, "usage", "Use `toolroll welcome sample`: it takes no folder or name.", EXIT.usage);
12369
+ for (const name of flags.keys())
12370
+ if (!["db", "json"].includes(name))
12371
+ return fail(write, json, command, "usage", `--${name} is not a welcome sample option.`, EXIT.usage);
12372
+ if (context.principal !== undefined)
12373
+ return fail(write, json, command, "not-remote", "The sample project is added on Toolroll's own computer.", EXIT.refused);
12374
+ const lead = envValue(process.env, "LEAD_TOKEN");
12375
+ if (context.leadToken !== undefined || (lead !== undefined && lead !== ""))
12376
+ return fail(write, json, command, "refused", "A lead token can't add the sample project. Run `toolroll` yourself and press s.", EXIT.refused);
12377
+ if (store.isDemo())
12378
+ return fail(write, json, command, "refused", "The sandbox never makes projects.", EXIT.refused);
12379
+ const viaScreen = localOwnerRequested();
12380
+ if (!viaScreen && !personAtTerminal(context))
12381
+ return fail(write, json, command, "not-a-terminal", "Add the sample project yourself at a terminal: run `toolroll` and press s, or `toolroll welcome sample`.", EXIT.refused);
12382
+ const binding = localOwnerBinding(store);
12383
+ if (binding === null)
12384
+ return fail(write, json, command, "not-local", "This Toolroll signs in with a password. Open it in the browser and choose Try a sample project on the welcome page.", EXIT.refused);
12385
+ if (!viaScreen && store.accountOf(binding.account)?.passwordSet === true) {
12386
+ return fail(write, json, command, "password-set", "This Toolroll has a password. Run `toolroll` and press s, or sign in in the browser and choose Try a sample project.", EXIT.refused);
12387
+ }
12388
+ const principal = viaScreen ? currentLocalOwner()
12389
+ : { account: binding.account, localGeneration: binding.localGeneration, accountGeneration: binding.accountGeneration, transport: "terminal", act: "add-project", sessionHash: null, request: null };
12390
+ if (principal === null || principal.act !== "add-project")
12391
+ return fail(write, json, command, "refused", "Set a password, or sign in with your password, to do this.", EXIT.refused);
12392
+ const registryFile = registryPathOf(context);
12393
+ const { readProjectRegistryNow } = await import("./repos.js");
12394
+ const ceiling = (registry) => {
12395
+ const read = registry ?? readProjectRegistryNow(registryFile);
12396
+ return "error" in read ? { repos: [], roots: [] } : resolveCeiling(read.repos, read.roots).ceiling;
12397
+ };
12398
+ if ("error" in readProjectRegistryNow(registryFile))
12399
+ return fail(write, json, command, "registry", "Toolroll's project list can't be read, so nothing was added.", EXIT.refused);
12400
+ const { addSampleProject } = await import("./sample-project.js");
12401
+ const added = await asLocalOwner(principal, async () => {
12402
+ const stands = () => localActNow(store, "add-project") !== null;
12403
+ return addSampleProject({ store, registryFile, now: context.clock(), ceiling, authority: { actor: { label: principal.account, origin: "cli" }, stands } });
12404
+ });
12405
+ if (!added.ok) {
12406
+ const words = {
12407
+ "no-root": "There's no projects folder to put the sample in. Run `toolroll` once to choose one, then try again.",
12408
+ exists: "A folder named toolroll-sample is already in your projects folder and wasn't made by Toolroll, so nothing was changed.",
12409
+ failed: "The sample project couldn't be made. Nothing was added. Try again.",
12410
+ "not-added": "The sample project was made but couldn't be added. Try again.",
12411
+ refused: "Your local sign-in changed while the sample was being added. Nothing was added. Run `toolroll` to sign in again.",
12412
+ incomplete: "The sample project wasn't added, and its line in your project list couldn't be taken back.",
12413
+ };
12414
+ return fail(write, json, command, added.reason, added.message ?? words[added.reason], EXIT.refused);
12415
+ }
12416
+ return succeed(write, json, command, { repo: added.repo, created: added.created, added: added.added, checkSet: added.checkSet }, () => [
12417
+ added.added ? `Added the sample project: ${added.repo}` : `The sample project is already added: ${added.repo}`,
12418
+ "Next: write a first task. Run `toolroll` and press n.",
12419
+ ]);
12420
+ }
12421
+ async function passwordResetCommand(rest, flags, context) {
12422
+ const { write, json, store } = context;
12423
+ const command = "password reset";
12424
+ if (rest.length > 0)
12425
+ return fail(write, json, command, "usage", "Use `toolroll password reset` (or `--as <name>` when several people sign in here).", EXIT.usage);
12426
+ for (const name of flags.keys())
12427
+ if (!["db", "json", "as"].includes(name))
12428
+ return fail(write, json, command, "usage", `--${name} is not a password reset option: the new password is only ever typed.`, EXIT.usage);
12429
+ const leadInShell = envValue(process.env, "LEAD_TOKEN");
12430
+ if (context.principal !== undefined || activeRemote() !== null || context.leadToken !== undefined || (leadInShell !== undefined && leadInShell !== "")) {
12431
+ return fail(write, json, command, "not-remote", "A password is reset by a person at the computer running Toolroll, from their own shell (not with a remote or lead token).", EXIT.refused);
12432
+ }
12433
+ if (localOwnerRequested() || !personAtTerminal(context)) {
12434
+ return fail(write, json, command, "not-a-terminal", "Reset the password yourself at a terminal on the computer running Toolroll: run `toolroll password reset`.", EXIT.refused);
12435
+ }
12436
+ const asked = flags.get("as");
12437
+ if (asked === true || asked === "")
12438
+ return fail(write, json, command, "usage", "Say whose password: `--as <name>`.", EXIT.usage);
12439
+ let account;
12440
+ if (typeof asked === "string") {
12441
+ account = asked;
12442
+ }
12443
+ else {
12444
+ const people = store.listApprovers().map(one => one.name).filter(name => store.accountOf(name)?.revokedAt === null);
12445
+ if (people.length === 0)
12446
+ return fail(write, json, command, "no-account", "No one signs in to this Toolroll yet. Nothing changed.", EXIT.refused);
12447
+ if (people.length > 1)
12448
+ return fail(write, json, command, "several", `Several people sign in here (${people.join(", ")}). Say whose: \`toolroll password reset --as <name>\`.`, EXIT.usage);
12449
+ account = people[0];
12450
+ }
12451
+ const sso = (await import("./sso-settings.js")).readSsoSettings(dirname(context.databaseFile));
12452
+ const operatorsOnly = sso !== null && sso.passwords === "operators";
12453
+ const refusalWords = (reason) => reason === "no-account" ? `No account named \`${account}\`. Nothing changed.`
12454
+ : reason === "revoked" ? `${account} was removed and can't sign in. Nothing changed.`
12455
+ : reason === "sso-only" ? `${account} signs in with ${sso?.label ?? "your identity provider"} and has no password to reset. Nothing changed.`
12456
+ : reason === "no-password" ? `${account} has no password yet. Set one with \`toolroll password set\`. Nothing changed.`
12457
+ : reason === "password-not-allowed" ? `${account} signs in with ${sso?.label ?? "your identity provider"}: passwords are only for instance operators here. Nothing changed.`
12458
+ : "The account changed while you were typing. Nothing changed; run `toolroll password reset` again.";
12459
+ const before = passwordResetRefusal(store, account, operatorsOnly);
12460
+ if (before !== null)
12461
+ return fail(write, json, command, before, refusalWords(before), EXIT.refused);
12462
+ const generation = store.accountOf(account).generation;
12463
+ write(`Reset the password for ${account}.`);
12464
+ write(`This ends ${account}'s browser sessions and remembered passwords, the terminal UI's sign-in, paired chats, phone notifications, lead sessions and lead tokens (mint a new one with \`toolroll lead token\`).`);
12465
+ write("It keeps API and MCP tokens (revoke them in Settings → Sessions & tokens) and coordinator credentials (`toolroll coordinator revoke`). Revoke those too if someone else may know the old password.");
12466
+ const typeHidden = context.easySeams?.askHidden ?? askHidden;
12467
+ const chosen = await typeHidden("New password: ");
12468
+ if (chosen.length < 8)
12469
+ return fail(write, json, command, "weak-password", "A password needs at least 8 characters. Nothing changed.", EXIT.refused);
12470
+ const again = await typeHidden("Type it again: ");
12471
+ if (again !== chosen)
12472
+ return fail(write, json, command, "mismatch", "The two passwords didn't match. Nothing changed.", EXIT.refused);
12473
+ const reset = resetAccountPassword(store, account, hashPassword(chosen), generation, operatorsOnly, context.clock());
12474
+ if (!reset.ok)
12475
+ return fail(write, json, command, reset.reason, refusalWords(reset.reason), EXIT.refused);
12476
+ const cleanup = removeStaleSavedLogin(dirname(context.databaseFile), account, chosen);
12477
+ const { shownPath } = await import("./server/login-help.js");
12478
+ const shown = (path) => shownPath(path, homedir(), null) ?? path;
12479
+ return succeed(write, json, command, { account, generation: reset.generation, removed: cleanup.removed }, () => [
12480
+ `Password reset for ${account}. Every session of ${account} has ended; sign in with the new password.`,
12481
+ ...(reset.leadTokens > 0 ? [`${account}'s lead token ended: mint a new one with \`toolroll lead token\`.`] : []),
12482
+ ...cleanup.removed.map(path => `Removed ${shown(path)}: it held the old password.`),
12483
+ ...cleanup.stale.map(path => `The saved first password at ${shown(path)} no longer works; delete it yourself.`),
12484
+ ...cleanup.unchecked.map(path => `${shown(path)} isn't a plain file in Toolroll's folder, so it was left alone. If it holds ${account}'s old password, delete it yourself.`),
12485
+ ]);
12486
+ }
12487
+ function shellCallerFacts(context) {
12488
+ return {
12489
+ json: context.json,
12490
+ agent: context.easySeams?.agent ?? underAgent(process.env),
12491
+ terminal: context.easySeams?.terminal ?? (process.stdin.isTTY === true && process.stdout.isTTY === true),
12492
+ };
12493
+ }
@@ -4,13 +4,14 @@ import { dirname, join, resolve } from "node:path";
4
4
  import { run } from "./exec.js";
5
5
  import { canonicalProject, projectName, sameRepo } from "./project.js";
6
6
  import { remoteUrlProblem } from "./remote-main.js";
7
- import { addRepos, loadProjectRegistry, removeRepos, updateRepos } from "./repos.js";
7
+ import { addRepos, loadProjectRegistry, removeRepos, updateProjectRegistry, updateRepos } from "./repos.js";
8
8
  import { FolderUnavailable } from "./folder-gate.js";
9
9
  const ADMISSION_GIT = {
10
10
  envAllowlist: ["PATH", "HOME", "TMPDIR", "LANG", "LC_ALL"],
11
11
  env: { GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: "/dev/null", GIT_NO_REPLACE_OBJECTS: "1" },
12
12
  };
13
13
  export const PROJECT_ADDED = "project added";
14
+ export const PROJECT_ADD_INCOMPLETE = "project add incomplete";
14
15
  export const PROJECT_REMOVED = "project removed";
15
16
  export async function proveProjectRoot(path, exec = run, resolveFolder) {
16
17
  if (path.trim() === "" || path.length > 4096 || /[\x00-\x1f]/.test(path)) {
@@ -53,48 +54,78 @@ export async function admitProject(store, input) {
53
54
  const discovered = !known && input.captureOrigin === true && input.actor.origin !== "console"
54
55
  ? await originOf(repo, input.exec ?? run) : null;
55
56
  let remote = { url: store.projectRemote(repo), why: null };
56
- let registryHad = true;
57
+ let enrolledHere = false;
58
+ const latestAdmission = () => Number(store.handle.prepare("SELECT COALESCE(MAX(id), 0) AS id FROM action_ledger WHERE repo = ? AND action = ?").get(repo, PROJECT_ADDED)?.["id"] ?? 0);
59
+ let admittedBefore = 0;
57
60
  const allowed = () => input.stillAllowed === undefined || input.stillAllowed(repo);
58
61
  const moved = { ok: false, reason: "moved", message: `${projectName(repo)} wasn't added: a project folder changed while it was being checked. Try again.` };
59
62
  if (input.registryFile !== null) {
60
63
  let refused = false;
61
64
  let had = false;
62
- const enrolled = await updateRepos(input.registryFile, repos => {
63
- had = repos.includes(repo);
64
- if (!allowed()) {
65
+ const enrolled = await updateProjectRegistry(input.registryFile, current => {
66
+ had = current.repos.includes(repo);
67
+ admittedBefore = latestAdmission();
68
+ if (!allowed() || (input.registryAllowed !== undefined && !input.registryAllowed(repo, current))) {
65
69
  refused = true;
66
- return repos;
70
+ return current;
67
71
  }
68
- return addRepos(repos, [repo]);
72
+ return { ...current, repos: addRepos(current.repos, [repo]) };
69
73
  });
70
74
  if (!enrolled.ok)
71
75
  return { ok: false, reason: enrolled.reason, message: `${projectName(repo)} wasn't added: ${enrolled.message}` };
72
76
  if (refused)
73
77
  return moved;
74
- registryHad = had;
78
+ enrolledHere = !had;
75
79
  }
76
- const added = store.transact(() => {
77
- if (!allowed())
78
- return null;
79
- const rowHad = store.listProjects().some(one => one.path === repo);
80
- const previous = store.projectRemote(repo);
81
- const first = !known && !store.projectAdmissionKnown(repo);
82
- remote = input.remoteUrl !== undefined ? { url: input.remoteUrl, why: null }
83
- : first && discovered !== null ? discovered : { url: previous, why: previous === null ? "no remote recorded; use repos add --remote <url>" : null };
84
- store.upsertProject(repo, projectName(repo), input.now, { remoteUrl: remote.url });
85
- if (input.remoteUrl !== undefined)
86
- store.recordProjectRemote(input.actor.label, repo, previous, input.remoteUrl, input.now);
87
- if (rowHad && registryHad)
88
- return false;
89
- store.recordAction({ at: input.now.toISOString(), actor: input.actor.label, repo, taskId: null, runId: null, action: PROJECT_ADDED, outcome: "added", source: "access", detail: `from ${input.actor.origin}` });
90
- return true;
91
- });
92
- if (added === null) {
93
- if (input.registryFile !== null && !registryHad)
94
- await updateRepos(input.registryFile, repos => removeRepos(repos, [repo]));
95
- return moved;
80
+ const giveBack = async (failure) => {
81
+ if (input.registryFile === null || !enrolledHere)
82
+ return failure;
83
+ let problem;
84
+ try {
85
+ const removed = await updateProjectRegistry(input.registryFile, current => !current.repos.includes(repo) || latestAdmission() > admittedBefore ? current : { ...current, repos: removeRepos(current.repos, [repo]) });
86
+ problem = removed.ok ? null : removed.message;
87
+ }
88
+ catch (error) {
89
+ problem = error instanceof Error ? error.message : String(error);
90
+ }
91
+ if (problem === null)
92
+ return failure;
93
+ let unrecorded = "";
94
+ try {
95
+ store.recordAction({ at: input.now.toISOString(), actor: input.actor.label, repo, taskId: null, runId: null, action: PROJECT_ADD_INCOMPLETE, outcome: "rollback-failed", source: "access",
96
+ detail: `its line in the project list couldn't be taken back: ${problem}` });
97
+ }
98
+ catch (error) {
99
+ unrecorded = ` It couldn't be recorded in the history either (${error instanceof Error ? error.message : String(error)}).`;
100
+ }
101
+ return { ok: false, reason: "incomplete", message: `${projectName(repo)} wasn't added, and its line in the project list couldn't be taken back (${problem}). Remove it with \`toolroll repos remove ${repo}\`.${unrecorded}` };
102
+ };
103
+ let added;
104
+ try {
105
+ added = store.transact(() => {
106
+ if (!allowed())
107
+ return null;
108
+ const rowHad = store.listProjects().some(one => one.path === repo);
109
+ const previous = store.projectRemote(repo);
110
+ const first = !known && !store.projectAdmissionKnown(repo);
111
+ remote = input.remoteUrl !== undefined ? { url: input.remoteUrl, why: null }
112
+ : first && discovered !== null ? discovered : { url: previous, why: previous === null ? "no remote recorded; use repos add --remote <url>" : null };
113
+ store.upsertProject(repo, projectName(repo), input.now, { remoteUrl: remote.url });
114
+ if (input.remoteUrl !== undefined)
115
+ store.recordProjectRemote(input.actor.label, repo, previous, input.remoteUrl, input.now);
116
+ input.withinAdmission?.(repo);
117
+ if (rowHad && !enrolledHere)
118
+ return false;
119
+ store.recordAction({ at: input.now.toISOString(), actor: input.actor.label, repo, taskId: null, runId: null, action: PROJECT_ADDED, outcome: "added", source: "access", detail: `from ${input.actor.origin}` });
120
+ return true;
121
+ });
122
+ }
123
+ catch (error) {
124
+ return giveBack({ ok: false, reason: "failed", message: `${projectName(repo)} wasn't added: ${error instanceof Error ? error.message : String(error)}` });
96
125
  }
97
- return { ok: true, repo, name: projectName(repo), added, remote };
126
+ if (added === null)
127
+ return giveBack(moved);
128
+ return { ok: true, repo, name: projectName(repo), added, remote, enrolled: enrolledHere };
98
129
  }
99
130
  export async function releaseProject(store, input) {
100
131
  const unavailable = (error) => error instanceof FolderUnavailable;
package/dist/project.js CHANGED
@@ -88,3 +88,76 @@ export function rowVisible(ceiling, repo) {
88
88
  export function projectName(path) {
89
89
  return basename(path);
90
90
  }
91
+ export function expandHomePath(path, home) {
92
+ if (path === "~")
93
+ return home;
94
+ if (path.startsWith("~/"))
95
+ return resolve(home, path.slice(2));
96
+ if (path.startsWith("~"))
97
+ return null;
98
+ return path;
99
+ }
100
+ export const SYSTEM_TREES = ["/System", "/Library", "/usr", "/bin", "/sbin", "/etc", "/dev", "/private", "/var", "/proc", "/sys", "/boot", "/run", "/lib", "/lib64", "/cores", "/Network"];
101
+ export const SYSTEM_TOPS = ["/Applications", "/Volumes", "/Users", "/home", "/opt", "/mnt", "/media", "/srv", "/tmp", "/root", "/snap"];
102
+ export function comparisonPaths(home, protectedDirs) {
103
+ return ["/", home, resolve(home, "Library"), ...protectedDirs, ...SYSTEM_TOPS, ...SYSTEM_TREES];
104
+ }
105
+ export function comparisonsOf(found, protectedCount) {
106
+ const after = 3 + protectedCount;
107
+ const unread = { kind: "unreadable" };
108
+ return {
109
+ root: found[0] ?? unread, home: found[1] ?? unread, library: found[2] ?? unread,
110
+ protectedDirs: found.slice(3, after), tops: found.slice(after, after + SYSTEM_TOPS.length), trees: found.slice(after + SYSTEM_TOPS.length),
111
+ };
112
+ }
113
+ export function folderRefusal(kind, target, facts) {
114
+ const id = (one) => one.chain[0];
115
+ const lower = (path) => path.toLowerCase();
116
+ const underPath = (path, outer) => lower(path) === lower(outer) || lower(path).startsWith(outer === "/" ? "/" : `${lower(outer)}/`);
117
+ const within = (one, outer) => outer.kind === "found" ? one.chain.includes(id(outer)) : outer.kind === "missing" ? underPath(one.real, outer.path) : null;
118
+ const holds = (one, inner) => inner.kind === "found" ? inner.chain.includes(id(one)) : inner.kind === "missing" ? underPath(inner.path, one.real) : null;
119
+ const same = (one, other) => other.kind === "found" ? id(other) === id(one) : other.kind === "missing" ? lower(other.path) === lower(one.real) : null;
120
+ const cant = (why) => kind === "folder" ? `${why} can’t be the projects folder` : `${why} can’t be added`;
121
+ const unchecked = cant("a folder Toolroll couldn’t check against its own and the system’s folders");
122
+ const { root, home, library } = facts;
123
+ if (root.kind !== "found" || home.kind !== "found")
124
+ return unchecked;
125
+ if (id(target) === id(root))
126
+ return cant("the top of the disk");
127
+ if (id(target) === id(home))
128
+ return kind === "folder" ? "your home folder itself can’t be the projects folder. Choose a folder inside it, like ~/Developer" : "your home folder itself can’t be added";
129
+ if (holds(target, home))
130
+ return `that folder holds your home folder, so it can’t be ${kind === "folder" ? "the projects folder" : "added"}`;
131
+ for (const dir of facts.protectedDirs) {
132
+ const inDir = within(target, dir);
133
+ const holdsDir = dir.kind === "found" && id(dir) === id(home) ? false : holds(target, dir);
134
+ if (inDir === null || holdsDir === null)
135
+ return unchecked;
136
+ if ((dir.kind === "found" && id(dir) === id(home) ? false : inDir) || holdsDir)
137
+ return cant("a folder holding Toolroll’s own settings, records or task checkouts");
138
+ }
139
+ const inLibrary = within(target, library);
140
+ if (inLibrary === null)
141
+ return unchecked;
142
+ if (inLibrary)
143
+ return cant("a folder in ~/Library");
144
+ if (target.real.split("/").some(name => name.startsWith(".")))
145
+ return cant("a hidden folder");
146
+ if (within(target, home))
147
+ return null;
148
+ for (const top of facts.tops) {
149
+ const is = same(target, top);
150
+ if (is === null)
151
+ return unchecked;
152
+ if (is)
153
+ return cant("a system folder");
154
+ }
155
+ for (const tree of facts.trees) {
156
+ const under = within(target, tree);
157
+ if (under === null)
158
+ return unchecked;
159
+ if (under)
160
+ return cant("a system folder");
161
+ }
162
+ return null;
163
+ }