create-pmos 0.817.0 → 0.819.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.
@@ -0,0 +1,75 @@
1
+ 'use strict';
2
+ /* pick-cli.js — `pmos pick --minutes <n>`: the one ask that fits the time you have and unblocks the most (initiative time-box-pick-chat,
3
+ * job #1873, idea A293; lib/time-box-pick.js).
4
+ *
5
+ * pmos pick --minutes 30 [--ws <id>] [--json]
6
+ * pmos pick --minutes 30 --root <dir> [--json]
7
+ *
8
+ * With a workspace server running it asks the server (GET /api/find with "I have N minutes", the same answer Ctrl K shows, waiting
9
+ * sessions included). With none it reads the repository and the runtime folder itself. It calls no model, sends nothing and changes no
10
+ * record; the only write is one line in the local use log. Exit codes: 0 done (nothing to pick is done), 1 the asks could not be read,
11
+ * 2 usage. */
12
+ const fs = require('fs');
13
+ const path = require('path');
14
+ const TB = require('./time-box-pick.js');
15
+ const { parseArgs } = require('./schedule-cli');
16
+
17
+ const COMMANDS = { pick: [] };
18
+ const USAGE = [
19
+ 'usage: pmos pick --minutes <n> [--ws <id>] [--json]',
20
+ ' pmos pick --minutes <n> --root <dir> [--json]',
21
+ 'Picks the one ask from Your move and Waiting on others that fits in <n> minutes and unblocks the most others, with why in one line.',
22
+ 'It calls no model, sends nothing and changes nothing.',
23
+ ];
24
+ const BOOL = new Set(['json', 'help']);
25
+ const VALUE = new Set(['minutes', 'ws', 'root']);
26
+
27
+ /** The repository this directory is in: the nearest folder up with a .git (no git process), else the directory itself. */
28
+ function repoRoot(cwd) {
29
+ let d = path.resolve(cwd);
30
+ for (;;) { try { if (fs.existsSync(path.join(d, '.git'))) return d; } catch { /* unreadable: look further up */ } const up = path.dirname(d); if (up === d) return path.resolve(cwd); d = up; }
31
+ }
32
+
33
+ async function run(argv, { say, call = async () => null, runtimeDir } = {}) {
34
+ const rest = [], bools = {};
35
+ for (const a of argv.slice(1)) {
36
+ if (a.startsWith('--') && BOOL.has(a.slice(2))) bools[a.slice(2)] = true;
37
+ else if (a === '-h' || a === 'help') bools.help = true;
38
+ else rest.push(a);
39
+ }
40
+ const { pos, flags } = parseArgs(rest);
41
+ const f = { ...flags, ...bools };
42
+ if (f.help) { USAGE.forEach((l) => say(l)); return 0; }
43
+ const bad = Object.keys(f).find((k) => !BOOL.has(k) && !VALUE.has(k));
44
+ if (bad || pos.length) { say(`✗ ${bad ? '--' + bad : pos[0]} is not an option of pmos pick`); USAGE.forEach((l) => say(l)); return 2; }
45
+ const mins = TB.minutesOf(String(f.minutes || '').trim() + (/^\d+(?:\.\d+)?$/.test(String(f.minutes || '').trim()) ? ' min' : ''));
46
+ if (!mins) { say('✗ say how long you have: --minutes 30'); USAGE.forEach((l) => say(l)); return 2; }
47
+ if (f.ws && f.root) { say('✗ --ws and --root name two different things: use one'); return 2; }
48
+ const root = path.resolve(f.root ? f.root : repoRoot(process.cwd()));
49
+ let p = null;
50
+ if (!f.root) {
51
+ let ws = f.ws || null;
52
+ if (!ws) {
53
+ const list = await call('GET', '/api/workspaces');
54
+ const mine = list && Array.isArray(list.workspaces) ? list.workspaces.find((x) => x && x.root && path.resolve(x.root) === root) : null;
55
+ ws = mine ? mine.id : null;
56
+ }
57
+ const r = ws ? await call('GET', '/api/find?q=' + encodeURIComponent('I have ' + mins + ' minutes') + '&ws=' + encodeURIComponent(ws)) : null;
58
+ if (f.ws && !(r && r.ok)) { say(`✗ the workspace ${f.ws} could not be reached: no workspace server answered. Start it, or give --root <dir>.`); return 1; }
59
+ if (r && r.ok && r.answer) p = { line: r.answer.text, pick: r.answer.pick || null, minutes: mins, via: 'server' };
60
+ }
61
+ if (!p) {
62
+ let rt = runtimeDir;
63
+ if (rt === undefined) { try { rt = require('./state-root.js').defaultRoot({ env: process.env }); } catch { rt = null; } }
64
+ let t = null;
65
+ try { t = TB.read({ w: { id: 'local', root }, runtimeDir: rt, minutes: mins }); } catch (e) { say('✗ the asks could not be read: ' + ((e && e.message) || e)); return 1; }
66
+ TB.logUse(rt, 'cli');
67
+ const c = t.pick || t.shortest;
68
+ p = { line: t.line, pick: c ? { key: c.key, kind: c.kind, minutes: c.minutes, unblocks: c.unblocks, ini: c.ini || null } : null, minutes: mins, fits: t.fits, via: 'local' };
69
+ }
70
+ if (f.json) say(JSON.stringify({ ok: true, ...p }));
71
+ else { say(p.line); if (p.pick && p.pick.ini) say(' open: ' + p.pick.ini); }
72
+ return 0;
73
+ }
74
+
75
+ module.exports = { run, COMMANDS, USAGE };
@@ -29,6 +29,9 @@ const VERBS = Object.freeze({
29
29
  help: 'pmos measure … — record a measured value of a KR or a health budget, with its source (pmos measure help)' }),
30
30
  today: Object.freeze({ module: 'today-cli.js', run: 3, guide: 'cli.md',
31
31
  help: 'pmos today — what needs you, ranked as Today shows it' }),
32
+ // Not a pm-os-absorb verb (run: null): time-box-pick-chat (idea A293) added it through the same table.
33
+ pick: Object.freeze({ module: 'pick-cli.js', run: null, guide: 'cli.md',
34
+ help: 'pmos pick --minutes <n> — for "I have 30 minutes": the one ask that fits the time and unblocks the most' }),
32
35
  board: Object.freeze({ module: 'board-cli.js', run: 4, guide: 'cli.md',
33
36
  help: 'pmos board [--mine] [--init <id>] — the items of every initiative, by column' }),
34
37
  'verify-work': Object.freeze({ module: 'verify-work-cli.js', run: 4, guide: 'cli.md',
@@ -9,6 +9,7 @@
9
9
  * pmos report definitions [--json] the report definitions (read-only)
10
10
  * pmos report setups [--json] the recurring reports (read-only)
11
11
  * pmos report finder <weekly|off> the PM's: how often PMOS looks for reports you send (also: finder source <name> <on|off>)
12
+ * pmos report language <cadence> "<Language>[ for <reader>]" [--off] who reads it in another language (lib/report-translate.js; agent-allowed)
12
13
  *
13
14
  * `draft` is the script with no model (R22.1): lib/report-draft.js folds the ledgers since the last issue and writes
14
15
  * every number into `<state>/reports/<cadence>/<slot>.md`, with one empty note marker per block. It refuses a slot that
@@ -37,7 +38,7 @@ const actorLib = require('./actor.js');
37
38
  const RS = require('./report-setups.js');
38
39
  const { parseArgs } = require('./schedule-cli');
39
40
 
40
- const COMMANDS = { report: ['make', 'read', 'find', 'write', 'check', 'rule', 'draft', 'issue', 'list', 'propose', 'definitions', 'setups', 'finder', 'library'] };
41
+ const COMMANDS = { report: ['make', 'read', 'find', 'write', 'check', 'rule', 'draft', 'issue', 'list', 'propose', 'definitions', 'setups', 'finder', 'library', 'language'] };
41
42
  const USAGE = [
42
43
  'usage: pmos report make|read|find|write|check|rule — the report engine: brief, read, find, answer, render (any report, any shape)',
43
44
  ' pmos report make <id> [--ask "<the question>"] [--readers "<who>"] [--source <kind:ref>,…] [--template <id>] [--slot <date>]',
@@ -74,12 +75,15 @@ const USAGE = [
74
75
  ' Show the recurring reports (read-only).',
75
76
  ' pmos report finder <weekly|off> | pmos report finder source <calendar|slack|mail|drive> <on|off>',
76
77
  ' Only the PM can change how PMOS looks for the reports you send (default weekly; mail is off until you turn it on).',
78
+ ' pmos report language <cadence> "<Language>[ for <reader>]" [--off]',
79
+ ' A reader who reads the report in another language. After each draft PMOS writes a translated copy beside it',
80
+ ' (<slot>.<code>.md) with every number and name unchanged; --off stops it. Nothing is sent. With no language: the list.',
77
81
  ' every command: [--json] [--root <dir>]. The cadence is the report skill id without "report-", for example biweekly.',
78
82
  ];
79
- const BOOL = new Set(['json', 'redraft', 'help']);
83
+ const BOOL = new Set(['json', 'redraft', 'help', 'off']);
80
84
  const VALUE = new Set(['now', 'root', 'ask', 'readers', 'source', 'slot', 'from', 'out', 'template']);
81
85
  const ALLOWED = { make: ['json', 'now', 'root', 'ask', 'readers', 'source', 'slot', 'template'], read: ['json', 'now', 'root', 'slot', 'from', 'source'], find: ['json', 'now', 'root', 'slot', 'from'],
82
- write: ['json', 'now', 'root', 'slot', 'from'], check: ['json', 'root', 'slot'], rule: ['json', 'root'], draft: ['json', 'redraft', 'now', 'root'], issue: ['root'], list: ['json', 'root'], propose: ['json', 'root'], definitions: ['json', 'root'], setups: ['json', 'root'], finder: ['json', 'root'], library: ['json', 'out', 'template'] };
86
+ write: ['json', 'now', 'root', 'slot', 'from'], check: ['json', 'root', 'slot'], rule: ['json', 'root'], draft: ['json', 'redraft', 'now', 'root'], issue: ['root'], list: ['json', 'root'], propose: ['json', 'root'], definitions: ['json', 'root'], setups: ['json', 'root'], finder: ['json', 'root'], language: ['json', 'root', 'off'], library: ['json', 'out', 'template'] };
83
87
  const CADENCE_RE = /^[a-z][a-z0-9-]{0,39}$/;
84
88
  const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
85
89
 
@@ -166,7 +170,7 @@ async function run(argv, { say = (s) => console.log(s), cwd = process.cwd(), isT
166
170
  return 0;
167
171
  }
168
172
  if (['make', 'read', 'find', 'write', 'check', 'rule'].includes(verb)) return engineVerb(verb, { pos, flags, root, json, say, fail, isTTY, env, stdin, now });
169
- if (verb === 'definitions' || verb === 'setups' || verb === 'propose' || verb === 'finder') return reportWorkspace(verb, { pos, flags, root, json, say, fail, cwd, isTTY, env, stdin, now });
173
+ if (verb === 'definitions' || verb === 'setups' || verb === 'propose' || verb === 'finder' || verb === 'language') return reportWorkspace(verb, { pos, flags, root, json, say, fail, cwd, isTTY, env, stdin, now });
170
174
 
171
175
  const [cadence, slot] = pos;
172
176
  if (!cadence || !CADENCE_RE.test(cadence) || pos.length > 2) { say(`usage: pmos report ${verb} <cadence> ${verb === 'issue' ? '<slot>' : '[<slot>]'}`); return 2; }
@@ -312,6 +316,22 @@ async function engineVerb(verb, { pos, flags, root, json, say, fail, isTTY, env,
312
316
  function reportWorkspace(verb, { pos, flags, root, json, say, fail, isTTY, env, stdin, now }) {
313
317
  const E = env === undefined ? process.env : env;
314
318
  const stamp = now == null ? undefined : now;
319
+ if (verb === 'language') {
320
+ const RT = require('./report-translate.js');
321
+ const cadence = pos[0], entry = pos.slice(1).join(' ').trim();
322
+ if (!cadence || !CADENCE_RE.test(cadence)) { say('usage: pmos report language <cadence> "<Language>[ for <reader>]" [--off]'); return 2; }
323
+ if (!entry) {
324
+ const list = RT.definitionLanguages(root, cadence);
325
+ if (json) { say(JSON.stringify({ ok: true, cadence, languages: list })); return 0; }
326
+ say(list.length ? list.map((x) => `${x.language}${x.reader ? ' for ' + x.reader : ''}`).join('\n') : `The ${cadence} report is read in one language.`);
327
+ return 0;
328
+ }
329
+ const r = RT.setLanguage(root, cadence, entry, { off: !!flags.off });
330
+ if (!r.ok) return fail(r.error);
331
+ if (json) { say(JSON.stringify(r)); return 0; }
332
+ say(`✓ ${r.path}: ${r.languages.length ? 'also in ' + r.languages.map((x) => `${x.language}${x.reader ? ' for ' + x.reader : ''}`).join(', ') : 'one language only'}. The next draft writes the copies; nothing is sent.`);
333
+ return 0;
334
+ }
315
335
  if (verb === 'definitions') {
316
336
  const defs = RS.definitionsOf(root);
317
337
  if (json) { say(JSON.stringify({ ok: true, definitions: defs })); return 0; }
@@ -0,0 +1,238 @@
1
+ 'use strict';
2
+ /* report-translate.js — a report in each reader's language (initiative report-reader-language, idea A111).
3
+ *
4
+ * WHY. A PM whose readers read different languages writes the report once and translates it by hand, or sends it in a language
5
+ * some readers read slowly. A hand translation is where a number or a name goes wrong. PMOS acts by itself: no run button.
6
+ *
7
+ * WHO READS WHAT. A report's definition (<state>/reports/definitions/<cadence>.md) may carry `languages: "Indonesian for Dita; Japanese"`:
8
+ * one language per reader, the reader optional. `pmos report language <cadence> "<Language>[ for <reader>]" [--off]` adds or removes one
9
+ * entry (the PM at a terminal, or the chat's agent). A language not in LANGS is skipped.
10
+ *
11
+ * WHEN IT RUNS. After every report draft this process writes (lib/report-draft.js onDraftWritten: Draft now, Redraft, a schedule), one
12
+ * read-only run per language through the design critic's ask path (lib/design-critic.js askVia: the normal `claude -p` session, kind ask).
13
+ * The draft's text is in the prompt. A copy whose `source_sha` is the draft's text already starts no run. Off: the AI switch for job
14
+ * `report-translate` (`pmos ai off report-translate`, or every AI job off), or the design critic's switch.
15
+ *
16
+ * WHAT IT WRITES. <state>/reports/<cadence>/<slot>.<code>.md beside the draft: the draft's frontmatter plus `translation_of`, `language`,
17
+ * `reader` and `source_sha`, then one line saying it is a translation, for whom, and that numbers and names are unchanged, then the
18
+ * translated body. The copy is written ONLY when keeps() finds every number and every name of the original in it: numbers are runs of
19
+ * digits with their decimals (counted), names are initiative ids, note markers, links, and acronyms or codes (two capitals, or a capital
20
+ * and a digit). Otherwise nothing is written and the server log says why. A copy is not a cycle: the report list reads <slot>.md only.
21
+ * Nothing is sent anywhere.
22
+ *
23
+ * LANGS · languagesOf(value) PURE → [{ language, code, reader }]
24
+ * bodyOf(text) PURE → { fm, body } · shaOf(body) PURE
25
+ * namesOf(body) PURE → { numbers: Map<string, count>, names: Set<string> } · keeps(orig, copy) PURE → { ok, why? }
26
+ * promptOf({ body, language, reader }) PURE · answerOf(answer) PURE → markdown | null
27
+ * copyPath(rel, code) PURE · copyText({ fm, body, rel, language, code, reader, sha }) PURE → the file
28
+ * alsoOf(root, rel) → [{ code, language, reader, path }] the copies on disk beside a draft (the ⋯ menu's Also in …)
29
+ * definitionLanguages(root, cadence) → [{ language, code, reader }] · setLanguage(root, cadence, entry, { off }) → { ok, languages, path } | { ok:false, error }
30
+ * translate({ root, rel, ask, runtime?, env?, guard? }) → Promise<{ written, refused, skipped, off? }>
31
+ * attach(ctxFactory) hook onDraftWritten once; ctx: { workspaceList, runtimeDir, spawnScheduled|spawnSession }
32
+ */
33
+ const fs = require('fs');
34
+ const path = require('path');
35
+ const crypto = require('crypto');
36
+
37
+ const JOB = 'report-translate';
38
+ const ORIGIN = 'briefing-ask:report-translate:';
39
+ const MAX_CHARS = 60000;
40
+ const LANGS = Object.freeze({
41
+ en: 'English', id: 'Indonesian', ms: 'Malay', zh: 'Chinese', ja: 'Japanese', ko: 'Korean', th: 'Thai', vi: 'Vietnamese', tl: 'Filipino',
42
+ hi: 'Hindi', ta: 'Tamil', ar: 'Arabic', es: 'Spanish', fr: 'French', de: 'German', pt: 'Portuguese', it: 'Italian', nl: 'Dutch',
43
+ });
44
+ const ALIASES = Object.freeze({ 'bahasa indonesia': 'id', bahasa: 'id', 'bahasa melayu': 'ms', mandarin: 'zh', tagalog: 'tl' });
45
+ const one = (v, n) => String(v == null ? '' : v).replace(/\s+/g, ' ').trim().slice(0, n);
46
+ const shaOf = (s) => crypto.createHash('sha1').update(String(s)).digest('hex').slice(0, 16);
47
+
48
+ /** PURE. One language name or code → its code, or null. */
49
+ function codeOf(word) {
50
+ const w = String(word || '').trim().toLowerCase();
51
+ if (!w) return null;
52
+ if (LANGS[w]) return w;
53
+ if (ALIASES[w]) return ALIASES[w];
54
+ const hit = Object.entries(LANGS).find(([, n]) => n.toLowerCase() === w);
55
+ return hit ? hit[0] : null;
56
+ }
57
+
58
+ /** PURE. `"Indonesian for Dita; Japanese"`, or a list → [{ language, code, reader }], one per code (the first reader wins). */
59
+ function languagesOf(value) {
60
+ const parts = (Array.isArray(value) ? value : String(value == null ? '' : value).split(/[;,]/)).map((x) => String(x).trim()).filter(Boolean);
61
+ const out = [];
62
+ for (const p of parts) {
63
+ const m = /^(.+?)(?:\s+for\s+(.+))?$/i.exec(p);
64
+ const code = m && codeOf(m[1]);
65
+ if (!code || code === 'en' || out.some((x) => x.code === code)) continue;
66
+ out.push({ language: LANGS[code], code, reader: m[2] ? one(m[2], 60) : '' });
67
+ }
68
+ return out;
69
+ }
70
+ const entryOf = (x) => x.language + (x.reader ? ' for ' + x.reader : '');
71
+
72
+ /** PURE. A file's frontmatter block (with its fences) and its body. */
73
+ function bodyOf(text) {
74
+ const t = String(text == null ? '' : text);
75
+ const m = /^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/.exec(t);
76
+ return m ? { fm: m[0], body: t.slice(m[0].length) } : { fm: '', body: t };
77
+ }
78
+ function fmMap(fm) {
79
+ const map = {};
80
+ for (const l of String(fm || '').split(/\r?\n/)) { const kv = /^([A-Za-z_][\w-]*):\s*(.*?)\s*$/.exec(l); if (kv) map[kv[1]] = kv[2].replace(/^["']|["']$/g, ''); }
81
+ return map;
82
+ }
83
+
84
+ /** PURE. What a translation must keep: numbers (counted) and names. */
85
+ function namesOf(body) {
86
+ const t = String(body || '');
87
+ const numbers = new Map();
88
+ for (const m of t.matchAll(/\d+(?:[.,]\d+)*/g)) {
89
+ const k = m[0].replace(/,/g, '.');
90
+ numbers.set(k, (numbers.get(k) || 0) + 1);
91
+ }
92
+ const names = new Set();
93
+ for (const m of t.matchAll(/<!--\s*\/?pmos:[^>]*-->/g)) names.add(m[0].replace(/\s+/g, ' '));
94
+ for (const m of t.matchAll(/^#{2,4}\s+.*\(([A-Za-z0-9._-]{1,80})\)\s*$/gm)) names.add('(' + m[1] + ')');
95
+ for (const m of t.matchAll(/\]\(([^)\s]+)\)/g)) names.add('](' + m[1] + ')');
96
+ for (const m of t.matchAll(/https?:\/\/[^\s)>\]]+/g)) names.add(m[0]);
97
+ for (const m of t.matchAll(/\b(?:[A-Z][A-Za-z0-9-]*[A-Z0-9][A-Za-z0-9-]*)\b/g)) if (/[A-Z].*[A-Z0-9]/.test(m[0]) && !/^\d/.test(m[0])) names.add(m[0]);
98
+ return { numbers, names };
99
+ }
100
+
101
+ /** PURE. Does the copy keep every number and every name of the original? */
102
+ function keeps(orig, copy) {
103
+ const a = namesOf(orig), b = namesOf(copy);
104
+ for (const [n, c] of a.numbers) if ((b.numbers.get(n) || 0) < c) return { ok: false, why: `the number ${n} is not in the copy as often as in the original` };
105
+ const flat = String(copy || '').replace(/\s+/g, ' ');
106
+ for (const n of a.names) if (!flat.includes(n)) return { ok: false, why: `the name ${n} is not in the copy` };
107
+ return { ok: true };
108
+ }
109
+
110
+ /** PURE. The run's prompt. */
111
+ function promptOf({ body, language, reader = '' } = {}) {
112
+ return [
113
+ `Translate this report into ${language}${reader ? ` for ${reader}` : ''}. Do not run any tool and do not read any file: the report is below.`,
114
+ 'Translate the words only. Keep every number, date digit, percentage, initiative id in brackets, person and product name, acronym, link and',
115
+ 'Markdown mark exactly as it is. Keep every line that starts with <!-- exactly as it is. Keep the same headings, lists and table rows, in the same order.',
116
+ 'Answer with the translated report in one fenced block that starts with ```markdown and nothing else.',
117
+ '', '```markdown', String(body || '').slice(0, MAX_CHARS), '```',
118
+ ].join('\n');
119
+ }
120
+
121
+ /** PURE. The translated body from the answer, or null. */
122
+ function answerOf(answer) {
123
+ const t = String(answer == null ? '' : answer);
124
+ const m = /```(?:markdown|md)?[^\n]*\n([\s\S]*?)\n```\s*$/i.exec(t.trim()) || /```(?:markdown|md)[^\n]*\n([\s\S]*?)\n```/i.exec(t);
125
+ const out = m ? m[1] : '';
126
+ return out.trim() ? out.replace(/\s+$/, '') + '\n' : null;
127
+ }
128
+
129
+ /** PURE. reports/<cadence>/<slot>.md → reports/<cadence>/<slot>.<code>.md */
130
+ const copyPath = (rel, code) => String(rel).replace(/\.md$/, '') + '.' + code + '.md';
131
+
132
+ /** PURE. The copy's file. */
133
+ function copyText({ fm = '', body = '', rel = '', language = '', code = '', reader = '', sha = '' } = {}) {
134
+ const q = (v) => `"${String(v).replace(/["\\]/g, "'")}"`;
135
+ const extra = [`translation_of: ${q(rel)}`, `language: ${code}`, ...(reader ? [`reader: ${q(reader)}`] : []), `source_sha: ${sha}`];
136
+ const head = fm
137
+ ? fm.replace(/\r?\n---(\r?\n|$)$/, '\n' + extra.join('\n') + '\n---\n').replace(/^(title:\s*)(["']?)(.*?)\2\s*$/m, (all, k, qt, v) => `${k}${q(v + ' (' + language + ')')}`)
138
+ : ['---', 'type: Reference', `title: ${q(path.basename(rel) + ' (' + language + ')')}`, ...extra, '---', ''].join('\n');
139
+ const note = `> Translation of ${path.basename(rel)} into ${language}${reader ? ' for ' + reader : ''}. PMOS checked that numbers and names are unchanged from the original.`;
140
+ return head + '\n' + note + '\n\n' + String(body).replace(/^\s+/, '');
141
+ }
142
+
143
+ function stateRelOf(rel) { const m = /^(.*)\/reports\/([a-z][a-z0-9-]{0,39})\/(\d{4}-\d{2}-\d{2})\.md$/.exec(String(rel)); return m ? { state: m[1], cadence: m[2], slot: m[3] } : null; }
144
+ function defFile(root, state, cadence) { return path.join(path.resolve(String(root)), state, 'reports', 'definitions', cadence + '.md'); }
145
+
146
+ /** The languages a report's definition names. */
147
+ function definitionLanguages(root, cadence, state = null) {
148
+ let st = state;
149
+ if (!st) { try { st = require('./report-draft.js').stateRel(root); } catch { return []; } }
150
+ let t = ''; try { t = fs.readFileSync(defFile(root, st, cadence), 'utf8'); } catch { return []; }
151
+ return languagesOf(fmMap(bodyOf(t).fm).languages || '');
152
+ }
153
+
154
+ /** Add or remove one `<Language>[ for <reader>]` entry on a definition's `languages:` line. */
155
+ function setLanguage(root, cadence, entry, { off = false, state = null } = {}) {
156
+ if (!/^[a-z][a-z0-9-]{0,39}$/.test(String(cadence || ''))) return { ok: false, error: 'the cadence is a report id, for example weekly' };
157
+ const want = languagesOf(entry || '');
158
+ if (!want.length) return { ok: false, error: `${JSON.stringify(String(entry || ''))} names no language PMOS knows (${Object.values(LANGS).filter((n) => n !== 'English').join(', ')})` };
159
+ let st = state;
160
+ if (!st) { try { st = require('./report-draft.js').stateRel(root); } catch (e) { return { ok: false, error: String((e && e.message) || e).slice(0, 160) }; } }
161
+ const file = defFile(root, st, cadence);
162
+ let t; try { t = fs.readFileSync(file, 'utf8'); } catch { return { ok: false, error: `the report ${cadence} has no definition (${path.relative(path.resolve(String(root)), file)}); set the report up first` }; }
163
+ const { fm, body } = bodyOf(t);
164
+ if (!fm) return { ok: false, error: 'the definition has no frontmatter' };
165
+ const cur = languagesOf(fmMap(fm).languages || '');
166
+ const next = off ? cur.filter((x) => !want.some((w) => w.code === x.code)) : [...cur.filter((x) => !want.some((w) => w.code === x.code)), ...want];
167
+ const line = next.length ? `languages: "${next.map(entryOf).join('; ').replace(/["\\]/g, "'")}"` : '';
168
+ let head = /^languages:.*$/m.test(fm) ? fm.replace(/^languages:.*\r?\n?/m, line ? line + '\n' : '') : (line ? fm.replace(/\r?\n---(\r?\n|$)$/, '\n' + line + '\n---\n') : fm);
169
+ fs.writeFileSync(file, head + body);
170
+ return { ok: true, languages: next, path: path.relative(path.resolve(String(root)), file).split(path.sep).join('/') };
171
+ }
172
+
173
+ /** The translated copies on disk beside a draft. */
174
+ function alsoOf(root, rel) {
175
+ const abs = path.resolve(String(root), String(rel || ''));
176
+ const dir = path.dirname(abs), base = path.basename(abs).replace(/\.md$/, '');
177
+ let names = []; try { names = fs.readdirSync(dir); } catch { return []; }
178
+ const out = [];
179
+ for (const n of names.sort()) {
180
+ const m = /^(.+)\.([a-z]{2})\.md$/.exec(n);
181
+ if (!m || m[1] !== base || !LANGS[m[2]]) continue;
182
+ let fm = {}; try { fm = fmMap(bodyOf(fs.readFileSync(path.join(dir, n), 'utf8')).fm); } catch { continue; }
183
+ if (!fm.translation_of) continue;
184
+ out.push({ code: m[2], language: LANGS[m[2]], reader: fm.reader || '', path: path.posix.join(path.posix.dirname(String(rel)), n) });
185
+ }
186
+ return out;
187
+ }
188
+
189
+ function guardOf() { try { return require('./ai-guard.js'); } catch { return null; } }
190
+
191
+ /** One draft → one copy per language its definition names. */
192
+ async function translate({ root, rel, ask, runtime = null, env = process.env, guard = guardOf(), langs = null } = {}) {
193
+ const res = { written: [], refused: [], skipped: [] };
194
+ try { if (require('./design-critic.js').off(env)) return { ...res, off: 'the critic runs are off' }; } catch { /* no switch */ }
195
+ if (guard) { const stop = guard.off(JOB, { env, settingsDir: runtime || null }); if (stop) return { ...res, off: stop }; }
196
+ const at = stateRelOf(rel);
197
+ if (!at) return { ...res, off: 'not a cadence draft' };
198
+ const list = langs || definitionLanguages(root, at.cadence, at.state);
199
+ if (!list.length) return { ...res, off: 'the definition names no other language' };
200
+ if (typeof ask !== 'function') return { ...res, off: 'no run can start here' };
201
+ let raw; try { raw = fs.readFileSync(path.resolve(String(root), rel), 'utf8'); } catch { return { ...res, off: 'the draft could not be read' }; }
202
+ const { fm, body } = bodyOf(raw);
203
+ const sha = shaOf(body);
204
+ for (const L of list) {
205
+ const out = copyPath(rel, L.code), abs = path.resolve(String(root), out);
206
+ let prev = ''; try { prev = fs.readFileSync(abs, 'utf8'); } catch { prev = ''; }
207
+ if (prev && fmMap(bodyOf(prev).fm).source_sha === sha) { res.skipped.push({ code: L.code, why: 'this text was translated already' }); continue; }
208
+ const answer = await ask(promptOf({ body, language: L.language, reader: L.reader }), { key: at.cadence + '-' + at.slot + '-' + L.code });
209
+ const tr = answerOf(answer);
210
+ if (!tr) { res.refused.push({ code: L.code, why: answer == null ? 'the run did not answer' : 'the answer held no translated report' }); continue; }
211
+ const k = keeps(body, tr);
212
+ if (!k.ok) { res.refused.push({ code: L.code, why: k.why }); continue; }
213
+ fs.writeFileSync(abs, copyText({ fm, body: tr, rel, language: L.language, code: L.code, reader: L.reader, sha }));
214
+ res.written.push({ code: L.code, path: out });
215
+ }
216
+ for (const r of res.refused) console.log(`[report-translate] ${rel} ${r.code}: not written (${r.why})`);
217
+ if (res.written.length) console.log(`[report-translate] ${rel}: ${res.written.map((w) => w.code).join(', ')} written`);
218
+ return res;
219
+ }
220
+
221
+ let attached = false;
222
+ /** server.js calls this once: every draft this process writes is translated for its readers, in the background. */
223
+ function attach(ctxFactory) {
224
+ if (attached || typeof ctxFactory !== 'function') return;
225
+ attached = true;
226
+ require('./report-draft.js').onDraftWritten(({ root, path: rel }) => {
227
+ setImmediate(() => {
228
+ let ctx = null; try { ctx = ctxFactory(); } catch { ctx = null; }
229
+ const spawn = ctx && (ctx.spawnScheduled || ctx.spawnSession);
230
+ if (typeof spawn !== 'function') return;
231
+ const ask = require('./design-critic.js').askVia(spawn, { name: 'report translation', origin: ORIGIN });
232
+ translate({ root: path.resolve(String(root)), rel, ask, runtime: ctx.runtimeDir || null })
233
+ .catch((e) => console.log(`[report-translate] ${rel}: not run (${one(e && e.message, 160)})`));
234
+ });
235
+ });
236
+ }
237
+
238
+ module.exports = { JOB, ORIGIN, LANGS, codeOf, languagesOf, bodyOf, shaOf, namesOf, keeps, promptOf, answerOf, copyPath, copyText, alsoOf, definitionLanguages, setLanguage, translate, attach };
@@ -7,6 +7,11 @@
7
7
  * merge, cost per merged pull request, human corrections per item. Zero is silence: a product with no factory run in the window
8
8
  * is left out, so no factory runs anywhere answers products: [].
9
9
  * `pmos build metrics` prints the same numbers for one repository.
10
+ *
11
+ * GET /api/factory?ws → { ok, products: [{ ws, name, snapshot }] } (initiative factory-floor-snapshot)
12
+ * The factory floor per product as the Driver saved it after its last run (lib/factory-floor.js load). It reads one file per product and
13
+ * folds nothing, so the Factory page opens in 200 ms or less. snapshot is null while no run has saved one: a read never computes or writes.
14
+ * ws: one workspace (404 when unknown); without it, every workspace.
10
15
  */
11
16
  const FT = require('./factory-traces.js');
12
17
 
@@ -28,8 +33,24 @@ function metricsFor(ctx, { ws = '', days = 30, now = Date.now() } = {}) {
28
33
  return { status: 200, body: { ok: true, days, products } };
29
34
  }
30
35
 
36
+ function floorFor(ctx, { ws = '' } = {}) {
37
+ let list;
38
+ if (ws) {
39
+ const w = ctx.getWs(ws);
40
+ if (!w || w.id !== ws) return bad(404, 'no such workspace');
41
+ list = [w];
42
+ } else list = (ctx.workspaceList ? ctx.workspaceList() : []).filter((w) => w && w.root && !w.linked);
43
+ const FF = require('./factory-floor.js');
44
+ const products = list.map((w) => ({ ws: w.id, name: w.name || w.id, snapshot: FF.load(w.root, { stateDir: require('./driver.js').stateDirOf(w.root) || (ctx.stateDirFor ? ctx.stateDirFor(w) : null) }) }));
45
+ return { status: 200, body: { ok: true, products } };
46
+ }
47
+
31
48
  async function handle(req, res, url, ctx) {
32
49
  const send = (r) => { ctx.json(res, r.body, r.status); return true; };
50
+ if (url.pathname === '/api/factory') {
51
+ if (req.method !== 'GET') return send(bad(405, 'GET only'));
52
+ return send(floorFor(ctx, { ws: String(url.searchParams.get('ws') || '') }));
53
+ }
33
54
  if (url.pathname !== '/api/factory/metrics') return send(bad(404, 'no such factory route'));
34
55
  if (req.method !== 'GET') return send(bad(405, 'GET only'));
35
56
  const d = url.searchParams.get('days');
@@ -38,4 +59,4 @@ async function handle(req, res, url, ctx) {
38
59
  return send(metricsFor(ctx, { ws: String(url.searchParams.get('ws') || ''), days }));
39
60
  }
40
61
 
41
- module.exports = { prefixes: ['/api/factory/metrics'], handle, metricsFor };
62
+ module.exports = { prefixes: ['/api/factory/metrics', '/api/factory'], handle, metricsFor, floorFor };
@@ -3,7 +3,8 @@
3
3
  *
4
4
  * GET /api/report?ws= the report files of the repository, drafts and issued, of every cadence,
5
5
  * with the `sig` the page watches (public/pm/sig-watch.js, 10 s)
6
- * GET /api/report/draft?ws=&cadence=&slot= one report file as it is now: its markdown, its note texts, its blob sha
6
+ * GET /api/report/draft?ws=&cadence=&slot= one report file as it is now: its markdown, its note texts, its blob sha, and `also`:
7
+ * the translated copies beside it (lib/report-translate.js alsoOf)
7
8
  * POST /api/report/draft { ws, cadence, slot?, redraft? } Draft now, and Redraft (the notes are kept)
8
9
  * POST /api/report/note { ws, cadence, slot, id, text } one note, by initiative id (or report.headline, report.asks, report.changelog)
9
10
  * POST /api/report/issue { ws, cadence, slot, sha } Issue: the PM's act (R25)
@@ -29,6 +30,8 @@ const actorLib = require('./actor.js');
29
30
  const RD = require('./report-draft.js');
30
31
  const issues = require('./issues.js');
31
32
  const RN = require('./report-needs.js');
33
+ /** The translated copies beside a draft; none when the module is not installed. */
34
+ const alsoOf = (root, rel) => { try { return require('./report-translate.js').alsoOf(root, rel); } catch { return []; } };
32
35
 
33
36
  const CADENCE_RE = /^[a-z][a-z0-9-]{0,39}$/;
34
37
  const SLOT_RE = /^\d{4}-\d{2}-\d{2}$/;
@@ -97,6 +100,7 @@ async function handle(req, res, url, ctx) {
97
100
  ctx.json(res, {
98
101
  ok: true, ws: w.id, sig: list.sig, cadence: cs.cadence, slot: cs.slot, exists: true, path: hit.path, status: hit.status,
99
102
  sha: RN.blobSha(file.buf), markdown: file.text, notes: RD.readNotes(file.text), issued: pageReport(hit).issued, edited: hit.edited, flags: pageFlags(list.flags),
103
+ also: alsoOf(w.root, hit.path),
100
104
  });
101
105
  return true;
102
106
  }
@@ -2,7 +2,9 @@
2
2
  /* routes-search.js — Search across the repository and every worktree (initiative premium-uncovered-features, E1; lib/search-index.js).
3
3
  *
4
4
  * GET /api/find?q=<words>&ws=<id>&wt=<id,id> → { ok, q, worktrees, counts, results, more, answer? } wt: the worktrees to search (none: all)
5
- * answer: one sentence from the user's own files with its source (lib/search-answer.js); absent when nothing is clear
5
+ * answer: one sentence from the user's own files with its source (lib/search-answer.js); absent when nothing is clear.
6
+ * "I have 30 minutes" (time-box-pick-chat, A293): the answer is instead the one ask that fits the time and unblocks the most
7
+ * (lib/time-box-pick.js, read-only, no model), and the use log counts it
6
8
  * GET /api/search-ask?q=<question>&ws=<id> → { ok, answer, why? } a question's answer (lib/search-ask.js): the copied sentence when there is
7
9
  * one, else one written by a read-only PMOS session from passages of the user's files, with those files as its sources (search-answers-questions)
8
10
  * GET /api/find/file?ws=<id>&wt=<id>&path=<p> → { ok, wt, branch, main, path, text, mtime } one file of a listed worktree, for the Viewer
@@ -36,6 +38,20 @@ module.exports = {
36
38
  ctx.json(res, { ws: w.id, q: String(url.searchParams.get('q') || '').trim(), ...r });
37
39
  return true;
38
40
  }
41
+ const mins = require('./time-box-pick.js').minutesOf(url.searchParams.get('q') || '');
42
+ if (mins) {
43
+ const TB = require('./time-box-pick.js');
44
+ let sessions = [];
45
+ try { sessions = ctx.sessionList ? ctx.sessionList() : []; } catch { sessions = []; }
46
+ try {
47
+ const p = TB.read({ w, stateDir: ctx.stateDirFor ? ctx.stateDirFor(w) : undefined, runtimeDir: ctx.runtimeDir, sessions, minutes: mins });
48
+ TB.logUse(ctx.runtimeDir, 'search');
49
+ ctx.json(res, { ok: true, ws: w.id, q: String(url.searchParams.get('q') || '').trim(), worktrees: [], counts: {}, results: [], more: false, answer: TB.answerOf(p) });
50
+ } catch (e) {
51
+ ctx.json(res, { ok: false, error: 'the pick could not be made: ' + String((e && e.message) || e).slice(0, 160) }, 500);
52
+ }
53
+ return true;
54
+ }
39
55
  let notes = [];
40
56
  try { const l = ctx.runtimeDir ? require('./notes.js').list(ctx.runtimeDir) : null; notes = l && l.ok ? l.notes : []; } catch { notes = []; }
41
57
  const only = (url.searchParams.get('wt') || '').split(',').map((x) => x.trim()).filter(Boolean);