@omacode/micromanager 0.1.1 → 1.0.0

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 (213) hide show
  1. package/README.md +7 -4
  2. package/THIRD_PARTY.md +100 -0
  3. package/decider/.python-version +1 -0
  4. package/decider/README.md +35 -0
  5. package/decider/decider/__init__.py +1 -0
  6. package/decider/decider/server.py +327 -0
  7. package/decider/pyproject.toml +34 -0
  8. package/decider/uv.lock +1255 -0
  9. package/dist/agenda.js +51 -0
  10. package/dist/agents.js +58 -0
  11. package/dist/artifact/handoff.js +281 -0
  12. package/dist/ask.js +200 -0
  13. package/dist/backends.js +219 -0
  14. package/dist/backlog.js +414 -0
  15. package/dist/bench.js +427 -0
  16. package/dist/board.js +1 -0
  17. package/dist/brief.js +202 -0
  18. package/dist/browser.js +679 -0
  19. package/dist/budget.js +61 -0
  20. package/dist/catalog.js +187 -0
  21. package/dist/checkchange.js +145 -0
  22. package/dist/checkpoint.js +94 -0
  23. package/dist/cli.js +764 -0
  24. package/dist/comfy-gate.js +258 -0
  25. package/dist/compact.js +142 -0
  26. package/dist/config.js +344 -0
  27. package/dist/context/capture.js +1 -0
  28. package/dist/context/digest.js +1 -0
  29. package/dist/context/embed.js +1 -0
  30. package/dist/context/index.js +2 -0
  31. package/dist/context/ledger.js +1 -0
  32. package/dist/context/manager.js +1 -0
  33. package/dist/context/memory.js +1 -0
  34. package/dist/context/policy.js +1 -0
  35. package/dist/context/prices.js +1 -0
  36. package/dist/context/recall.js +1 -0
  37. package/dist/context/rules.js +1 -0
  38. package/dist/context/search.js +1 -0
  39. package/dist/context/status.js +1 -0
  40. package/dist/context/store.js +1 -0
  41. package/dist/context/summary.js +1 -0
  42. package/dist/context/tokens.js +1 -0
  43. package/dist/context/tools.js +1 -0
  44. package/dist/continuation.js +184 -0
  45. package/dist/contract.js +294 -0
  46. package/dist/contractround.js +178 -0
  47. package/dist/control.js +1 -0
  48. package/dist/creative-tools.js +237 -0
  49. package/dist/dataset.js +175 -0
  50. package/dist/decide.js +676 -0
  51. package/dist/decider.js +171 -0
  52. package/dist/design-shell.js +448 -0
  53. package/dist/design.js +1410 -0
  54. package/dist/desktop.js +44 -0
  55. package/dist/egress.js +156 -0
  56. package/dist/eval.js +60 -0
  57. package/dist/evolver.js +302 -0
  58. package/dist/features.js +193 -0
  59. package/dist/followups.js +32 -0
  60. package/dist/forms.js +195 -0
  61. package/dist/gate.js +108 -0
  62. package/dist/gatebox.js +46 -0
  63. package/dist/grants.js +189 -0
  64. package/dist/graph.js +65 -0
  65. package/dist/guard/index.js +1 -0
  66. package/dist/guard/wire.js +1 -0
  67. package/dist/helpers.js +85 -0
  68. package/dist/hooks.js +158 -0
  69. package/dist/image-models.js +117 -0
  70. package/{src/integration.ts → dist/integration.js} +1 -2
  71. package/dist/journal.js +1 -0
  72. package/dist/look.js +363 -0
  73. package/dist/memory.js +1 -0
  74. package/dist/mode.js +97 -0
  75. package/dist/native.js +3348 -0
  76. package/dist/nogit.js +259 -0
  77. package/dist/outcomes.js +148 -0
  78. package/dist/permission.js +35 -0
  79. package/dist/pick.js +89 -0
  80. package/dist/pipelines.js +262 -0
  81. package/dist/plan.js +641 -0
  82. package/dist/plandoc.js +211 -0
  83. package/dist/plugin.js +4736 -0
  84. package/dist/policy.js +58 -0
  85. package/dist/pools.js +1 -0
  86. package/dist/preview.js +274 -0
  87. package/dist/profile.js +165 -0
  88. package/dist/progress.js +1 -0
  89. package/dist/promote.js +313 -0
  90. package/dist/redact.js +1 -0
  91. package/dist/registry.js +179 -0
  92. package/dist/riskscore.js +126 -0
  93. package/dist/roles.js +1 -0
  94. package/dist/routing.js +1 -0
  95. package/dist/runner.js +1892 -0
  96. package/{src/sandbox.ts → dist/sandbox.js} +1 -2
  97. package/dist/sandboxgate.js +90 -0
  98. package/dist/scheduler.js +170 -0
  99. package/dist/services-main.js +131 -0
  100. package/dist/services.js +265 -0
  101. package/dist/session.js +241 -0
  102. package/dist/setup.js +423 -0
  103. package/dist/shell/decide.js +1 -0
  104. package/dist/shell/index.js +2 -0
  105. package/dist/shell/sandbox.js +1 -0
  106. package/dist/shell/wire.js +1 -0
  107. package/dist/skills.js +103 -0
  108. package/dist/state.js +1 -0
  109. package/dist/store.js +1 -0
  110. package/dist/switcher.js +1 -0
  111. package/dist/synth.js +418 -0
  112. package/dist/tools.js +477 -0
  113. package/dist/trials.js +223 -0
  114. package/dist/usage.js +1 -0
  115. package/dist/wait.js +167 -0
  116. package/dist/watchdog.js +476 -0
  117. package/dist/web-guidance.js +43 -0
  118. package/dist/which.js +20 -0
  119. package/dist/worktree/git.js +545 -0
  120. package/dist/writeguard.js +311 -0
  121. package/package.json +36 -17
  122. package/skills/deck/SKILL.md +98 -0
  123. package/skills/design/SKILL.md +150 -0
  124. package/skills/image/SKILL.md +66 -0
  125. package/skills/orchestrator/SKILL.md +107 -0
  126. package/skills/video/SKILL.md +97 -0
  127. package/skills/web/SKILL.md +60 -0
  128. package/src/agenda.ts +0 -56
  129. package/src/agents.ts +0 -74
  130. package/src/ask.ts +0 -243
  131. package/src/backends.ts +0 -144
  132. package/src/backlog.ts +0 -436
  133. package/src/bench.ts +0 -163
  134. package/src/board.ts +0 -1
  135. package/src/brief.ts +0 -151
  136. package/src/browser.ts +0 -624
  137. package/src/budget.ts +0 -73
  138. package/src/catalog.ts +0 -214
  139. package/src/checkchange.ts +0 -180
  140. package/src/checkpoint.ts +0 -99
  141. package/src/cli.ts +0 -117
  142. package/src/compact.ts +0 -162
  143. package/src/config.ts +0 -340
  144. package/src/context/capture.ts +0 -1
  145. package/src/context/digest.ts +0 -1
  146. package/src/context/embed.ts +0 -1
  147. package/src/context/index.ts +0 -2
  148. package/src/context/ledger.ts +0 -1
  149. package/src/context/manager.ts +0 -1
  150. package/src/context/memory.ts +0 -1
  151. package/src/context/policy.ts +0 -1
  152. package/src/context/prices.ts +0 -1
  153. package/src/context/recall.ts +0 -1
  154. package/src/context/rules.ts +0 -1
  155. package/src/context/search.ts +0 -1
  156. package/src/context/status.ts +0 -1
  157. package/src/context/store.ts +0 -1
  158. package/src/context/summary.ts +0 -1
  159. package/src/context/tokens.ts +0 -1
  160. package/src/context/tools.ts +0 -1
  161. package/src/continuation.ts +0 -122
  162. package/src/contract.ts +0 -342
  163. package/src/contractround.ts +0 -225
  164. package/src/control.ts +0 -1
  165. package/src/dataset.ts +0 -133
  166. package/src/decide.ts +0 -690
  167. package/src/eval.ts +0 -66
  168. package/src/evolver.ts +0 -369
  169. package/src/followups.ts +0 -50
  170. package/src/forms.ts +0 -191
  171. package/src/gate.ts +0 -90
  172. package/src/grants.ts +0 -239
  173. package/src/graph.ts +0 -74
  174. package/src/guard/index.ts +0 -1
  175. package/src/guard/wire.ts +0 -1
  176. package/src/helpers.ts +0 -105
  177. package/src/hooks.ts +0 -199
  178. package/src/jev.ts +0 -141
  179. package/src/journal.ts +0 -1
  180. package/src/look.ts +0 -390
  181. package/src/memory.ts +0 -1
  182. package/src/native.ts +0 -2455
  183. package/src/nogit.ts +0 -112
  184. package/src/outcomes.ts +0 -210
  185. package/src/pick.ts +0 -112
  186. package/src/pipelines.ts +0 -252
  187. package/src/plan.ts +0 -449
  188. package/src/plugin.ts +0 -3187
  189. package/src/policy.ts +0 -84
  190. package/src/pools.ts +0 -1
  191. package/src/profile.ts +0 -186
  192. package/src/progress.ts +0 -1
  193. package/src/redact.ts +0 -1
  194. package/src/registry.ts +0 -207
  195. package/src/roles.ts +0 -1
  196. package/src/routing.ts +0 -1
  197. package/src/runner.ts +0 -1506
  198. package/src/scheduler.ts +0 -200
  199. package/src/session.ts +0 -269
  200. package/src/shell/decide.ts +0 -1
  201. package/src/shell/index.ts +0 -2
  202. package/src/shell/sandbox.ts +0 -1
  203. package/src/shell/wire.ts +0 -1
  204. package/src/skills.ts +0 -111
  205. package/src/state.ts +0 -1
  206. package/src/store.ts +0 -1
  207. package/src/switcher.ts +0 -1
  208. package/src/tools.ts +0 -480
  209. package/src/trials.ts +0 -247
  210. package/src/usage.ts +0 -1
  211. package/src/wait.ts +0 -180
  212. package/src/watchdog.ts +0 -498
  213. package/src/worktree/git.ts +0 -378
package/dist/policy.js ADDED
@@ -0,0 +1,58 @@
1
+ // Who makes a decision: the decision model, the user, a preset or the rules (design.md §22).
2
+ //
3
+ // A policy is set per decision key ("N6.pipeline", "G0.locality", …) or per node ("N6" covers all its keys), on
4
+ // five levels; the most specific level wins. Guards and hard rules are never switched off by a config-level
5
+ // preset: only a single decision may override a guard, explicitly.
6
+ export const LEVELS = ["decision", "task", "job", "project", "global"];
7
+ // Guard nodes: a preset above the single decision is ignored for them.
8
+ const GUARDED = new Set(["G0", "G"]);
9
+ export function parsePolicy(text) {
10
+ const t = text.trim();
11
+ if (t === "auto" || t === "ask" || t === "rule")
12
+ return { kind: t };
13
+ if (t.startsWith("fixed:") && t.length > "fixed:".length)
14
+ return { kind: "fixed", value: t.slice("fixed:".length) };
15
+ return undefined;
16
+ }
17
+ export function resolvePolicy(key, policies) {
18
+ const node = key.split(".")[0] ?? key;
19
+ const guarded = GUARDED.has(node);
20
+ for (const level of LEVELS) {
21
+ if (guarded && level !== "decision")
22
+ continue;
23
+ const set = policies[level];
24
+ if (!set)
25
+ continue;
26
+ for (const candidate of [key, node]) {
27
+ const raw = set[candidate];
28
+ if (raw === undefined)
29
+ continue;
30
+ const policy = parsePolicy(raw);
31
+ if (policy)
32
+ return { policy, level, key: candidate };
33
+ }
34
+ }
35
+ return { policy: { kind: "auto" } };
36
+ }
37
+ export function validatePolicies(set) {
38
+ return Object.entries(set).flatMap(([key, value]) => typeof value === "string" && parsePolicy(value) && /^[A-Z][A-Za-z0-9]*(\.[a-z_]+)?$/.test(key)
39
+ ? []
40
+ : [`decisions.${key}: expected a key like "N6.pipeline" and "auto", "ask", "rule" or "fixed:<value>"`]);
41
+ }
42
+ const SHORTCUTS = [
43
+ { re: /^(always|only) local$/i, pin: () => ({ level: "job", key: "G0.locality", value: "fixed:local" }) },
44
+ { re: /^no planning session$/i, pin: () => ({ level: "job", key: "N2.clarity", value: "fixed:clear" }) },
45
+ { re: /^pipeline (P\d)$/i, pin: (m) => ({ level: "job", key: "N6.pipeline", value: `fixed:${m[1].toUpperCase()}` }) },
46
+ { re: /^ask me (about|before) everything$/i, pin: () => ({ level: "job", key: "N5", value: "ask" }) },
47
+ { re: /^([A-Za-z][\w.-]*) use ([\w./:-]+)$/, pin: (m) => ({ level: "task", taskId: m[1], key: "N5.model", value: `fixed:${m[2]}` }) },
48
+ { re: /^skip review for ([A-Za-z][\w.-]*)$/i, pin: (m) => ({ level: "task", taskId: m[1], key: "N6.review", value: "fixed:skip" }) },
49
+ ];
50
+ export function matchShortcut(text) {
51
+ const t = text.trim().replace(/[.!]+$/, "");
52
+ for (const s of SHORTCUTS) {
53
+ const m = t.match(s.re);
54
+ if (m)
55
+ return s.pin(m);
56
+ }
57
+ return undefined;
58
+ }
package/dist/pools.js ADDED
@@ -0,0 +1 @@
1
+ export * from "@omacode/tui/pools";
@@ -0,0 +1,274 @@
1
+ // The preview of a cloud send, and the one question it asks (D13, A2-T6). Nothing leaves the machine until the user has
2
+ // seen the text and said "send"; "keep it local" and "cancel" leave no request at all.
3
+ //
4
+ // The plugin cannot open a form itself (src/forms.ts: its context has no form domain), so a preview waits the way a
5
+ // grant waits: the request is opened here, its id is the form's header, and the micromanager session puts the form to
6
+ // the user with the question tool. The answer comes back through tool.execute.after, which settles the promise the
7
+ // cloud call is waiting on. Without an answer it is kept local after the timeout — never sent.
8
+ //
9
+ // This file only shapes the question and the note; src/plugin.ts owns the session that puts it.
10
+ import { formInput } from "./forms.js";
11
+ // Two minutes: long enough for the user who is at the screen, short enough that a worker's permission request is not
12
+ // held hostage. A cloud call that times out is kept local and says so in the journal.
13
+ export const PREVIEW_TIMEOUT_MS = 2 * 60_000;
14
+ const SEND = "Send it";
15
+ const LOCAL = "Keep it local";
16
+ const CANCEL = "Cancel";
17
+ // The previews waiting for an answer. One per id; a second ask of the same node in the same text waits on the first
18
+ // form rather than putting a second one.
19
+ export class PreviewRequests {
20
+ #pending = new Map();
21
+ #journal;
22
+ #timeoutMs;
23
+ #n = 0;
24
+ constructor(journal = () => { }, timeoutMs = PREVIEW_TIMEOUT_MS) {
25
+ this.#journal = journal;
26
+ this.#timeoutMs = timeoutMs;
27
+ }
28
+ open(request) {
29
+ const same = [...this.#pending.values()].find((p) => p.destination === request.destination && p.text === request.text);
30
+ if (same)
31
+ return { pending: strip(same), answer: same.answer, fresh: false };
32
+ const id = `S${++this.#n}`;
33
+ let settle;
34
+ const answer = new Promise((resolve) => (settle = resolve));
35
+ const waiting = { ...request, id, at: Date.now(), answer, settle };
36
+ waiting.timer = setTimeout(() => {
37
+ if (!this.#pending.delete(id))
38
+ return;
39
+ this.#journal({ kind: "egress", event: "timeout", id, node: request.node, destination: request.destination, session: request.session });
40
+ settle("keep-local");
41
+ }, this.#timeoutMs);
42
+ waiting.timer.unref?.();
43
+ this.#pending.set(id, waiting);
44
+ this.#journal({ kind: "egress", event: "asked", id, node: request.node, destination: request.destination, session: request.session, job: request.job, words: request.words, unredactable: request.unredactable, replaced: request.replaced });
45
+ return { pending: strip(waiting), answer, fresh: true };
46
+ }
47
+ get(id) {
48
+ const p = this.#pending.get(id);
49
+ return p && strip(p);
50
+ }
51
+ // The user's answer. Returns the preview it settled, or undefined when none waits under this id any more.
52
+ answer(id, choice) {
53
+ const p = this.#take(id);
54
+ if (!p)
55
+ return undefined;
56
+ this.#journal({ kind: "egress", event: "answered", id, node: p.node, destination: p.destination, session: p.session, job: p.job, answer: choice, waitedMs: Date.now() - p.at });
57
+ p.settle(choice);
58
+ return strip(p);
59
+ }
60
+ // The previews of sessions that ended: kept local quietly, nobody waits for them any more.
61
+ drop(sessionIDs) {
62
+ const dropped = [...this.#pending.values()].filter((p) => p.session !== undefined && sessionIDs.includes(p.session));
63
+ for (const p of dropped) {
64
+ this.#take(p.id);
65
+ this.#journal({ kind: "egress", event: "dropped", id: p.id, node: p.node, destination: p.destination, session: p.session, job: p.job });
66
+ p.settle("keep-local");
67
+ }
68
+ return dropped.map(strip);
69
+ }
70
+ #take(id) {
71
+ const p = this.#pending.get(id);
72
+ if (!p)
73
+ return undefined;
74
+ this.#pending.delete(id);
75
+ clearTimeout(p.timer);
76
+ return p;
77
+ }
78
+ }
79
+ function strip(p) {
80
+ const { settle: _s, timer: _t, answer: _a, ...shown } = p;
81
+ return shown;
82
+ }
83
+ // The header a form is recognised by: "Send S1" (src/plugin.ts reads the answer by it, as it does for grants).
84
+ export const previewHeader = (id) => `Send ${id}`;
85
+ const SHOWN = 1200;
86
+ // The form: the host, what the redaction changed, whether the payload is one nobody can vouch for, and the first
87
+ // characters of the exact text that would leave. Enough to recognise the payload, never the whole of it.
88
+ export function previewForm(p) {
89
+ const what = p.replaced.length ? `Redacted: ${p.replaced.join(", ")}.` : "Nothing in it matched a detector.";
90
+ const sure = p.unredactable
91
+ ? `It is not one that can be vouched for: ${p.why ?? "the redaction left it unchanged"}.`
92
+ : p.names
93
+ ? "Names and addresses are replaced by the local detector; e-mail, keys, paths and addresses by the redaction."
94
+ : "No local name detector is on, so this payload is uncertain: read the text before you send it.";
95
+ const tail = p.text.length > SHOWN ? `${p.text.slice(0, SHOWN)}\n… (${p.text.length - SHOWN} more characters)` : p.text;
96
+ return [{
97
+ header: previewHeader(p.id),
98
+ question: `${p.node ?? "A decision"} would send ${p.words} word${p.words === 1 ? "" : "s"} to ${p.destination}${p.job ? ` for job ${p.job}` : ""}. ` +
99
+ `${what} ${sure}\n\n${tail}\n\nSend it?`,
100
+ options: [
101
+ { label: SEND, description: `This payload leaves the machine, as shown, once` },
102
+ { label: LOCAL, description: "Nothing is sent; the decision is answered on this machine or by you" },
103
+ { label: CANCEL, description: "Nothing is sent, and this decision is not asked again for this call" },
104
+ ],
105
+ }];
106
+ }
107
+ // The note that wakes the micromanager: the form to put to the user, exactly as it is.
108
+ export function previewNote(p, timeoutMs = PREVIEW_TIMEOUT_MS) {
109
+ return `[micromanager] ${p.id}: a cloud decision waits for the user's word. ${p.node ?? "a decision"} would send ${p.words} words to ${p.destination}${p.job ? ` for job ${p.job}` : ""}. Only the user may let a payload leave this machine: ask them with the question tool, with exactly this input (a form; their answer reaches the plugin by itself), then end your turn:\n${formInput(previewForm(p))}\nWithout an answer it is kept local in ${Math.round(timeoutMs / 60_000)} minutes and the decision is made without the cloud.`;
110
+ }
111
+ // What the user's answer means. A short yes or no they typed themselves is taken the same way; anything else is no
112
+ // answer, and the preview keeps waiting.
113
+ export function previewAnswer(labels) {
114
+ for (const label of labels) {
115
+ const said = label.trim().toLowerCase().replace(/\s*\(recommended\)\s*$/, "").replace(/\s+/g, " ");
116
+ if (said === SEND.toLowerCase() || ["send", "yes", "ja", "send it"].includes(said))
117
+ return "send";
118
+ if (said === LOCAL.toLowerCase() || ["keep local", "keep it local", "local", "no", "nein"].includes(said))
119
+ return "keep-local";
120
+ if (said === CANCEL.toLowerCase() || ["stop", "abort", "cancel it"].includes(said))
121
+ return "cancel";
122
+ }
123
+ return undefined;
124
+ }
125
+ // --- the per-session cloud opt-in (A2-T5) ------------------------------------------------------------------------
126
+ // The opt-in is a value of a session, not of a job and not of the machine. It is asked once, through the same channel
127
+ // as the preview (the session's micromanager puts the form), and it is remembered for the session until it expires or
128
+ // the job it was given for changes; then the session's first cloud ask asks again. A "keep it local" answer is
129
+ // remembered just the same, so the user is not asked before every decision.
130
+ //
131
+ // The guards are a second answer: a session may let ordinary decisions go to the cloud and still keep injection
132
+ // and sensitive on this machine, which is the default and the only thing a plain opt-in allows.
133
+ // A working day. Long enough not to nag within one, short enough that yesterday's yes is asked again.
134
+ export const OPT_IN_TTL_MS = 12 * 60 * 60_000;
135
+ const CLOUD = "Cloud for this session";
136
+ const GUARDS = "Cloud and guards";
137
+ const KEEP = "Keep it local";
138
+ // The answers and the forms that wait for one. It does not wake anyone itself: the plugin gives it a channel through
139
+ // the session's micromanager (src/plugin.ts), so this file stays testable without a host.
140
+ export class CloudOptIn {
141
+ #decided = new Map();
142
+ #pending = new Map();
143
+ #journal;
144
+ #timeoutMs;
145
+ #ttlMs;
146
+ #n = 0;
147
+ constructor(journal = () => { }, timeoutMs = PREVIEW_TIMEOUT_MS, ttlMs = OPT_IN_TTL_MS) {
148
+ this.#journal = journal;
149
+ this.#timeoutMs = timeoutMs;
150
+ this.#ttlMs = ttlMs;
151
+ }
152
+ // What this session already decided, and whether that answer still stands. The job is compared only when the ask
153
+ // names one: an opt-in given without a job is not thrown away by an ask that has one, it is re-confirmed once.
154
+ state(session, job, now = Date.now()) {
155
+ const rec = this.#decided.get(session);
156
+ if (!rec)
157
+ return { allow: false, guards: false, need: "none", why: "this session has not opted in to the cloud" };
158
+ if (now - rec.at >= this.#ttlMs)
159
+ return { allow: false, guards: false, need: "stale", why: "the session's cloud opt-in expired" };
160
+ if (job !== undefined && rec.job !== job)
161
+ return { allow: false, guards: false, need: "job", why: "the session opted in for another job" };
162
+ return {
163
+ allow: rec.answer !== "local",
164
+ guards: rec.answer === "guards",
165
+ need: rec.answer === "local" ? "local" : "ok",
166
+ why: rec.answer === "local" ? "the user kept this session local" : "the session opted in",
167
+ };
168
+ }
169
+ // Remember an answer for the session. It replaces an earlier one, and the guard override with it: the override
170
+ // cannot outlive the answer that carried it.
171
+ remember(session, job, answer, at = Date.now()) {
172
+ this.#decided.set(session, { ...(job !== undefined ? { job } : {}), at, answer });
173
+ this.#journal({ kind: "cloud-opt-in", event: "decided", session, job, answer });
174
+ return this.state(session, job, at);
175
+ }
176
+ // One form per session and job: a second ask while the first waits is answered by the same form.
177
+ open(session, job) {
178
+ const same = [...this.#pending.values()].find((p) => p.session === session && p.job === job);
179
+ if (same)
180
+ return { pending: stripOptIn(same), answer: same.answer, fresh: false };
181
+ const id = `O${++this.#n}`;
182
+ let settle;
183
+ const answer = new Promise((resolve) => (settle = resolve));
184
+ const waiting = { id, session, ...(job !== undefined ? { job } : {}), at: Date.now(), answer, settle };
185
+ waiting.timer = setTimeout(() => {
186
+ if (!this.#pending.delete(id))
187
+ return;
188
+ this.#journal({ kind: "cloud-opt-in", event: "timeout", id, session, job });
189
+ // No answer is a no, remembered like one: the session is not asked before every decision, and nothing leaves.
190
+ this.remember(session, job, "local");
191
+ settle("local");
192
+ }, this.#timeoutMs);
193
+ waiting.timer.unref?.();
194
+ this.#pending.set(id, waiting);
195
+ this.#journal({ kind: "cloud-opt-in", event: "asked", id, session, job });
196
+ return { pending: stripOptIn(waiting), answer, fresh: true };
197
+ }
198
+ get(id) {
199
+ const p = this.#pending.get(id);
200
+ return p && stripOptIn(p);
201
+ }
202
+ // The user's answer. Returns the request it settled, or undefined when none waits under this id any more.
203
+ answer(id, choice) {
204
+ const p = this.#take(id);
205
+ if (!p)
206
+ return undefined;
207
+ this.#journal({ kind: "cloud-opt-in", event: "answered", id, session: p.session, job: p.job, answer: choice, waitedMs: Date.now() - p.at });
208
+ // The answer is remembered per session, whatever it was: "keep it local" too, so the user is not asked before every
209
+ // decision. The guard override lives in the same record, so it can never outlive the answer that carried it.
210
+ this.remember(p.session, p.job, choice);
211
+ p.settle(choice);
212
+ return stripOptIn(p);
213
+ }
214
+ // The sessions that ended: their forms are dropped, and their answers with them. An opt-in cannot outlive its
215
+ // session, and neither can a guard override.
216
+ drop(sessions) {
217
+ const dropped = [...this.#pending.values()].filter((p) => sessions.includes(p.session));
218
+ for (const p of dropped) {
219
+ this.#take(p.id);
220
+ this.#journal({ kind: "cloud-opt-in", event: "dropped", id: p.id, session: p.session, job: p.job });
221
+ p.settle("local");
222
+ }
223
+ for (const session of sessions) {
224
+ if (this.#decided.delete(session))
225
+ this.#journal({ kind: "cloud-opt-in", event: "forgotten", session });
226
+ }
227
+ return dropped.map(stripOptIn);
228
+ }
229
+ #take(id) {
230
+ const p = this.#pending.get(id);
231
+ if (!p)
232
+ return undefined;
233
+ this.#pending.delete(id);
234
+ clearTimeout(p.timer);
235
+ return p;
236
+ }
237
+ }
238
+ function stripOptIn(p) {
239
+ const { settle: _s, timer: _t, answer: _a, ...shown } = p;
240
+ return shown;
241
+ }
242
+ // The header a form is recognised by: "Cloud O1" (src/plugin.ts reads the answer by it, as it does for grants).
243
+ export const optInHeader = (id) => `Cloud ${id}`;
244
+ // The form: the three answers, with what each one means for this session. No payload is shown here — that is the
245
+ // preview, after the opt-in and per call.
246
+ export function optInForm(p) {
247
+ return [{
248
+ header: optInHeader(p.id),
249
+ question: `May decisions in this session go to the cloud decision client${p.job ? ` for job ${p.job}` : ""}? ` +
250
+ "Each send is still redacted and shown to you before it leaves. The answer holds for this session only.",
251
+ options: [
252
+ { label: CLOUD, description: "Ordinary decisions may reach the cloud, after a redacted preview you confirm; the guards stay on this machine" },
253
+ { label: GUARDS, description: "The same, and the guard questions (injection, sensitive) may go too — for this session only; a payload carrying the sensitive flag is never sent by this" },
254
+ { label: KEEP, description: "Nothing leaves this machine in this session; every decision is answered locally or by you" },
255
+ ],
256
+ }];
257
+ }
258
+ // The note that wakes the micromanager for a session that has not opted in.
259
+ export function optInNote(p, timeoutMs = PREVIEW_TIMEOUT_MS) {
260
+ return `[micromanager] ${p.id}: the decision client asks whether this session may use the cloud${p.job ? ` (job ${p.job})` : ""}. Only the user may say so, once per session: ask them with the question tool, with exactly this input (a form; their answer reaches the plugin by itself), then end your turn:\n${formInput(optInForm(p))}\nWithout an answer everything stays on this machine in ${Math.round(timeoutMs / 60_000)} minutes, and the decision is made locally.`;
261
+ }
262
+ // What the user's answer means. As with the preview, a short yes or no they typed themselves counts.
263
+ export function optInAnswer(labels) {
264
+ for (const label of labels) {
265
+ const said = label.trim().toLowerCase().replace(/\s*\(recommended\)\s*$/, "").replace(/\s+/g, " ");
266
+ if (said === GUARDS.toLowerCase() || ["cloud and guards", "guards too", "cloud, guards too"].includes(said))
267
+ return "guards";
268
+ if (said === CLOUD.toLowerCase() || ["cloud", "cloud for this session", "yes", "ja", "allow cloud"].includes(said))
269
+ return "cloud";
270
+ if (said === KEEP.toLowerCase() || ["keep it local", "keep local", "local", "no", "nein"].includes(said))
271
+ return "local";
272
+ }
273
+ return undefined;
274
+ }
@@ -0,0 +1,165 @@
1
+ // N5 + N5b: one decision request per task classifies it and sets its profile (design.md §8.1). Code combines the
2
+ // isolated answers: the role matrix is the upper bound, a profile only narrows it, and a contradiction is cut
3
+ // back to the matrix at the cost of confidence.
4
+ import { CHOICE_FLOOR, CLASSIFY, NOUL_FLOOR, roleChoice, RISKS, skillQuestion } from "./catalog.js";
5
+ import { recallQuestions, recalled } from "./memory.js";
6
+ import { resolvePolicy } from "./policy.js";
7
+ import { ROLES, TEST_RUNNERS, WRITER_ROLES, roleById } from "./roles.js";
8
+ // Profiles deny tool groups, never single tools: in Phase A a worker without read read the file through grep.
9
+ export const TOOL_GROUPS = {
10
+ shell: ["shell"],
11
+ web: ["webfetch", "websearch"],
12
+ };
13
+ // What a role is for: these groups are never narrowed away from it.
14
+ const ROLE_NEEDS = { test: ["shell"], review: ["shell"], research: ["web"] };
15
+ // Roles that change files (state/roles.ts WRITER_ROLES, which the memory's rules use too).
16
+ export const WRITERS = WRITER_ROLES;
17
+ // The questions for one task: the fixed set, the role choice, and one noul per skill the planner's role may load.
18
+ export function classifyQuestions(task, skills, memory = []) {
19
+ const roles = Object.fromEntries(ROLES.map((r) => [r.id, r.description]));
20
+ const allowed = skills.filter((s) => s.roles.includes(task.role));
21
+ return {
22
+ role: roleChoice(roles),
23
+ ...CLASSIFY,
24
+ ...Object.fromEntries(allowed.map((s) => [`skill.${s.name}`, skillQuestion(s.name, s.description)])),
25
+ ...recallQuestions(memory),
26
+ };
27
+ }
28
+ // The task alone, not the job (Phase D: a new function in a job that also fixed a bug was classified as a bug fix).
29
+ // Probe on that case: is_bug_fix 0.91 with the goal, 0.84 with it as background, 0.08 without it, while the bug fix
30
+ // task itself stays at 0.94. The planner writes each task's description for a worker that knows nothing else.
31
+ export function classifyState(_goal, task, acceptance) {
32
+ return {
33
+ task: { id: task.id, title: task.title, description: task.description, files: task.files, plannerRole: task.role },
34
+ acceptance: acceptance.map((a) => `${a.text}${a.verify ? ` (checked with: ${a.verify})` : ""}`),
35
+ };
36
+ }
37
+ // A role can use an action unless it denies it outright with no exception. For the shell of a role that only reads,
38
+ // what counts is whether it may run the tests: every reader may run reading commands (git log, ls, grep), and a task
39
+ // that needs the shell needs it to run something (review allows the test runners, oracle does not).
40
+ const canUse = (role, action) => {
41
+ if (action === "shell" && !WRITERS.has(role.id))
42
+ return TEST_RUNNERS.some((cmd) => role.rules.some((r) => r.action === "shell" && r.resource === cmd && r.effect === "allow"));
43
+ return (!role.rules.some((r) => r.action === action && r.resource === "*" && r.effect === "deny") ||
44
+ role.rules.some((r) => r.action === action && r.resource !== "*" && r.effect !== "deny"));
45
+ };
46
+ // The first role in the same write class that may use the group, for a task whose role cannot do what it needs.
47
+ function roleThatCan(group, writer) {
48
+ const order = writer ? ["code", "test", "debug", "visual"] : ["review", "research", "explore"];
49
+ return order.map((id) => roleById(id)).find((r) => TOOL_GROUPS[group].every((a) => canUse(r, a)));
50
+ }
51
+ const MAX_SKILLS = 3;
52
+ export function combine(task, acceptance, asked, policies, skills = [], memory = []) {
53
+ const a = asked?.decision.answers ?? {};
54
+ const noul = (q) => (a[q]?.type === "noul" ? a[q].noul : undefined);
55
+ const yes = (q) => (noul(q) ?? 0) >= NOUL_FLOOR;
56
+ const choice = (q) => (a[q]?.type === "choice" ? a[q] : undefined);
57
+ const fixed = (key) => {
58
+ const p = resolvePolicy(`N5.${key}`, policies).policy;
59
+ return p.kind === "fixed" ? p.value : undefined;
60
+ };
61
+ let confidence = 1;
62
+ const take = (q, allowed, fallback) => {
63
+ const c = choice(q);
64
+ if (!c || c.confidence < CHOICE_FLOOR || !allowed.includes(c.choice))
65
+ return fallback;
66
+ confidence = Math.min(confidence, c.confidence);
67
+ return c.choice;
68
+ };
69
+ // Role: the planner's, unless the model is sure of another in the same write class, or the user pinned one.
70
+ const writer = task.files.length > 0;
71
+ let role = task.role;
72
+ let roleReason = "the planner's role";
73
+ const pinnedRole = fixed("role");
74
+ const modelRole = choice("role");
75
+ if (pinnedRole && roleById(pinnedRole))
76
+ [role, roleReason] = [pinnedRole, "preset"];
77
+ else if (modelRole && modelRole.choice !== role && modelRole.confidence >= CHOICE_FLOOR && WRITERS.has(modelRole.choice) === writer) {
78
+ ;
79
+ [role, roleReason] = [modelRole.choice, `the decision model (${modelRole.confidence.toFixed(2)}) over the planner's ${task.role}`];
80
+ confidence = Math.min(confidence, modelRole.confidence);
81
+ }
82
+ // A task that needs a group its role denies gets a role that has it (live test: "run the tests" went to oracle,
83
+ // which has no shell, and the worker could only read). Without a model answer, a verify command means shell.
84
+ const tools = { shell: noul("tool.shell"), web: noul("tool.web") };
85
+ let penalty = 1; // each contradiction cut back to the matrix
86
+ const needsShell = tools.shell !== undefined ? tools.shell >= NOUL_FLOOR : !writer && acceptance.some((x) => x.verify) && /\b(run|test|build|lint)/i.test(`${task.title} ${task.description}`);
87
+ for (const [group, needed] of [["shell", needsShell], ["web", tools.web !== undefined && tools.web >= NOUL_FLOOR]]) {
88
+ const current = roleById(role);
89
+ if (!needed || TOOL_GROUPS[group].every((x) => canUse(current, x)))
90
+ continue;
91
+ const other = pinnedRole ? undefined : roleThatCan(group, writer);
92
+ if (other)
93
+ [role, roleReason] = [other.id, `${current.id} has no ${group}, the task needs it`];
94
+ penalty *= 0.8;
95
+ }
96
+ const score = a.difficulty?.type === "score" ? a.difficulty.score : undefined;
97
+ const pinnedDifficulty = Number(fixed("difficulty"));
98
+ const difficulty = Number.isFinite(pinnedDifficulty) && fixed("difficulty") !== undefined ? Math.max(0, Math.min(1, pinnedDifficulty)) : score !== undefined ? Math.max(0, Math.min(4, score)) / 4 : 0.5;
99
+ const risk = fixed("risk") ?? take("risk", Object.keys(RISKS), "internal");
100
+ const perm = fixed("perm_profile") ?? take("perm_profile", ["strict", "normal", "trusted"], "strict");
101
+ const budget = fixed("budget_tier") ?? take("budget_tier", ["S", "M", "L"], "M");
102
+ const picked = skills
103
+ .filter((s) => s.roles.includes(role))
104
+ .map((s) => ({ name: s.name, p: noul(`skill.${s.name}`) ?? 0 }))
105
+ .filter((s) => s.p >= NOUL_FLOOR)
106
+ .sort((x, y) => y.p - x.p)
107
+ .slice(0, MAX_SKILLS)
108
+ .map((s) => s.name);
109
+ return {
110
+ role,
111
+ roleReason,
112
+ difficulty,
113
+ risk,
114
+ testOracle: noul("has_test_oracle") !== undefined ? yes("has_test_oracle") : acceptance.some((x) => x.verify),
115
+ testFirst: yes("test_first_possible"),
116
+ bugFix: yes("is_bug_fix"),
117
+ approachUncertain: yes("approach_uncertain"),
118
+ bugUnknownCause: yes("bug_unknown_cause"),
119
+ vision: yes("needs_vision"),
120
+ tools,
121
+ skills: picked,
122
+ perm,
123
+ budget,
124
+ injection: yes("injection"),
125
+ confidence: confidence * penalty,
126
+ source: asked && Object.keys(a).length > 0 ? "model" : "rules",
127
+ decision: asked?.id,
128
+ recall: recalled(memory, a, NOUL_FLOOR),
129
+ };
130
+ }
131
+ // The worker session's own permission rules (Phase A, A5): groups the task does not need are denied, by how strict
132
+ // the profile is. They are appended to the role's rules, so they can only take rights away.
133
+ export function narrowing(profile) {
134
+ if (profile.perm === "trusted")
135
+ return [];
136
+ const below = profile.perm === "strict" ? NOUL_FLOOR : 0.2;
137
+ const keep = new Set(ROLE_NEEDS[profile.role] ?? []);
138
+ const out = [];
139
+ for (const group of Object.keys(TOOL_GROUPS)) {
140
+ const p = profile.tools[group];
141
+ if (p === undefined || p >= below || keep.has(group))
142
+ continue;
143
+ for (const action of TOOL_GROUPS[group])
144
+ out.push({ action, resource: "*", effect: "deny" });
145
+ }
146
+ return out;
147
+ }
148
+ // One line for the plan, the journal and the user.
149
+ export function profileText(p) {
150
+ const groups = Object.keys(p.tools).filter((g) => p.tools[g] !== undefined).map((g) => `${g} ${p.tools[g].toFixed(2)}`);
151
+ return [
152
+ `role ${p.role}${p.roleReason === "the planner's role" ? "" : ` (${p.roleReason})`}`,
153
+ `difficulty ${p.difficulty.toFixed(2)}`,
154
+ `risk ${p.risk}`,
155
+ p.testOracle ? "test oracle" : "no test oracle",
156
+ p.testFirst ? "test first possible" : undefined,
157
+ p.bugFix ? "bug fix" : undefined,
158
+ p.approachUncertain ? "approach uncertain" : undefined,
159
+ p.vision ? "needs vision" : undefined,
160
+ `${p.perm} rights${groups.length ? ` (${groups.join(", ")})` : ""}`,
161
+ `budget ${p.budget}`,
162
+ p.skills.length ? `skills ${p.skills.join(", ")}` : undefined,
163
+ p.source === "rules" ? "rules only" : undefined,
164
+ ].filter(Boolean).join(" · ");
165
+ }
@@ -0,0 +1 @@
1
+ export * from "@omacode/tui/progress";