@pugi/cli 0.1.0-beta.93 → 0.1.0-beta.94

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 (35) hide show
  1. package/dist/commands/retro.js +210 -0
  2. package/dist/core/diagnostics/probes/sandbox.js +65 -33
  3. package/dist/core/engine/native-pugi.js +184 -10
  4. package/dist/core/engine/tool-bridge.js +35 -0
  5. package/dist/core/engine/verification-patterns.js +9 -9
  6. package/dist/core/mcp/orchestrator-config.js +192 -0
  7. package/dist/core/mcp/orchestrator-tools.js +147 -3
  8. package/dist/core/pugi-gitignore.js +52 -0
  9. package/dist/core/repl/engine-bridge.js +199 -0
  10. package/dist/core/repl/session.js +395 -6
  11. package/dist/core/repl/tool-route.js +382 -0
  12. package/dist/core/retro/git-collector.js +251 -0
  13. package/dist/core/retro/health-card.js +25 -0
  14. package/dist/core/retro/metrics.js +342 -0
  15. package/dist/core/retro/narrative.js +249 -0
  16. package/dist/core/retro/plane-collector.js +274 -0
  17. package/dist/core/retro/pr-issue-link.js +65 -0
  18. package/dist/core/retro/types.js +16 -0
  19. package/dist/core/sandboxing/adapter.js +29 -0
  20. package/dist/core/sandboxing/index.js +49 -0
  21. package/dist/core/sandboxing/none.js +19 -0
  22. package/dist/core/sandboxing/seatbelt.js +183 -0
  23. package/dist/core/session.js +27 -0
  24. package/dist/core/settings.js +22 -0
  25. package/dist/runtime/cli.js +167 -33
  26. package/dist/runtime/commands/mcp.js +64 -8
  27. package/dist/runtime/deprecation-warning.js +69 -0
  28. package/dist/runtime/headless.js +8 -3
  29. package/dist/runtime/stream-renderer.js +195 -0
  30. package/dist/runtime/version.js +1 -1
  31. package/dist/tui/agent-tree.js +11 -0
  32. package/dist/tui/ask-user-question-chips.js +1 -1
  33. package/dist/tui/multi-file-diff-approval.js +3 -3
  34. package/dist/tui/repl-render.js +42 -0
  35. package/package.json +2 -2
@@ -0,0 +1,382 @@
1
+ /**
2
+ * PUGI-538b () — `<pugi-tool-route>` envelope parser.
3
+ *
4
+ * The admin-api Pugi coordinator persona emits an
5
+ * `<pugi-tool-route command="code|fix|build" persona="<slug>" brief="…"/>`
6
+ * envelope on her turn when the operator's brief requires workspace
7
+ * tool use (write/edit/read a file, run a script, install a package,
8
+ * build, test). The CLI consumer parses the envelope, strips it from
9
+ * operator-visible detail, and routes the brief through the local
10
+ * `NativePugiEngineAdapter` → `runEngineLoop` → `POST /api/pugi/engine`
11
+ * flow that already drives `pugi code/fix/build` end-to-end with real
12
+ * tool calls and atomic file writes.
13
+ *
14
+ * Without this envelope the REPL chat path is a single-shot text
15
+ * streamer: customer says "make tic-tac-toe", Pugi responds with a
16
+ * bash heredoc dump as prose, no file is written. (PUGI-538a)
17
+ * lays out the architecture; this parser is the CLI half of the bridge.
18
+ *
19
+ * # Grammar (self-closing form is preferred; paired form also accepted)
20
+ *
21
+ * <pugi-tool-route command="code" persona="dev" brief="One sentence…"/>
22
+ * <pugi-tool-route command="fix" persona="dev" brief="…"></pugi-tool-route>
23
+ *
24
+ * Attributes:
25
+ * - command (required) — exactly one of `code`, `fix`, `build`.
26
+ * - persona (optional) — Tier-1 persona slug hint; defaults to `dev`
27
+ * when omitted. The value `main` is rejected (the REPL
28
+ * coordinator IS Pugi already, routing back to herself
29
+ * would not change behaviour).
30
+ * - brief (required) — single-sentence operational brief,
31
+ * <= 400 chars after entity decoding.
32
+ *
33
+ * # Why a hand-rolled parser, not a generic XML library
34
+ *
35
+ * Same rationale as `ask.ts`: generic XML libraries (sax,
36
+ * fast-xml-parser, xmldoc) carry a large attack surface (external
37
+ * entity expansion, recursive blowup on malformed input, sloppy
38
+ * attribute handling) and require ~50 KB of runtime dependency. The
39
+ * persona-side grammar here is one tag with a closed three-attribute
40
+ * set, so a bounded tokenizer is both safer and smaller. The defences
41
+ * mirror ask.ts: closed entity allowlist, control-char strip, refusal
42
+ * on raw `&` outside `&amp;` / `&lt;` / `&gt;` / `&quot;` / `&apos;`,
43
+ * refusal on nested tags inside attribute blob, hard span cap.
44
+ *
45
+ * # Buffering across streaming chunks
46
+ *
47
+ * The session calls `extractToolRouteTags(buffer)` on the accumulated
48
+ * `agent.step.detail` body. If the close tag (or self-close `/>`) has
49
+ * not arrived yet, the parser returns `{ tags: [], pendingOpenTag: true }`
50
+ * and the session waits for more chunks. This mirrors the
51
+ * `extractAskTags` / `extractPlanReviewTags` shape so `session.ts`
52
+ * routes the three envelope families through one buffer-and-strip
53
+ * machinery.
54
+ */
55
+ /* ------------------------------------------------------------------ */
56
+ /* Bounded constants */
57
+ /* ------------------------------------------------------------------ */
58
+ /** Hard cap on the brief length after entity decoding. */
59
+ export const TOOL_ROUTE_MAX_BRIEF_LEN = 400;
60
+ /** Hard cap on the persona slug length. */
61
+ export const TOOL_ROUTE_MAX_PERSONA_LEN = 32;
62
+ /** Hard cap on the entire tag span. Long enough for full attrs + a
63
+ * worst-case 400-char brief plus closing form; defends against runaway
64
+ * payloads. */
65
+ const TAG_MAX_SPAN_BYTES = 4 * 1024;
66
+ /** Tag families exhaustively enumerated for the closed-attribute gate. */
67
+ const ALLOWED_ATTRS = new Set([
68
+ 'command',
69
+ 'persona',
70
+ 'brief',
71
+ ]);
72
+ /** Accepted `command` literals — locked to the engine adapter contract. */
73
+ const ALLOWED_COMMANDS = new Set(['code', 'fix', 'build']);
74
+ /** Refused personas. `main` would route Pugi back to herself; the engine
75
+ * adapter rejects the slug anyway, so we filter at parse time for clarity. */
76
+ const REFUSED_PERSONAS = new Set(['main', 'pugi']);
77
+ /** Default persona slug when the attribute is omitted. Matches the
78
+ * ENVELOPES_BODY prompt copy ("Defaults to 'dev' when omitted"). */
79
+ const DEFAULT_PERSONA = 'dev';
80
+ /* ------------------------------------------------------------------ */
81
+ /* Public extraction API */
82
+ /* ------------------------------------------------------------------ */
83
+ /**
84
+ * Find every well-formed `<pugi-tool-route>` envelope in `body`.
85
+ * Malformed envelopes are dropped and surfaced via `hadMalformedTag`
86
+ * so the session can log a warning. Streaming-incomplete envelopes
87
+ * (open observed, close/self-close not yet arrived) are withheld from
88
+ * `cleaned` so the raw envelope cannot leak into the transcript if the
89
+ * stream pauses mid-tag.
90
+ */
91
+ export function extractToolRouteTags(body) {
92
+ const tags = [];
93
+ const segments = [];
94
+ let cursor = 0;
95
+ let pendingOpenTag = false;
96
+ let hadMalformedTag = false;
97
+ // Hard cap on tags per buffer so a hostile (or accidental) flood
98
+ // does not pin the parser. 16 is generous — a real session never
99
+ // has more than one envelope queued per turn.
100
+ const MAX_TAGS_PER_BUFFER = 16;
101
+ // Belt-and-braces safety counter — the body length bounds the
102
+ // iteration count strictly, but a pathological input could otherwise
103
+ // loop until the per-buffer cap fires.
104
+ let safetyIterations = body.length + 16;
105
+ const OPEN_PREFIX = '<pugi-tool-route';
106
+ const PAIR_CLOSE = '</pugi-tool-route>';
107
+ while (cursor < body.length && tags.length < MAX_TAGS_PER_BUFFER) {
108
+ if (safetyIterations-- <= 0)
109
+ break;
110
+ const openIndex = body.indexOf(OPEN_PREFIX, cursor);
111
+ if (openIndex === -1) {
112
+ // No more envelopes. Flush the rest of the body as cleaned prose.
113
+ segments.push(body.slice(cursor));
114
+ cursor = body.length;
115
+ break;
116
+ }
117
+ // Push everything before the opening tag as cleaned prose.
118
+ segments.push(body.slice(cursor, openIndex));
119
+ // Locate the end of the opening tag. The envelope may be self-
120
+ // closing (`/>`) or paired (`>` then `</pugi-tool-route>`).
121
+ // Search for the FIRST unquoted `>` after the OPEN_PREFIX position
122
+ // so a quoted attribute value with an embedded `>` (escaped as
123
+ // `&gt;` per the grammar; raw `>` is rejected below) cannot
124
+ // confuse the boundary scan.
125
+ const openEnd = findUnquotedGt(body, openIndex + OPEN_PREFIX.length);
126
+ if (openEnd === -1) {
127
+ // Open seen, no terminator yet. Withhold from `cleaned` so the
128
+ // raw envelope cannot leak. Same posture as ask.ts.
129
+ pendingOpenTag = true;
130
+ cursor = body.length;
131
+ break;
132
+ }
133
+ const selfClosed = body[openEnd - 1] === '/';
134
+ let tagEnd;
135
+ if (selfClosed) {
136
+ tagEnd = openEnd + 1; // include the closing `>`
137
+ }
138
+ else {
139
+ // Paired form — look for `</pugi-tool-route>`.
140
+ const closeAt = body.indexOf(PAIR_CLOSE, openEnd + 1);
141
+ if (closeAt === -1) {
142
+ pendingOpenTag = true;
143
+ cursor = body.length;
144
+ break;
145
+ }
146
+ tagEnd = closeAt + PAIR_CLOSE.length;
147
+ }
148
+ const span = body.slice(openIndex, tagEnd);
149
+ if (span.length > TAG_MAX_SPAN_BYTES) {
150
+ hadMalformedTag = true;
151
+ cursor = tagEnd;
152
+ continue;
153
+ }
154
+ // Reject nested envelopes — the generic "find next close" would
155
+ // otherwise pair an outer open with an inner close.
156
+ const innerOpen = span.indexOf(OPEN_PREFIX, OPEN_PREFIX.length);
157
+ if (innerOpen !== -1) {
158
+ hadMalformedTag = true;
159
+ cursor = tagEnd;
160
+ continue;
161
+ }
162
+ // Slice the attribute blob between OPEN_PREFIX and the closing
163
+ // `>` (excluding the trailing `/` on the self-closed form).
164
+ const attrBlobEnd = selfClosed ? openEnd - 1 : openEnd;
165
+ const attrBlob = body.slice(openIndex + OPEN_PREFIX.length, attrBlobEnd);
166
+ const parsed = parseToolRouteInner(attrBlob, {
167
+ start: openIndex,
168
+ end: tagEnd,
169
+ });
170
+ if (parsed === null) {
171
+ hadMalformedTag = true;
172
+ cursor = tagEnd;
173
+ continue;
174
+ }
175
+ tags.push(parsed);
176
+ cursor = tagEnd;
177
+ }
178
+ return {
179
+ tags,
180
+ cleaned: segments.join('').replace(/\s+\n/g, '\n').trimEnd(),
181
+ pendingOpenTag,
182
+ hadMalformedTag,
183
+ };
184
+ }
185
+ /* ------------------------------------------------------------------ */
186
+ /* Inner parser */
187
+ /* ------------------------------------------------------------------ */
188
+ function parseToolRouteInner(attrBlob, span) {
189
+ // Reject CDATA, comments, processing instructions, DOCTYPE inside
190
+ // the attribute blob — none of those appear in the legal grammar.
191
+ if (/<!--|<!\[|<\?|<!DOCTYPE/i.test(attrBlob))
192
+ return null;
193
+ // Reject raw `&` not in a known entity (decoded entities are allowed
194
+ // via decodeEntities below).
195
+ if (containsRawAmpersand(attrBlob))
196
+ return null;
197
+ // Reject raw `<` / `>` inside the attribute blob — they should always
198
+ // be escaped as `&lt;` / `&gt;`. The presence of a raw bracket is a
199
+ // sign of either accidental sloppy output or an injection attempt.
200
+ if (/[<>]/.test(attrBlob))
201
+ return null;
202
+ const attrs = parseAttrBlob(attrBlob);
203
+ if (attrs === null)
204
+ return null;
205
+ // Closed-attribute gate — refuse anything outside the allowlist.
206
+ for (const key of Object.keys(attrs)) {
207
+ if (!ALLOWED_ATTRS.has(key))
208
+ return null;
209
+ }
210
+ const command = attrs['command'];
211
+ if (typeof command !== 'string' || command.length === 0)
212
+ return null;
213
+ if (!ALLOWED_COMMANDS.has(command))
214
+ return null;
215
+ const briefRaw = attrs['brief'];
216
+ if (typeof briefRaw !== 'string')
217
+ return null;
218
+ const brief = briefRaw.trim();
219
+ if (brief.length === 0 || brief.length > TOOL_ROUTE_MAX_BRIEF_LEN)
220
+ return null;
221
+ // Persona is optional → default to `dev`. Any explicit non-empty
222
+ // value runs through the slug shape check + refused-persona gate.
223
+ const personaRaw = attrs['persona'];
224
+ let persona = DEFAULT_PERSONA;
225
+ if (typeof personaRaw === 'string' && personaRaw.length > 0) {
226
+ const trimmed = personaRaw.trim();
227
+ if (trimmed.length === 0 || trimmed.length > TOOL_ROUTE_MAX_PERSONA_LEN)
228
+ return null;
229
+ // Slug shape: lowercase ASCII letters + digits + hyphens, must
230
+ // start with a letter. Same shape as the `<pugi-delegate>` slug
231
+ // gate in admin-api so a future engine adapter can reuse the slug
232
+ // verbatim without re-validating.
233
+ if (!/^[a-z][a-z0-9-]*$/.test(trimmed))
234
+ return null;
235
+ if (REFUSED_PERSONAS.has(trimmed))
236
+ return null;
237
+ persona = trimmed;
238
+ }
239
+ const signature = signatureForToolRoute(command, persona, brief);
240
+ return {
241
+ command: command,
242
+ persona,
243
+ brief,
244
+ signature,
245
+ start: span.start,
246
+ end: span.end,
247
+ };
248
+ }
249
+ /**
250
+ * Parse `key="value"` / `key='value'` pairs out of an attribute blob.
251
+ * Returns null on any malformed attribute (unterminated quote, raw
252
+ * entity outside the allowlist, etc). Mirrors the bounded tokenizer
253
+ * in ask.ts so the parsing posture is uniform across envelope families.
254
+ */
255
+ function parseAttrBlob(blob) {
256
+ const trimmed = blob.trim();
257
+ if (trimmed.length === 0)
258
+ return {};
259
+ const result = {};
260
+ let cursor = 0;
261
+ const maxIterations = trimmed.length + 4;
262
+ let iterations = 0;
263
+ while (cursor < trimmed.length && iterations++ < maxIterations) {
264
+ while (cursor < trimmed.length && /\s/.test(trimmed[cursor] ?? ''))
265
+ cursor += 1;
266
+ if (cursor >= trimmed.length)
267
+ break;
268
+ const nameStart = cursor;
269
+ // Attribute names are lowercase letters; allow `-` for consistency
270
+ // with the rest of the persona grammar even though our allowlist is
271
+ // hyphen-free. Mismatch is caught by the ALLOWED_ATTRS gate.
272
+ while (cursor < trimmed.length &&
273
+ /[a-z-]/.test(trimmed[cursor] ?? '')) {
274
+ cursor += 1;
275
+ }
276
+ if (cursor === nameStart)
277
+ return null;
278
+ const name = trimmed.slice(nameStart, cursor);
279
+ if (trimmed[cursor] !== '=')
280
+ return null;
281
+ cursor += 1;
282
+ const quote = trimmed[cursor];
283
+ if (quote !== '"' && quote !== "'")
284
+ return null;
285
+ cursor += 1;
286
+ const valueStart = cursor;
287
+ const valueEnd = trimmed.indexOf(quote, valueStart);
288
+ if (valueEnd === -1)
289
+ return null;
290
+ const rawValue = trimmed.slice(valueStart, valueEnd);
291
+ // Raw `&` outside a known entity is malformed; raw angle brackets
292
+ // are forbidden inside quoted values (must be escaped). The closed
293
+ // entity allowlist + control-char strip mirrors ask.ts.
294
+ if (containsRawAmpersand(rawValue))
295
+ return null;
296
+ if (/[<>]/.test(rawValue))
297
+ return null;
298
+ result[name] = stripControlChars(decodeEntities(rawValue));
299
+ cursor = valueEnd + 1;
300
+ }
301
+ return result;
302
+ }
303
+ /* ------------------------------------------------------------------ */
304
+ /* Streaming helper — find an unquoted `>` after `from` */
305
+ /* ------------------------------------------------------------------ */
306
+ /**
307
+ * Walk `body` from index `from` looking for the first `>` that is NOT
308
+ * inside a quoted attribute value. Returns the index of the `>` or -1
309
+ * when no such position is found.
310
+ *
311
+ * Quote tracking is necessary because a `brief="…contains > as &gt;…"`
312
+ * value should never confuse the boundary scan. The grammar already
313
+ * forbids raw `>` inside quoted values (escape as `&gt;`) — this is
314
+ * belt-and-braces against a sloppy model emission.
315
+ */
316
+ function findUnquotedGt(body, from) {
317
+ let quote = null;
318
+ for (let i = from; i < body.length; i += 1) {
319
+ const ch = body[i];
320
+ if (quote !== null) {
321
+ if (ch === quote)
322
+ quote = null;
323
+ continue;
324
+ }
325
+ if (ch === '"' || ch === "'") {
326
+ quote = ch;
327
+ continue;
328
+ }
329
+ if (ch === '>')
330
+ return i;
331
+ }
332
+ return -1;
333
+ }
334
+ /* ------------------------------------------------------------------ */
335
+ /* Entity decoding + amp safety + control strip */
336
+ /* ------------------------------------------------------------------ */
337
+ const ENTITY_MAP = Object.freeze({
338
+ amp: '&',
339
+ lt: '<',
340
+ gt: '>',
341
+ quot: '"',
342
+ apos: "'",
343
+ });
344
+ function decodeEntities(input) {
345
+ return input.replace(/&([a-z]+);/g, (whole, name) => {
346
+ const decoded = ENTITY_MAP[name];
347
+ return decoded === undefined ? whole : decoded;
348
+ });
349
+ }
350
+ function stripControlChars(input) {
351
+ // eslint-disable-next-line no-control-regex -- deliberately matching control range
352
+ return input.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f\x80-\x9f]/g, '');
353
+ }
354
+ function containsRawAmpersand(input) {
355
+ for (let i = 0; i < input.length; i += 1) {
356
+ if (input[i] !== '&')
357
+ continue;
358
+ const semi = input.indexOf(';', i + 1);
359
+ if (semi === -1)
360
+ return true;
361
+ const name = input.slice(i + 1, semi);
362
+ if (!Object.prototype.hasOwnProperty.call(ENTITY_MAP, name))
363
+ return true;
364
+ i = semi;
365
+ }
366
+ return false;
367
+ }
368
+ /* ------------------------------------------------------------------ */
369
+ /* Signature */
370
+ /* ------------------------------------------------------------------ */
371
+ /**
372
+ * Stable dedupe signature for a tool-route tag. Exported so future
373
+ * synthesisers (slash command, local fallback) can produce signatures
374
+ * that collision-match parser-produced ones — without a single source
375
+ * of truth a local synth could share a signature with a persona-emitted
376
+ * envelope and the rolling-seen set would suppress one of them.
377
+ */
378
+ export function signatureForToolRoute(command, persona, brief) {
379
+ const raw = `${command}::${persona.toLowerCase()}::${brief.trim().toLowerCase()}`;
380
+ return Buffer.from(raw, 'utf8').toString('base64');
381
+ }
382
+ //# sourceMappingURL=tool-route.js.map
@@ -0,0 +1,251 @@
1
+ /**
2
+ * Git collector for `pugi retro`.
3
+ *
4
+ * Mines a window of git history into RawCommit[] using `git log
5
+ * --numstat --no-renames` plus a few discrete `git` calls for branch
6
+ * + base + user identity. All git invocations go through child_process
7
+ * (execFile) so we never shell-expand operator-controlled values.
8
+ *
9
+ * The collector is intentionally tolerant of a "no git" workspace —
10
+ * `pugi retro` should not crash on a fresh `pugi init` scratch dir.
11
+ * `collectGitContext` returns an empty harvest with `hasGit: false`
12
+ * so the renderer can emit a friendly empty-state.
13
+ */
14
+ import { execFile } from 'node:child_process';
15
+ import { existsSync } from 'node:fs';
16
+ import { join } from 'node:path';
17
+ import { promisify } from 'node:util';
18
+ const execFileAsync = promisify(execFile);
19
+ const GIT_LOG_FORMAT = '%H%x01%an%x01%ae%x01%aI%x01%at%x01%s%x01%b';
20
+ const RECORD_SEP = '\x02';
21
+ const FIELD_SEP = '\x01';
22
+ /** Files counted as tests (used both for stats split + commit-type
23
+ * classification when the author forgets a conventional prefix). */
24
+ const TEST_FILE_RE = /(^|\/)(test|tests|spec|__tests__)\//i;
25
+ const TEST_FILE_SUFFIX_RE = /\.(spec|test)\.(ts|tsx|js|jsx|mjs|cjs)$/i;
26
+ function isTestFile(path) {
27
+ if (TEST_FILE_RE.test(path))
28
+ return true;
29
+ if (TEST_FILE_SUFFIX_RE.test(path))
30
+ return true;
31
+ return false;
32
+ }
33
+ /** Format a Date as `YYYY-MM-DDTHH:mm:ss` in LOCAL time (no `Z` suffix).
34
+ * Spec: git log `--since` parses local-time strings when no Z is given.
35
+ */
36
+ export function formatLocalDateTime(d) {
37
+ const pad = (n) => n.toString().padStart(2, '0');
38
+ const y = d.getFullYear();
39
+ const mo = pad(d.getMonth() + 1);
40
+ const da = pad(d.getDate());
41
+ const h = pad(d.getHours());
42
+ const mi = pad(d.getMinutes());
43
+ const s = pad(d.getSeconds());
44
+ return `${y}-${mo}-${da}T${h}:${mi}:${s}`;
45
+ }
46
+ /** Detect whether the cwd lives inside a git working tree.
47
+ * Cheap probe: checks for a `.git` dir/file, then falls back to the
48
+ * actual `git rev-parse --is-inside-work-tree` for worktrees / submodules.
49
+ */
50
+ export async function isGitWorkspace(cwd) {
51
+ if (existsSync(join(cwd, '.git')))
52
+ return true;
53
+ try {
54
+ const { stdout } = await execFileAsync('git', ['rev-parse', '--is-inside-work-tree'], { cwd });
55
+ return stdout.trim() === 'true';
56
+ }
57
+ catch {
58
+ return false;
59
+ }
60
+ }
61
+ /** Resolve `origin/HEAD` symbolic ref → short name (e.g. `main`).
62
+ * Falls back to `main` if the remote ref is not set (common in fresh
63
+ * scratch repos with no remote).
64
+ */
65
+ export async function detectBaseBranch(cwd) {
66
+ try {
67
+ const { stdout } = await execFileAsync('git', ['symbolic-ref', '--short', 'refs/remotes/origin/HEAD'], { cwd });
68
+ const ref = stdout.trim();
69
+ if (!ref)
70
+ return 'main';
71
+ const idx = ref.lastIndexOf('/');
72
+ return idx === -1 ? ref : ref.slice(idx + 1);
73
+ }
74
+ catch {
75
+ return 'main';
76
+ }
77
+ }
78
+ export async function detectCurrentBranch(cwd) {
79
+ try {
80
+ const { stdout } = await execFileAsync('git', ['branch', '--show-current'], { cwd });
81
+ const branch = stdout.trim();
82
+ return branch || 'HEAD';
83
+ }
84
+ catch {
85
+ return 'HEAD';
86
+ }
87
+ }
88
+ export async function detectUserIdentity(cwd) {
89
+ const name = await readGitConfig(cwd, 'user.name');
90
+ const email = await readGitConfig(cwd, 'user.email');
91
+ return { name: name || 'You', email: email || '' };
92
+ }
93
+ async function readGitConfig(cwd, key) {
94
+ try {
95
+ const { stdout } = await execFileAsync('git', ['config', '--get', key], { cwd });
96
+ return stdout.trim();
97
+ }
98
+ catch {
99
+ return '';
100
+ }
101
+ }
102
+ /** Parse the multi-line `git log --numstat` output into RawCommit[].
103
+ *
104
+ * Format laid out as: `<header>\n<numstat lines>\n` per record,
105
+ * records separated by RECORD_SEP. The header has 7 fields joined by
106
+ * FIELD_SEP: sha, name, email, iso-date, epoch, subject, body. Each
107
+ * numstat line is `<ins>\t<del>\t<path>`; binary diffs surface as
108
+ * `-\t-\t<path>` and contribute 0/0 to the stats roll-up.
109
+ */
110
+ export function parseGitLog(raw) {
111
+ const records = raw.split(RECORD_SEP).map((r) => r.trim()).filter(Boolean);
112
+ const commits = [];
113
+ for (const record of records) {
114
+ const lines = record.split('\n');
115
+ const headerLine = lines[0];
116
+ if (!headerLine)
117
+ continue;
118
+ const headerFields = headerLine.split(FIELD_SEP);
119
+ if (headerFields.length < 7)
120
+ continue;
121
+ const sha = headerFields[0] ?? '';
122
+ const author = headerFields[1] ?? '';
123
+ const authorEmail = headerFields[2] ?? '';
124
+ const timestamp = headerFields[3] ?? '';
125
+ const epochRaw = headerFields[4] ?? '0';
126
+ const subject = headerFields[5] ?? '';
127
+ const body = headerFields[6] ?? '';
128
+ const epochSeconds = Number.parseInt(epochRaw, 10);
129
+ if (!sha || !Number.isFinite(epochSeconds))
130
+ continue;
131
+ const files = [];
132
+ let insertions = 0;
133
+ let deletions = 0;
134
+ let testInsertions = 0;
135
+ let testDeletions = 0;
136
+ for (let i = 1; i < lines.length; i += 1) {
137
+ const line = lines[i];
138
+ if (!line)
139
+ continue;
140
+ const parts = line.split('\t');
141
+ if (parts.length < 3)
142
+ continue;
143
+ const insRaw = parts[0] ?? '0';
144
+ const delRaw = parts[1] ?? '0';
145
+ const path = parts[2] ?? '';
146
+ if (!path)
147
+ continue;
148
+ const ins = insRaw === '-' ? 0 : Number.parseInt(insRaw, 10) || 0;
149
+ const del = delRaw === '-' ? 0 : Number.parseInt(delRaw, 10) || 0;
150
+ files.push(path);
151
+ insertions += ins;
152
+ deletions += del;
153
+ if (isTestFile(path)) {
154
+ testInsertions += ins;
155
+ testDeletions += del;
156
+ }
157
+ }
158
+ commits.push({
159
+ sha,
160
+ author,
161
+ authorEmail,
162
+ timestamp,
163
+ epochSeconds,
164
+ subject,
165
+ body,
166
+ files,
167
+ stats: { insertions, deletions, testInsertions, testDeletions },
168
+ });
169
+ }
170
+ return commits;
171
+ }
172
+ /** Run `git log` for the given window. The format string packs every
173
+ * field we need into one stream so we only spawn git once. Records
174
+ * are separated by RECORD_SEP and fields by FIELD_SEP (both control
175
+ * characters that cannot appear inside commit text), so the parser
176
+ * never confuses subject text containing tabs/newlines for delimiters.
177
+ */
178
+ async function runGitLog(cwd, window) {
179
+ const since = formatLocalDateTime(window.since);
180
+ const until = formatLocalDateTime(window.until);
181
+ const args = [
182
+ 'log',
183
+ `--since=${since}`,
184
+ `--until=${until}`,
185
+ '--no-renames',
186
+ '--numstat',
187
+ `--pretty=format:${RECORD_SEP}${GIT_LOG_FORMAT}`,
188
+ 'HEAD',
189
+ ];
190
+ try {
191
+ const { stdout } = await execFileAsync('git', args, {
192
+ cwd,
193
+ maxBuffer: 64 * 1024 * 1024,
194
+ });
195
+ return stdout;
196
+ }
197
+ catch {
198
+ return '';
199
+ }
200
+ }
201
+ /** Count commits between the merge-base of <base>...HEAD and HEAD —
202
+ * i.e. how many commits the current branch has added over the base.
203
+ * Returns 0 when the branch is base or the base ref is unknown.
204
+ */
205
+ export async function countCommitsAheadOfBase(cwd, base, since) {
206
+ try {
207
+ const { stdout } = await execFileAsync('git', [
208
+ 'rev-list',
209
+ '--count',
210
+ `${base}..HEAD`,
211
+ `--since=${formatLocalDateTime(since)}`,
212
+ ], { cwd });
213
+ const n = Number.parseInt(stdout.trim(), 10);
214
+ return Number.isFinite(n) ? n : 0;
215
+ }
216
+ catch {
217
+ return 0;
218
+ }
219
+ }
220
+ export async function collectGitContext(options) {
221
+ const { cwd, window } = options;
222
+ const hasGit = await isGitWorkspace(cwd);
223
+ if (!hasGit) {
224
+ return {
225
+ hasGit: false,
226
+ cwd,
227
+ currentBranch: '',
228
+ baseBranch: '',
229
+ userName: '',
230
+ userEmail: '',
231
+ commits: [],
232
+ };
233
+ }
234
+ const [currentBranch, baseBranch, identity, rawLog] = await Promise.all([
235
+ detectCurrentBranch(cwd),
236
+ detectBaseBranch(cwd),
237
+ detectUserIdentity(cwd),
238
+ runGitLog(cwd, window),
239
+ ]);
240
+ const commits = parseGitLog(rawLog);
241
+ return {
242
+ hasGit: true,
243
+ cwd,
244
+ currentBranch,
245
+ baseBranch,
246
+ userName: identity.name,
247
+ userEmail: identity.email,
248
+ commits,
249
+ };
250
+ }
251
+ //# sourceMappingURL=git-collector.js.map
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Workspace health card — Plane module oversize detection.
3
+ *
4
+ * Background (recall Pugi incident 2026-05-30): the Plane web UI
5
+ * tripped a React error boundary when an admin-api module accumulated
6
+ * ~200 issues. The actual REST API still returned 200, but the frontend
7
+ * choked. The fix was to keep modules at or below 60 issues and split larger ones.
8
+ *
9
+ * The health card surfaces a P1 warning when a module exceeds the
10
+ * recommended cap so the operator can split it before the next sprint.
11
+ */
12
+ /** Recommended max issues per Plane module. The retro card surfaces
13
+ * any module exceeding this so the operator can split it. */
14
+ export const OVERSIZED_MODULE_THRESHOLD = 60;
15
+ export function computeHealthCard(modules) {
16
+ const oversized = modules
17
+ .filter((m) => m.issueCount > OVERSIZED_MODULE_THRESHOLD)
18
+ .sort((a, b) => b.issueCount - a.issueCount);
19
+ return {
20
+ totalModules: modules.length,
21
+ oversized,
22
+ oversizedThreshold: OVERSIZED_MODULE_THRESHOLD,
23
+ };
24
+ }
25
+ //# sourceMappingURL=health-card.js.map