toolroll 0.9.108 → 0.9.110

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 (187) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/dist/advanced-view.js +0 -1
  3. package/dist/agent-detect.js +244 -0
  4. package/dist/agent-fence.js +47 -5
  5. package/dist/agent-state.js +5 -2
  6. package/dist/agentconfig.js +2 -2
  7. package/dist/approval-summary.js +344 -0
  8. package/dist/assignment-ui.js +5 -5
  9. package/dist/assignment.js +5 -2
  10. package/dist/attest.js +2 -2
  11. package/dist/browser/terminal.js +1 -1
  12. package/dist/browser/workspace.css +2 -2
  13. package/dist/browser/workspace.js +37 -34
  14. package/dist/browser-crew.js +4 -4
  15. package/dist/browser-workspace.js +4 -11
  16. package/dist/builder.js +45 -3
  17. package/dist/chat-actions.js +24 -17
  18. package/dist/chat-controls.js +6 -5
  19. package/dist/chat-core.js +3 -1
  20. package/dist/chat-decide.js +102 -47
  21. package/dist/chat-delivery-state.js +2 -0
  22. package/dist/chat-delivery.js +3 -2
  23. package/dist/chat-live.js +2 -1
  24. package/dist/chat-quiet.js +3 -3
  25. package/dist/chat-task-actions.js +6 -0
  26. package/dist/chat-voice.js +2 -2
  27. package/dist/check-report.js +1 -1
  28. package/dist/cli-help.js +12 -13
  29. package/dist/cli.js +6 -3
  30. package/dist/console-chrome.js +10 -3
  31. package/dist/console-instance.js +10 -1
  32. package/dist/contracts/console-api.js +14 -8
  33. package/dist/contracts/engine-api.js +271 -0
  34. package/dist/contracts/handoff.js +4 -0
  35. package/dist/coordinator.js +2 -2
  36. package/dist/decision.js +17 -0
  37. package/dist/demo-chat.js +1 -1
  38. package/dist/demo.js +6 -0
  39. package/dist/design/kit.js +4 -3
  40. package/dist/discord-api.js +4 -3
  41. package/dist/discord-chat.js +3 -1
  42. package/dist/dispatch.js +3 -8
  43. package/dist/easy-start-args.js +7 -3
  44. package/dist/easy-start.js +25 -0
  45. package/dist/egress.js +72 -10
  46. package/dist/engine-handoff.js +34 -0
  47. package/dist/engine-reads.js +261 -0
  48. package/dist/eval-world.js +3 -2
  49. package/dist/evidence.js +2 -0
  50. package/dist/fast-start.js +55 -14
  51. package/dist/fast-terms.js +2 -2
  52. package/dist/first-run.js +10 -2
  53. package/dist/flexible-agents.js +234 -0
  54. package/dist/flexible-answers-schema.js +61 -0
  55. package/dist/flexible-answers.js +889 -0
  56. package/dist/flexible-available.js +1 -0
  57. package/dist/flexible-custody.js +494 -0
  58. package/dist/flexible-import.js +782 -0
  59. package/dist/flexible-launch-schema.js +72 -0
  60. package/dist/flexible-launch.js +331 -0
  61. package/dist/flexible-launcher.js +88 -0
  62. package/dist/flexible-levels.js +34 -0
  63. package/dist/flexible-merge-guard.js +47 -0
  64. package/dist/flexible-refs.js +47 -0
  65. package/dist/flexible-relay-cancel.js +19 -0
  66. package/dist/flexible-relay-schema.js +55 -0
  67. package/dist/flexible-relay-upstreams.js +36 -0
  68. package/dist/flexible-relay.js +1032 -0
  69. package/dist/flexible-schema.js +32 -0
  70. package/dist/flexible-session.js +732 -0
  71. package/dist/flexible-ship-schema.js +81 -0
  72. package/dist/flexible-ship.js +694 -0
  73. package/dist/flexible-start.js +80 -0
  74. package/dist/flexible-thread-schema.js +30 -0
  75. package/dist/flexible-thread.js +676 -0
  76. package/dist/flexible-turns-schema.js +69 -0
  77. package/dist/flexible-turns.js +490 -0
  78. package/dist/flexible-ui.js +44 -0
  79. package/dist/flexible.js +368 -0
  80. package/dist/flow-actions.js +6 -4
  81. package/dist/flow-steps.js +1 -1
  82. package/dist/flows-cli.js +2 -1
  83. package/dist/git-views.js +44 -41
  84. package/dist/guides.js +11 -10
  85. package/dist/install-mode.js +225 -0
  86. package/dist/keymap.js +1 -1
  87. package/dist/lead-context.js +1 -1
  88. package/dist/lead-doors.js +7 -1
  89. package/dist/limits-ui.js +8 -1
  90. package/dist/live-bus.js +70 -13
  91. package/dist/live-reply.js +6 -0
  92. package/dist/live-terminal.js +425 -29
  93. package/dist/local-owner.js +6 -0
  94. package/dist/model-choices.js +12 -6
  95. package/dist/needs-you.js +3 -3
  96. package/dist/nightly-github.js +2 -2
  97. package/dist/notification-delivery.js +11 -0
  98. package/dist/operate.js +185 -33
  99. package/dist/outbound-privacy.js +204 -0
  100. package/dist/passwordless.js +2 -1
  101. package/dist/project-delete-ui.js +2 -1
  102. package/dist/project-delete.js +15 -0
  103. package/dist/provider-auth.js +1 -1
  104. package/dist/provider-connection.js +5 -3
  105. package/dist/publish.js +5 -0
  106. package/dist/pull-request-flow.js +26 -7
  107. package/dist/push.js +5 -1
  108. package/dist/release-card.js +11 -3
  109. package/dist/release.js +11 -1
  110. package/dist/result-actions.js +3 -0
  111. package/dist/result-evidence-readers.js +8 -2
  112. package/dist/result-review.js +20 -9
  113. package/dist/route-store.js +2 -2
  114. package/dist/sandbox-launch.js +32 -8
  115. package/dist/sandbox-runtime.js +16 -7
  116. package/dist/sandbox-tools.js +176 -0
  117. package/dist/scope.js +12 -36
  118. package/dist/scout-net.js +7 -2
  119. package/dist/serve.js +90 -40
  120. package/dist/server/chat.js +9 -9
  121. package/dist/server/chrome.js +19 -17
  122. package/dist/server/console.css +33 -6
  123. package/dist/server/engine-api.js +378 -0
  124. package/dist/server/flows.js +2 -2
  125. package/dist/server/guards.js +10 -4
  126. package/dist/server/home.js +37 -5
  127. package/dist/server/http.js +11 -2
  128. package/dist/server/in-place.js +5 -4
  129. package/dist/server/kit.js +2 -2
  130. package/dist/server/link-redemption.js +52 -0
  131. package/dist/server/live.js +100 -10
  132. package/dist/server/mutation-key.js +21 -7
  133. package/dist/server/pages.js +129 -74
  134. package/dist/server/people-tokens.js +17 -41
  135. package/dist/server/render-chat.js +2 -1
  136. package/dist/server/render-history.js +18 -4
  137. package/dist/server/render-new-task.js +4 -4
  138. package/dist/server/render-pages.js +21 -39
  139. package/dist/server/render-people.js +2 -2
  140. package/dist/server/render-projects.js +5 -5
  141. package/dist/server/render-results.js +30 -14
  142. package/dist/server/render-tasks.js +155 -155
  143. package/dist/server/retired-routes.js +37 -4
  144. package/dist/server/route-policy.js +8 -0
  145. package/dist/server/route-table.js +43 -5
  146. package/dist/server/settings-computers.js +140 -0
  147. package/dist/server/settings-scripts.js +15 -0
  148. package/dist/server/settings-section-table.js +59 -0
  149. package/dist/server/settings-sections.js +291 -0
  150. package/dist/server/settings.js +247 -28
  151. package/dist/server/task-views.js +55 -15
  152. package/dist/server/tasks.js +168 -98
  153. package/dist/server/terminals.js +181 -28
  154. package/dist/server/welcome.js +40 -14
  155. package/dist/settings-groups-ui.js +26 -107
  156. package/dist/settings-proofs.js +18 -11
  157. package/dist/slack-api.js +4 -3
  158. package/dist/slack-chat.js +5 -3
  159. package/dist/spend.js +46 -12
  160. package/dist/sqlite-telemetry.js +70 -21
  161. package/dist/status-probe.js +343 -0
  162. package/dist/store.js +206 -10
  163. package/dist/task-link.js +64 -0
  164. package/dist/teams-api.js +4 -3
  165. package/dist/teams-chat.js +4 -2
  166. package/dist/telegram-lead.js +2 -1
  167. package/dist/telegram-live.js +2 -1
  168. package/dist/telegram-team.js +2 -1
  169. package/dist/telegram.js +17 -5
  170. package/dist/trusted-path.js +162 -0
  171. package/dist/tui/darwin-arm64/toolroll-tui +0 -0
  172. package/dist/tui/darwin-x64/toolroll-tui +0 -0
  173. package/dist/tui/linux-arm64/toolroll-tui +0 -0
  174. package/dist/tui/linux-x64/toolroll-tui +0 -0
  175. package/dist/tui-launch.js +282 -0
  176. package/dist/tui-source.js +5 -3
  177. package/dist/tui.js +2 -2
  178. package/dist/typed-words-schema.js +18 -0
  179. package/dist/webhooks.js +8 -4
  180. package/dist/welcome-facts.js +25 -17
  181. package/dist/work-index.js +126 -29
  182. package/dist/work-reads.js +279 -0
  183. package/dist/workspace-ui.js +5 -0
  184. package/package.json +4 -2
  185. package/scripts/crash-canary.mjs +1 -1
  186. package/scripts/pilot.mjs +1 -1
  187. package/scripts/provider-canary.mjs +5 -3
@@ -0,0 +1,204 @@
1
+ import { scanForSecrets } from "./evidence.js";
2
+ const HOME_FOLDER = /(?:^|[\s"'`(<[=:,])(?:\/Users\/|\/home\/|\/root\/|~\/)/;
3
+ const DRIVE_OR_SHARE = /(?<![A-Za-z0-9+.-])[A-Za-z]:[\\/]|\\\\|\bfile:\/\//i;
4
+ export function privateWords(text) {
5
+ return scanForSecrets(text).length > 0 || /\b\d{5,}:[A-Za-z0-9_-]{20,}\b/.test(text) || HOME_FOLDER.test(text) || DRIVE_OR_SHARE.test(text);
6
+ }
7
+ export const outboundPrivate = (fields) => fields.some(privateWords);
8
+ export function textsOf(value, depth = 0) {
9
+ if (typeof value === "string")
10
+ return [value];
11
+ if (depth > 12 || value === null || typeof value !== "object")
12
+ return [];
13
+ return (Array.isArray(value) ? value : Object.values(value)).flatMap(one => textsOf(one, depth + 1));
14
+ }
15
+ const unescaped = (text) => text.replace(/\\([\\`*_{}[\]()#+\-.!|~>])/g, "$1");
16
+ export const privateValue = (value) => textsOf(value).some(text => privateWords(text) || privateWords(unescaped(text)));
17
+ export function projectName(repo) {
18
+ if (repo === null || repo === undefined)
19
+ return null;
20
+ const name = (repo.split(/[\\/]/).filter(Boolean).pop() ?? "").replace(/[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2060-\u206f]/g, "").trim().slice(0, 48);
21
+ return name === "" || privateWords(name) || privateWords(` ${name}`) ? null : name;
22
+ }
23
+ export function taskSubject(store, task) {
24
+ if (task === null || task === undefined || task === "")
25
+ return { project: null };
26
+ return { project: store.lookupRef(task)?.repo ?? null, withheld: privateWords(store.getTask(task)?.title ?? "") };
27
+ }
28
+ export function safeWords(subject) {
29
+ const name = projectName(subject?.project);
30
+ return name === null ? "An update is ready. Open it in Toolroll." : `An update is ready in ${name}. Open it in Toolroll.`;
31
+ }
32
+ export function checkedChunks(whole, chunks, subject) {
33
+ return privateValue(whole) ? [safeWords(subject)] : [...chunks];
34
+ }
35
+ export const OPEN_IN_TOOLROLL = "Open in Toolroll";
36
+ export const WITHHELD = "Its words name a key or a folder on this computer, so it stays in Toolroll.";
37
+ export function safeLink(value) {
38
+ if (typeof value !== "string" || value.length > 2_000)
39
+ return null;
40
+ let url;
41
+ try {
42
+ url = new URL(value);
43
+ }
44
+ catch {
45
+ return null;
46
+ }
47
+ if ((url.protocol !== "https:" && url.protocol !== "http:") || url.username !== "" || url.password !== "")
48
+ return null;
49
+ let decoded;
50
+ try {
51
+ decoded = decodeURIComponent(`${url.pathname}${url.search}${url.hash}`);
52
+ }
53
+ catch {
54
+ return null;
55
+ }
56
+ if (privateWords(value) || privateWords(` ${decoded}`))
57
+ return null;
58
+ return /[|<>\s]/.test(url.href) ? null : url.href;
59
+ }
60
+ export function firstLink(value, depth = 0) {
61
+ if (depth > 12 || value === null || typeof value !== "object")
62
+ return null;
63
+ for (const [key, one] of Object.entries(value)) {
64
+ if (key === "url" && safeLink(one) !== null)
65
+ return safeLink(one);
66
+ const found = firstLink(one, depth + 1);
67
+ if (found !== null)
68
+ return found;
69
+ }
70
+ return null;
71
+ }
72
+ const pick = (from, keys) => Object.fromEntries(keys.filter(key => from[key] !== undefined).map(key => [key, from[key]]));
73
+ const goesSafe = (subject, message, ...values) => (message && subject?.withheld === true) || values.some(privateValue);
74
+ const checked = (made) => made === null || privateValue(made) ? null : made;
75
+ export function guardTelegram(transport, subject) {
76
+ return async (method, params, signal, upload, more) => {
77
+ const files = [upload, ...(more ?? [])].filter((one) => one !== undefined);
78
+ const privateFile = files.some(one => one.contentType === "text/plain" && privateWords(one.bytes.toString("utf8")));
79
+ if (!privateFile && !goesSafe(subject, TELEGRAM_MESSAGES.has(method), params))
80
+ return transport(method, params, signal, upload, more);
81
+ const safe = privateFile ? null : checked(safeTelegramCall(method, params, safeWords(subject)));
82
+ if (safe === null)
83
+ return { ok: false, description: WITHHELD };
84
+ return transport(method, safe, signal, upload, more);
85
+ };
86
+ }
87
+ const TELEGRAM_MESSAGES = new Set(["sendMessage", "editMessageText", "sendMessageDraft", "sendPhoto", "sendDocument", "editMessageCaption", "sendMediaGroup"]);
88
+ function safeTelegramCall(method, params, words) {
89
+ const link = firstLink(params["reply_markup"]);
90
+ const keyboard = link === null ? {} : { reply_markup: { inline_keyboard: [[{ text: OPEN_IN_TOOLROLL, url: link }]] } };
91
+ const where = pick(params, ["chat_id", "message_id", "inline_message_id", "message_thread_id", "reply_parameters", "draft_id", "disable_notification"]);
92
+ switch (method) {
93
+ case "sendMessage":
94
+ case "editMessageText":
95
+ case "sendMessageDraft":
96
+ return { ...where, text: words, link_preview_options: { is_disabled: true }, ...(method === "sendMessageDraft" ? {} : keyboard) };
97
+ case "sendPhoto":
98
+ case "sendDocument":
99
+ case "editMessageCaption":
100
+ return { ...pick(params, ["photo", "document"]), ...where, caption: words, ...keyboard };
101
+ case "sendMediaGroup": {
102
+ const media = Array.isArray(params["media"]) ? params["media"] : [];
103
+ return { ...where, media: media.map((one, index) => {
104
+ const item = one !== null && typeof one === "object" ? one : {};
105
+ return { ...pick(item, ["type", "media"]), ...(index === 0 ? { caption: words } : {}) };
106
+ }) };
107
+ }
108
+ case "answerCallbackQuery":
109
+ return { ...pick(params, ["callback_query_id"]), text: "Open it in Toolroll." };
110
+ default:
111
+ return null;
112
+ }
113
+ }
114
+ export function guardSlack(api, refuse, subject) {
115
+ return (async (method, args) => {
116
+ if (args === undefined || !goesSafe(subject, SLACK_MESSAGES.has(method), args))
117
+ return api(method, args);
118
+ const safe = checked(safeSlackCall(method, args, safeWords(subject)));
119
+ if (safe === null)
120
+ throw refuse();
121
+ return api(method, safe);
122
+ });
123
+ }
124
+ const SLACK_MESSAGES = new Set(["chat.postMessage", "chat.update", "chat.postEphemeral", "files.completeUploadExternal"]);
125
+ function safeSlackCall(method, args, words) {
126
+ const escaped = words.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
127
+ switch (method) {
128
+ case "chat.postMessage":
129
+ case "chat.update":
130
+ case "chat.postEphemeral": {
131
+ const link = firstLink(args["blocks"]) ?? firstLink(args["attachments"]);
132
+ const text = link === null ? escaped : `${escaped} <${link}|${OPEN_IN_TOOLROLL}>`;
133
+ return { ...pick(args, ["channel", "ts", "thread_ts", "user"]), text, blocks: [{ type: "section", text: { type: "mrkdwn", text, verbatim: true } }],
134
+ mrkdwn: true, parse: "none", link_names: false, unfurl_links: false, unfurl_media: false };
135
+ }
136
+ case "files.completeUploadExternal": {
137
+ const files = Array.isArray(args["files"]) ? args["files"] : [];
138
+ return { ...pick(args, ["channel_id", "thread_ts"]), initial_comment: words,
139
+ files: files.map(one => ({ id: one !== null && typeof one === "object" ? one["id"] : undefined, title: words })) };
140
+ }
141
+ default:
142
+ return null;
143
+ }
144
+ }
145
+ export function guardDiscord(api, refuse, subject) {
146
+ return (async (method, path, body, file) => {
147
+ if (!goesSafe(subject, body !== undefined && discordMessagePath(method, path) !== null, body, file?.name ?? ""))
148
+ return api(method, path, body, file);
149
+ const safe = file !== undefined && privateWords(file.name) ? null : checked(safeDiscordCall(method, path, body ?? {}, safeWords(subject)));
150
+ if (safe === null)
151
+ throw refuse();
152
+ return api(method, path, safe, file);
153
+ });
154
+ }
155
+ function discordMessage(body, words) {
156
+ const link = firstLink(body["components"]) ?? firstLink(body["embeds"]);
157
+ const attachments = Array.isArray(body["attachments"]) ? body["attachments"].map(one => one !== null && typeof one === "object" ? pick(one, ["id", "filename"]) : {}) : undefined;
158
+ return { content: words.replace(/[\\*_~`|>#[\]()-]/g, "\\$&"), embeds: [],
159
+ components: link === null ? [] : [{ type: 1, components: [{ type: 2, style: 5, label: OPEN_IN_TOOLROLL, url: link }] }],
160
+ allowed_mentions: { parse: [], replied_user: false }, ...pick(body, ["message_reference", "flags"]), ...(attachments === undefined ? {} : { attachments }) };
161
+ }
162
+ function discordMessagePath(method, path) {
163
+ if ((method === "POST" || method === "PATCH") && /^\/channels\/[0-9]+\/messages(?:\/[0-9]+)?$/.test(path))
164
+ return "message";
165
+ if (method === "POST" && /^\/interactions\/[0-9]+\/[A-Za-z0-9._-]+\/callback$/.test(path))
166
+ return "interaction";
167
+ return null;
168
+ }
169
+ function safeDiscordCall(method, path, body, words) {
170
+ const kind = discordMessagePath(method, path);
171
+ if (kind === "message")
172
+ return discordMessage(body, words);
173
+ if (kind === "interaction") {
174
+ const data = body["data"] !== null && typeof body["data"] === "object" ? body["data"] : {};
175
+ return { type: body["type"], data: discordMessage(data, words) };
176
+ }
177
+ return null;
178
+ }
179
+ export function guardTeams(api, refuse, subject) {
180
+ return (async (method, serviceUrl, path, body) => {
181
+ if (!goesSafe(subject, teamsMessage(method, path, body), body))
182
+ return api(method, serviceUrl, path, body);
183
+ const safe = checked(teamsMessage(method, path, body) ? safeTeamsActivity(body, safeWords(subject)) : null);
184
+ if (safe === null)
185
+ throw refuse();
186
+ return api(method, serviceUrl, path, safe);
187
+ });
188
+ }
189
+ const teamsMessage = (method, path, body) => method !== "GET" && /\/activities(?:\/[^/]+)?$/.test(path) && body?.["type"] === "message";
190
+ function safeTeamsActivity(body, words) {
191
+ const link = firstLink(body["attachments"]);
192
+ const where = pick(body, ["replyToId"]);
193
+ if (link === null)
194
+ return { type: "message", ...where, text: words, textFormat: "plain" };
195
+ return { type: "message", ...where, attachments: [{ contentType: "application/vnd.microsoft.card.adaptive",
196
+ content: { type: "AdaptiveCard", version: "1.4", $schema: "http://adaptivecards.io/schemas/adaptive-card.json",
197
+ body: [{ type: "TextBlock", text: words, wrap: true }], actions: [{ type: "Action.OpenUrl", title: OPEN_IN_TOOLROLL, url: link }] } }] };
198
+ }
199
+ export function safeMail(mail, subject) {
200
+ if (!outboundPrivate([mail.subject, mail.text]))
201
+ return mail;
202
+ const name = projectName(subject?.project);
203
+ return { ...mail, subject: name === null ? "An update from Toolroll" : `An update from Toolroll in ${name}`, text: safeWords(subject) };
204
+ }
@@ -13,7 +13,8 @@ export function passwordlessSetting(store) {
13
13
  }
14
14
  export const passwordlessOn = (store) => passwordlessSetting(store).on;
15
15
  export function setPasswordless(store, on, by, now) {
16
- if (passwordlessOn(store) === on)
16
+ const setting = passwordlessSetting(store);
17
+ if (setting.on === on && (on || setting.at !== null))
17
18
  return { changed: false };
18
19
  store.recordAction({ at: now.toISOString(), actor: by, repo: null, taskId: null, runId: null, action: PASSWORDLESS_ACTION, outcome: on ? "on" : "off", source: "policy",
19
20
  detail: on ? "Passwordless on: signing in is the only password" : "Passwordless off: step-ups ask for the password again" });
@@ -6,6 +6,7 @@ import { html, joinHtml, postForm } from "./html.js";
6
6
  import { holdingsWords } from "./project-delete.js";
7
7
  import { acts, btn, codeLine, disclose, formRow, infoLine, input, note, notice, radios, settingsSection, switchInput, textarea } from "./server/kit.js";
8
8
  import { kitSectionForm } from "./settings-kit.js";
9
+ import { flexibleSettingsHtml } from "./flexible-ui.js";
9
10
  export const PROJECT_DELETE_CSS = ".k-opt [data-check-access-warning]{display:none;color:var(--so-ink)}.k-opt:has(input:checked) [data-check-access-warning]{display:block}" +
10
11
  ".k-opt:has(input:disabled){cursor:default;opacity:.6}";
11
12
  const mono = (text) => html `<span class="k-mono">${text}</span>`;
@@ -199,7 +200,7 @@ export function projectSettingsHtml(view, said) {
199
200
  disclose("Change remote", joinHtml([note("An owner or instance operator can run:"), codeLine("toolroll repos add <project> --remote <url>")])),
200
201
  ]) });
201
202
  const advanced = advancedShownNow();
202
- const settings = joinHtml([buildsHtml(view), accessHtml(view), networkHtml(view), advanced || (view.fallback?.setting ?? null) !== null ? fallbackHtml(view) : "",
203
+ const settings = joinHtml([flexibleSettingsHtml(view.flexible), buildsHtml(view), accessHtml(view), networkHtml(view), advanced || (view.fallback?.setting ?? null) !== null ? fallbackHtml(view) : "",
203
204
  writesHtml(view), sandboxHtml(view), checkAccessHtml(view), advanced || view.liveView?.commands === true ? liveViewHtml(view) : "", advanced ? codeMapHtml(view) : ""]);
204
205
  if (!view.canDelete)
205
206
  return joinHtml([answer, project, settings, note("An instance operator can remove or delete a project.")]);
@@ -30,6 +30,7 @@ const SETTINGS = [
30
30
  ["learning_policy", "repo"], ["operating_mode", "repo"], ["project_knowledge", "repo"], ["live_detail_setting", "repo"],
31
31
  ["project_decision", "repo"], ["flow_script", "repo"], ["workflow_recipe", "repo"], ["team_lead_project", "project"],
32
32
  ["fallback_setting", "repo"],
33
+ ["flexible_terms", "repo"],
33
34
  ];
34
35
  export const MODEL_SETTINGS = Object.freeze([["phase_config", "scope"], ["phase_tier_config", "scope"], ["phase_tier_alternate", "scope"]]);
35
36
  export const PROJECT_SETTINGS = Object.freeze(SETTINGS.map(one => [...one]));
@@ -70,6 +71,9 @@ export function projectRunning(store, repo, now) {
70
71
  const merges = count(`SELECT COUNT(*) AS n FROM merge_intent WHERE state IN ('claimed','firing') AND publication IN (SELECT id FROM publication WHERE task_ref IN (SELECT value FROM json_each(?)))`, json(d.refs))
71
72
  + count("SELECT COUNT(*) AS n FROM merge_in_flight WHERE at > ? AND task_ref IN (SELECT value FROM json_each(?))", new Date(now.getTime() - 15 * 60_000).toISOString(), json(d.refs));
72
73
  const checkouts = count("SELECT COUNT(*) AS n FROM worktree WHERE repo = ? AND runner IS NOT NULL AND released_at IS NULL", repo);
74
+ const threads = tableExists(db, "flexible_thread") ? count("SELECT COUNT(*) AS n FROM flexible_thread WHERE repo = ? AND state IN ('preparing', 'ready', 'removing')", repo) : 0;
75
+ const agents = tableExists(db, "flexible_thread_launch")
76
+ ? count("SELECT COUNT(*) AS n FROM flexible_thread_launch WHERE state <> 'exited' AND thread IN (SELECT id FROM flexible_thread WHERE repo = ?)", repo) : 0;
73
77
  return [
74
78
  ...(building > 0 ? [`${plural(building, "task")} ${building === 1 ? "is" : "are"} being built`] : []),
75
79
  ...(slots > 0 ? ["an agent is working"] : []),
@@ -78,6 +82,8 @@ export function projectRunning(store, repo, now) {
78
82
  ...(calls > 0 ? ["a subagent is working"] : []),
79
83
  ...(merges > 0 ? ["a merge is in progress"] : []),
80
84
  ...(checkouts > 0 && building === 0 ? [`${plural(checkouts, "checkout")} ${checkouts === 1 ? "is" : "are"} in use`] : []),
85
+ ...(agents > 0 ? ["a Flexible thread's agent is still running"] : []),
86
+ ...(threads > 0 ? [`${plural(threads, "Flexible thread")} ${threads === 1 ? "is" : "are"} still open (remove ${threads === 1 ? "it" : "them"} first)`] : []),
81
87
  ];
82
88
  }
83
89
  const inside = (root, path) => { const rel = relative(resolve(root), resolve(path)); return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel); };
@@ -293,6 +299,15 @@ function deleteRows(store, repo, d, now) {
293
299
  for (const table of ["knowledge_change", "project_identity_carry", "project_skill_change", "memory_gap", "memory_proposal", "memory_rejection", "memory_session", "memory_search", "mode_rail", "side_spend", "watch_episode", "worktree", "coordinator_proposal", "lead_commitment"])
294
300
  del(table, "repo = ?", repo);
295
301
  del("watch_lease", "repo = ? AND expires_at <= ?", repo, now.toISOString());
302
+ const flexibleThreads = `thread IN (SELECT id FROM flexible_thread WHERE repo = ? AND state IN ('removed', 'failed'))`;
303
+ del("thread_decision", flexibleThreads, repo);
304
+ del("thread_relay_call", flexibleThreads, repo);
305
+ del("thread_relay_pending", flexibleThreads, repo);
306
+ del("flexible_relay_grant", flexibleThreads, repo);
307
+ del("thread_turn", flexibleThreads, repo);
308
+ del("flexible_thread_launch", flexibleThreads, repo);
309
+ del("flexible_thread_level", flexibleThreads, repo);
310
+ del("flexible_thread", "repo = ? AND state IN ('removed', 'failed')", repo);
296
311
  del("project", "path = ?", repo);
297
312
  return rows;
298
313
  }
@@ -105,7 +105,7 @@ function notifyOperators(store, key, message, now) {
105
105
  dedupeKey: `${SIGN_IN_KEY_PREFIX}${key}:${recipient}`,
106
106
  kind: message.kind,
107
107
  pushClass: "attention",
108
- link: "/tasks",
108
+ link: "/",
109
109
  subject: message.subject,
110
110
  body: message.body,
111
111
  recipient,
@@ -1,5 +1,6 @@
1
1
  import { homedir } from "node:os";
2
- import { run } from "./exec.js";
2
+ import {} from "./exec.js";
3
+ import { statusProbe } from "./status-probe.js";
3
4
  import { ALL_CREDENTIAL_ENV, inspectionOf } from "./provider.js";
4
5
  import { isAcpProvider } from "./acp-agents.js";
5
6
  import { keyStatus, PROVIDER_KEY_ENV, readAuthMode, readProviderKey, verifyProviderKey } from "./keys.js";
@@ -39,9 +40,10 @@ export function signInFacts(provider, result, now = new Date()) {
39
40
  return { ...base, state: "unverified" };
40
41
  }
41
42
  export function createConnectionChecker(options = {}) {
42
- const probe = options.probe ?? run;
43
- const verify = options.verify ?? ((provider, key) => verifyProviderKey(provider, key));
44
43
  const home = options.home ?? homedir();
44
+ const probe = options.probe ?? statusProbe({ ...(options.env === undefined ? {} : { env: options.env }), ...(options.store === undefined ? {} : { store: options.store }),
45
+ ...(options.databaseFile === undefined ? {} : { databaseFile: options.databaseFile }) });
46
+ const verify = options.verify ?? ((provider, key) => verifyProviderKey(provider, key));
45
47
  const clock = options.clock ?? (() => new Date());
46
48
  const cache = new Map();
47
49
  const pending = new Map();
package/dist/publish.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { flexibleMergeRefusal } from "./flexible-merge-guard.js";
1
2
  import { createHash } from "node:crypto";
2
3
  import { protectedPublicationHold } from "./result-completion.js";
3
4
  import { fastPublishProblem } from "./fast-start.js";
@@ -427,6 +428,10 @@ export async function sweepMerges(store, options) {
427
428
  continue;
428
429
  if (publication.githubRepo !== grant.githubRepo)
429
430
  continue;
431
+ if (flexibleMergeRefusal(store, ref.externalId, "publish-sweep") !== null) {
432
+ report.skipped++;
433
+ continue;
434
+ }
430
435
  const blocker = store.mergeBlockerFor(publication.id);
431
436
  if (blocker !== null) {
432
437
  report.skipped++;
@@ -1,6 +1,7 @@
1
1
  import { fastPublishProblem } from "./fast-start.js";
2
2
  import { createHash, randomUUID } from "node:crypto";
3
3
  import { run as execRun } from "./exec.js";
4
+ import { flexibleMergeRefusal } from "./flexible-merge-guard.js";
4
5
  import { bodyHashOf, publicationBody, publicationGrantOf } from "./publish.js";
5
6
  import { failingChecks, summarizeChecks } from "./pulls.js";
6
7
  import { assignmentOf, checkAssignmentAsOperator } from "./assignment.js";
@@ -254,6 +255,8 @@ export async function followPullRequests(store, seen, options) {
254
255
  const taskId = taskIdOf(store, publication);
255
256
  if (refArchived(store, publication.taskRef))
256
257
  continue;
258
+ if (flexibleMergeRefusal(store, taskId, "merge-when-green") !== null)
259
+ continue;
257
260
  if (one.remoteState === "MERGED") {
258
261
  updateFollow(store, publication.id, { merge_commit: one.mergeCommit ?? "", merged_by: "GitHub", merged_at: clock().toISOString() }, clock());
259
262
  continue;
@@ -363,6 +366,10 @@ export async function mergePullRequest(store, input) {
363
366
  return refuse("release", "This result belongs to a release; it merges only through `toolroll release`.");
364
367
  if (mergedTask !== null && autoReleaseSealed(store, mergedTask))
365
368
  return refuse("release", "This result was approved automatically for a release; it merges only through `toolroll release`.");
369
+ const flexibleAuthority = { ...(input.flexibleShip === undefined ? {} : { ship: input.flexibleShip }), ...(input.flexibleToken === undefined ? {} : { token: input.flexibleToken }), ...(input.anyway === true ? { anyway: true } : {}) };
370
+ const flexibleHold = flexibleMergeRefusal(store, mergedTask, "pull-request", flexibleAuthority);
371
+ if (flexibleHold !== null)
372
+ return refuse("flexible", flexibleHold);
366
373
  const fastHold = mergedTask === null ? null : fastPublishProblem(store, mergedTask, input.runId);
367
374
  if (fastHold !== null)
368
375
  return refuse("fast-start", fastHold);
@@ -370,7 +377,9 @@ export async function mergePullRequest(store, input) {
370
377
  const follow = publication === null ? null : followOf(store, publication.id);
371
378
  if (publication === null || follow === null || publication.prNumber === null)
372
379
  return refuse("no-pr", "This result has no open pull request to merge.");
373
- if (follow.mergeCommit !== null)
380
+ if (input.flexibleShip !== undefined && input.destination === undefined)
381
+ return refuse("flexible", "A Flexible merge must say where it may land.");
382
+ if (follow.mergeCommit !== null && input.destination === undefined)
374
383
  return { ok: true, commit: follow.mergeCommit || null };
375
384
  const ref = store.refById(publication.taskRef);
376
385
  const grant = ref?.repo == null ? null : store.publicationGrantFor(ref.repo);
@@ -379,13 +388,14 @@ export async function mergePullRequest(store, input) {
379
388
  const method = input.method ?? grant.mergeMethod ?? "squash";
380
389
  const pr = String(publication.prNumber);
381
390
  const view = async () => {
382
- const viewed = await exec("gh", ["pr", "view", pr, "--repo", publication.githubRepo, "--json", "state,isDraft,headRefOid,statusCheckRollup,mergeCommit"], { timeoutMs: EXEC_TIMEOUT_MS });
391
+ const viewed = await exec("gh", ["pr", "view", pr, "--repo", publication.githubRepo, "--json", "state,isDraft,headRefOid,statusCheckRollup,mergeCommit,baseRefName,url"], { timeoutMs: EXEC_TIMEOUT_MS });
383
392
  if (viewed.code !== 0)
384
393
  return null;
385
394
  try {
386
395
  const payload = JSON.parse(viewed.stdout);
387
396
  return { state: String(payload.state ?? "").toUpperCase(), draft: payload.isDraft === true, head: typeof payload.headRefOid === "string" ? payload.headRefOid : null,
388
- checks: summarizeChecks(payload.statusCheckRollup), commit: typeof payload.mergeCommit?.oid === "string" ? payload.mergeCommit.oid : null };
397
+ checks: summarizeChecks(payload.statusCheckRollup), commit: typeof payload.mergeCommit?.oid === "string" ? payload.mergeCommit.oid : null,
398
+ base: typeof payload.baseRefName === "string" ? payload.baseRefName : null, url: typeof payload.url === "string" ? payload.url : null };
389
399
  }
390
400
  catch {
391
401
  return null;
@@ -418,8 +428,12 @@ export async function mergePullRequest(store, input) {
418
428
  if (before === null)
419
429
  return fail("unread", "GitHub couldn't be read just now. Try again.");
420
430
  if (before.state === "MERGED") {
421
- record(before.commit, input.by);
422
- return { ok: true, commit: before.commit };
431
+ const landed = input.destination?.({ base: before.base, url: before.url, head: before.head }) ?? null;
432
+ if (landed !== null)
433
+ return refuse("elsewhere", landed);
434
+ if (follow.mergeCommit === null)
435
+ record(before.commit, input.by);
436
+ return { ok: true, commit: before.commit, ...(input.destination === undefined ? {} : { seen: { base: before.base, url: before.url, head: before.head } }) };
423
437
  }
424
438
  if (before.state !== "OPEN")
425
439
  return fail("closed", "This pull request is closed on GitHub.");
@@ -431,7 +445,9 @@ export async function mergePullRequest(store, input) {
431
445
  return fail("checks", before.checks === "failing" ? "Checks are failing, so it can't merge." : before.checks === "running" ? "Checks are still running. Merge once they pass." : "No checks have reported yet. Merge once they pass.");
432
446
  const token = randomUUID();
433
447
  const reserved = store.transact(() => {
434
- if (input.proceed?.() === false)
448
+ if (input.proceed?.({ base: before.base, url: before.url, head: before.head }) === false)
449
+ return "halted";
450
+ if (flexibleMergeRefusal(store, mergedTask, "pull-request", flexibleAuthority, "reserve") !== null)
435
451
  return "halted";
436
452
  if (refArchived(store, publication.taskRef))
437
453
  return "archived";
@@ -459,8 +475,11 @@ export async function mergePullRequest(store, input) {
459
475
  store.handle.prepare("DELETE FROM merge_in_flight WHERE publication = ? AND token = ?").run(publication.id, token);
460
476
  }
461
477
  if (after?.state === "MERGED") {
478
+ const landed = input.destination?.({ base: after.base, url: after.url, head: after.head }) ?? null;
479
+ if (landed !== null)
480
+ return refuse("elsewhere", landed);
462
481
  record(after.commit, input.by);
463
- return { ok: true, commit: after.commit };
482
+ return { ok: true, commit: after.commit, ...(input.destination === undefined ? {} : { seen: { base: after.base, url: after.url, head: after.head } }) };
464
483
  }
465
484
  if (merged.code === 4)
466
485
  return fail("gh-signed-out", "The GitHub CLI isn't signed in on this computer. Run gh auth login, then merge again.");
package/dist/push.js CHANGED
@@ -3,6 +3,7 @@ import { join } from "node:path";
3
3
  import { createCipheriv, createECDH, createPrivateKey, hkdfSync, randomBytes, createHash, sign as cryptoSign } from "node:crypto";
4
4
  import { isCheckProgressLine } from "./check-progress.js";
5
5
  import { RELEASE_PUSH_WORDS, releasePushOf, releaseReadyObsolete } from "./release-approval.js";
6
+ import { privateValue } from "./outbound-privacy.js";
6
7
  export const VAPID_FILE = "vapid-keys.json";
7
8
  const RECORD_SIZE = 4096;
8
9
  export const PLAINTEXT_CEILING = 3993;
@@ -190,8 +191,11 @@ export function pushLineOf(notification) {
190
191
  }
191
192
  return { body: PUSH_WORDS[pushClass].body, url: safePushLink(pushClass, notification.link) };
192
193
  }
194
+ export function privacySafeLine(line, pushClass) {
195
+ return privateValue(line) ? { body: PUSH_WORDS[pushClass].body, url: CLASS_FALLBACK[pushClass] } : line;
196
+ }
193
197
  export function buildPushPayload(notification, waiting = null, release = null) {
194
- const line = release !== null ? { body: PUSH_WORDS.release.body, url: safePushLink("release", release.link) } : pushLineOf(notification);
198
+ const line = privacySafeLine(release !== null ? { body: PUSH_WORDS.release.body, url: safePushLink("release", release.link) } : pushLineOf(notification), release !== null ? "release" : notification.pushClass ?? "attention");
195
199
  return JSON.stringify({
196
200
  title: "Toolroll",
197
201
  body: line.body,
@@ -93,11 +93,18 @@ const valueAt = (terms, path) => path.split(".").reduce((at, key) => at !== null
93
93
  export function approvalTermsOf(store, scope, words) {
94
94
  const ref = store.lookupRef(scope.taskId);
95
95
  const repo = ref?.repo ?? null;
96
+ const where = (path) => {
97
+ if (words.chat !== true)
98
+ return text(path);
99
+ const remote = store.projectRemote(path);
100
+ const slug = remote === null ? null : releaseRemote(remote)?.slug ?? null;
101
+ return slug ?? text(projectName(path));
102
+ };
96
103
  const filer = store.taskFiler(scope.taskId);
97
104
  const profile = scope.profile ?? null;
98
105
  const scopeValues = {
99
106
  title: said(store.getTask(scope.taskId)?.title),
100
- project: repo === null ? NONE : `${text(projectName(repo))} (${text(repo)})`,
107
+ project: repo === null ? NONE : `${text(projectName(repo))} (${where(repo)})`,
101
108
  filedBy: filer === null ? NONE : filer.name === null ? filer.kind : `${text(filer.name)}${filer.kind === "person" ? "" : ` (${filer.kind})`}`,
102
109
  goal: said(scope.goal),
103
110
  outOfScope: said(scope.outOfScope),
@@ -127,7 +134,7 @@ export function approvalTermsOf(store, scope, words) {
127
134
  if (terms === null && scope.releaseCheck != null) {
128
135
  const purpose = scope.releaseCheck;
129
136
  for (const path of schemaLeaves(releaseCheckPurposeSchema)) {
130
- const value = path === "pr" ? `#${purpose.pr}` : path === "purpose" ? "a release check: every later commit asks again" : said(valueAt(purpose, path));
137
+ const value = path === "pr" ? `#${purpose.pr}` : path === "purpose" ? "a release check: every later commit asks again" : path === "repo" ? where(purpose.repo) : said(valueAt(purpose, path));
131
138
  lines.push({ key: `releaseCheck.${path}`, label: RELEASE_CHECK_LABELS[path] ?? path, value });
132
139
  }
133
140
  return lines;
@@ -136,7 +143,8 @@ export function approvalTermsOf(store, scope, words) {
136
143
  const label = RELEASE_TERM_LABELS[path] ?? path;
137
144
  const value = terms === null ? NONE : path === "pr" ? `#${terms.pr}`
138
145
  : path === "policy.protectedPaths" && terms.policy.protectProject ? `the whole project (listed: ${said(terms.policy.protectedPaths)})`
139
- : path === "policy.unsandboxedCarry" && terms.policy.unsandboxedCarry === undefined ? "no (not set when sealed)" : said(valueAt(terms, path));
146
+ : path === "policy.unsandboxedCarry" && terms.policy.unsandboxedCarry === undefined ? "no (not set when sealed)"
147
+ : path === "repo" ? where(terms.repo) : said(valueAt(terms, path));
140
148
  lines.push({ key: `release.${path}`, label, value });
141
149
  }
142
150
  return lines;
package/dist/release.js CHANGED
@@ -36,8 +36,18 @@ export const ADVISORY_PR_CHECKS = {
36
36
  "upgrade path": ".github/workflows/upgrade-path.yml",
37
37
  "install smoke · ubuntu-24.04": ".github/workflows/install-smoke.yml",
38
38
  "install smoke · macos-latest": ".github/workflows/install-smoke.yml",
39
+ "wire budgets": ".github/workflows/wire-budgets.yml",
40
+ "rust · ubuntu-latest": ".github/workflows/rust.yml",
41
+ "rust · macos-latest": ".github/workflows/rust.yml",
42
+ "workbench bundle · ubuntu-24.04": ".github/workflows/tui-bundle.yml",
43
+ "workbench bundle · macos-latest": ".github/workflows/tui-bundle.yml",
44
+ "workbench bundle / binary · darwin-arm64": ".github/workflows/tui-bundle.yml",
45
+ "workbench bundle / binary · darwin-x64": ".github/workflows/tui-bundle.yml",
46
+ "workbench bundle / binary · linux-x64": ".github/workflows/tui-bundle.yml",
47
+ "workbench bundle / binary · linux-arm64": ".github/workflows/tui-bundle.yml",
48
+ "workbench bundle / assemble": ".github/workflows/tui-bundle.yml",
39
49
  };
40
- export const RELEASE_TAG_CHECKS = ["release proof", "publish"];
50
+ export const RELEASE_TAG_CHECKS = ["release proof", "package / binary · darwin-arm64", "package / binary · darwin-x64", "package / binary · linux-x64", "package / binary · linux-arm64", "package / assemble", "publish"];
41
51
  export const RELEASE_TAG_WORKFLOW = ".github/workflows/publish.yml";
42
52
  export const RELEASE_STEPS = ["gate", "approval", "check", "complete", "quiet", "deploy", "link", "ci", "merge", "tree", "tag", "publish", "homebrew", "done"];
43
53
  export const RELEASE_LIMITS = { gate: 60, approval: 24 * 60, check: 360, quiet: 60, deploy: 30, ci: 60, publish: 45, homebrew: 45 };
@@ -1,5 +1,6 @@
1
1
  import { verifyResultImage } from "./chat-evidence.js";
2
2
  import { createHash, randomBytes } from "node:crypto";
3
+ import { markTypedByPerson } from "./store.js";
3
4
  import { EVIDENCE_CAPS, readVerifiedArtifact, writeEvidenceFile } from "./evidence.js";
4
5
  import { parseFeedbackImage, sameFeedbackImage, isRevisionFeedback, parseRevisionBatch, revisionSourceOf, commentSourceKey, REQUEST_TOKEN } from "./result-review.js";
5
6
  import { validateNote, hasForbiddenControls } from "./decision.js";
@@ -68,6 +69,8 @@ export function requestResultChanges(store, evidenceRoot, input, now) {
68
69
  const noteId = earlier?.id ?? store.addDiffComment({ artifactId: artifact.id, runId: run.id, path, line, note: valid.note, author: input.actor, sourceKey, image: input.image ?? null }, now);
69
70
  if (noteId === null)
70
71
  return fail(409, "This feedback changed while saving. Your draft is unchanged; reopen the result.");
72
+ if (earlier === null)
73
+ markTypedByPerson(store, { comment: noteId }, input.actor, input.typedWords, now);
71
74
  const result = createResultRevision(store, evidenceRoot, { ...input, batch: [...new Set([...batch, noteId])].sort((a, b) => a - b).join(",") }, now);
72
75
  if (!result.ok)
73
76
  return fail(result.status, result.message);
@@ -1,5 +1,5 @@
1
1
  import { readVerifiedArtifact } from "./evidence.js";
2
- import { hasForbiddenControls } from "./decision.js";
2
+ import { HANDOFF_REPORT_CAP, hasDisguisedText, hasForbiddenControls } from "./decision.js";
3
3
  import { parseHandoffArtifact } from "./contracts/handoff.js";
4
4
  const CAPTURE_EXIT = /\(exit ([0-9]{1,4})\)\s*$/;
5
5
  export const SCREENSHOT_CAPTURE = /^agent-claimed screenshot at (.+) \(validated (?:png|jpeg)\)/;
@@ -25,7 +25,13 @@ export function structuredHandoffView(artifacts, root, displayText = text => tex
25
25
  .filter(one => one.trim() !== "" && !hasForbiddenControls(one))
26
26
  .slice(0, 8)
27
27
  .map(one => oneLineOf(one, 240));
28
- return { conclusion, changes: list(handoff.changes), verification: list(handoff.verification), followUps: list(handoff.followUps) };
28
+ const reported = (items) => (items ?? [])
29
+ .filter(one => one.trim() !== "" && !hasDisguisedText(one))
30
+ .slice(0, HANDOFF_REPORT_CAP)
31
+ .map(one => oneLineOf(displayText(one), 240))
32
+ .filter(one => one !== "" && !hasDisguisedText(one));
33
+ return { conclusion, changes: list(handoff.changes), verification: list(handoff.verification), followUps: list(handoff.followUps),
34
+ report: { decisions: reported(handoff.decisions), assumptions: reported(handoff.assumptions), notDone: reported(handoff.notDone), risks: reported(handoff.risks) } };
29
35
  }
30
36
  export function terminalDiffView(artifacts, root) {
31
37
  const patchArtifact = artifacts.find(one => one.kind === "terminal-diff");
@@ -145,8 +145,8 @@ export function resultReturnTarget(raw, runId, tasks = []) {
145
145
  return raw;
146
146
  if (tasks.some(task => raw === `/t/${encodeURIComponent(task)}`))
147
147
  return raw;
148
- const tab = /^\/t\/([A-Za-z0-9._~%-]{1,200})\?(?:version=[A-Za-z0-9._~%-]{1,200}&)?tab=result&run=([0-9]{1,15})(?:&section=(?:summary|changes|checks))?$/.exec(raw);
149
- if (tab !== null && Number(tab[2]) === runId && tasks.some(task => tab[1] === encodeURIComponent(task)))
148
+ const tab = /^\/t\/([A-Za-z0-9._~%-]{1,200})\?(?:version=[A-Za-z0-9._~%-]{1,200}&)?tab=result(?:&run=([0-9]{1,15}))?(?:&section=(?:summary|changes|checks))?$/.exec(raw);
149
+ if (tab !== null && (tab[2] === undefined || Number(tab[2]) === runId) && tasks.some(task => tab[1] === encodeURIComponent(task)))
150
150
  return raw;
151
151
  }
152
152
  return `/r/${runId}`;
@@ -236,6 +236,15 @@ export const RESULT_REVIEW_SCRIPT = String.raw `
236
236
  if(form){
237
237
  var noteBox=form.querySelector('[name=note]'),pathBox=form.querySelector('[name=path]'),lineBox=form.querySelector('[name=line]'),pin=form.querySelector('details.result-pin');
238
238
  var imageBox=form.querySelector('[name=image]'),imagePreview=form.querySelector('[data-feedback-image]');
239
+ // What the page fills in for the person (a reviewer's note to act on, a requirement marked Not right) is its own
240
+ // field, shown as sent with the note and never written into the person's own box: only what they type is theirs.
241
+ var contextBox=form.querySelector('[name=context]'),contextLine=form.querySelector('[data-request-context-line]');
242
+ // One item per line; each is shown, as text, in a list under "Sent with it".
243
+ function setContext(text){if(!contextBox)return;contextBox.value=text;if(contextLine){contextLine.textContent='';var items=text.split('\n').filter(function(one){return one.trim()!=='';});
244
+ if(items.length>0){contextLine.appendChild(document.createTextNode('Sent with it:'));var list=document.createElement('ul');items.forEach(function(one){var li=document.createElement('li');li.textContent=one;list.appendChild(li);});contextLine.appendChild(list);}
245
+ contextLine.hidden=items.length===0;}}
246
+ // A further item joins what is already there (the same one again changes nothing): earlier feedback is never lost.
247
+ function addContext(item){if(!contextBox||!item.trim())return;var items=contextBox.value.split('\n').filter(function(one){return one.trim()!=='';});if(items.indexOf(item)<0)items.push(item);setContext(items.join('\n'));}
239
248
  function showImage(){
240
249
  if(!imageBox||!imagePreview)return;
241
250
  imagePreview.hidden=!imageBox.value;
@@ -253,7 +262,7 @@ export const RESULT_REVIEW_SCRIPT = String.raw `
253
262
  });
254
263
  var limit=document.getElementById('comment-note-limit'),requestBox=form.querySelector('[name=request]');
255
264
  function updateActions(){
256
- var typed=!!(noteBox&&noteBox.value.trim()),batch=form.querySelector('[name=batch]');
265
+ var typed=!!(noteBox&&noteBox.value.trim())||!!(contextBox&&contextBox.value.trim()),batch=form.querySelector('[name=batch]');
257
266
  var requestAction=form.querySelector('[data-request-changes]'),saveAction=form.querySelector('[data-save-feedback]');
258
267
  if(requestAction)requestAction.disabled=!typed&&!(batch&&batch.value);
259
268
  if(saveAction)saveAction.disabled=!typed;
@@ -266,8 +275,7 @@ export const RESULT_REVIEW_SCRIPT = String.raw `
266
275
  document.addEventListener('click',function(ev){
267
276
  var button=ev.target&&ev.target.closest?ev.target.closest('button.pick-file,button.pick-line'):null;if(!button)return;
268
277
  var reviewNote=button.getAttribute('data-review-note');
269
- if(reviewNote!==null&&noteBox&&noteBox.value&&!window.confirm('Replace the feedback draft with this note?'))return;
270
- if(reviewNote!==null&&noteBox)noteBox.value=reviewNote;
278
+ if(reviewNote!==null){var at=button.getAttribute('data-path');addContext(reviewNote.replace(/\s+/g,' ')+(at?' ('+at+(button.getAttribute('data-line')?':'+button.getAttribute('data-line'):'')+')':''));}
271
279
  if(pathBox)pathBox.value=button.getAttribute('data-path')||'';
272
280
  if(lineBox)lineBox.value=button.getAttribute('data-line')||'';
273
281
  if(pin)pin.open=true;
@@ -285,7 +293,8 @@ export const RESULT_REVIEW_SCRIPT = String.raw `
285
293
  // A fresh request identity: 16 random bytes as hex, the server's own shape.
286
294
  function mint(){var bytes=new Uint8Array(16);try{crypto.getRandomValues(bytes);}catch(e){for(var i=0;i<16;i++)bytes[i]=Math.floor(Math.random()*256);}
287
295
  var hex='';for(var j=0;j<16;j++)hex+=(bytes[j]<16?'0':'')+bytes[j].toString(16);return hex;}
288
- function payload(){return JSON.stringify([noteBox?noteBox.value:'',pathBox?pathBox.value:'',lineBox?lineBox.value:'',imageBox?imageBox.value:'']);}
296
+ // The filled-in field joins the identity only when it holds something, so a draft sent before it existed keeps its own.
297
+ function payload(){var parts=[noteBox?noteBox.value:'',pathBox?pathBox.value:'',lineBox?lineBox.value:'',imageBox?imageBox.value:''];if(contextBox&&contextBox.value)parts.push(contextBox.value);return JSON.stringify(parts);}
289
298
  // What the current token was last submitted with; null = never sent.
290
299
  var sent=null,bound=null;
291
300
  // The server refused this token for a different note or another result:
@@ -308,8 +317,9 @@ export const RESULT_REVIEW_SCRIPT = String.raw `
308
317
  if(typeof saved.request==='string'&&/^[a-f0-9]{32}$/.test(saved.request)&&requestBox)requestBox.value=saved.request;
309
318
  if(typeof saved.sent==='string')sent=saved.sent;
310
319
  if(imageBox&&typeof saved.image==='string'&&saved.image.length<250)imageBox.value=saved.image;
320
+ if(contextBox&&!contextBox.value&&typeof saved.context==='string'&&saved.context.length<=4000)setContext(saved.context);
311
321
  showImage();
312
- bound=JSON.stringify([saved.note,saved.path||'',saved.line||'',saved.image||'']);
322
+ bound=JSON.stringify([saved.note,saved.path||'',saved.line||'',saved.image||''].concat(saved.context?[saved.context]:[]));
313
323
  if(noteBox)noteBox.dispatchEvent(new Event('input'));
314
324
  }
315
325
  function save(){
@@ -319,8 +329,9 @@ export const RESULT_REVIEW_SCRIPT = String.raw `
319
329
  var current=payload();
320
330
  if((bound!==null&&current!==bound)||(sent!==null&&current!==sent)){sent=null;if(requestBox)requestBox.value=mint();}
321
331
  bound=current;
322
- if(!note&&!path&&!line&&!(imageBox&&imageBox.value)){write(draftKey,null);return;}
323
- write(draftKey,{note:note,path:path,line:line,image:imageBox?imageBox.value:'',request:requestBox?requestBox.value:'',sent:sent,at:Date.now()});
332
+ var context=contextBox?contextBox.value:'';
333
+ if(!note&&!path&&!line&&!context&&!(imageBox&&imageBox.value)){write(draftKey,null);return;}
334
+ write(draftKey,{note:note,path:path,line:line,image:imageBox?imageBox.value:'',context:context,request:requestBox?requestBox.value:'',sent:sent,at:Date.now()});
324
335
  if(!storage&&limit)limit.textContent='Draft stays on this page only. Browser storage is unavailable.';
325
336
  }
326
337
  form.addEventListener('input',save);