@pugi/cli 0.1.0-alpha.9 → 0.1.0-beta.2

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 (68) hide show
  1. package/README.md +33 -0
  2. package/assets/pugi-mascot.ansi +41 -0
  3. package/dist/commands/deploy.js +439 -0
  4. package/dist/core/agents/loader.js +104 -0
  5. package/dist/core/agents/registry.js +1 -1
  6. package/dist/core/consensus/anvil-fanout.js +276 -0
  7. package/dist/core/consensus/diff-capture.js +382 -0
  8. package/dist/core/consensus/rubric.js +233 -0
  9. package/dist/core/context/index.js +21 -0
  10. package/dist/core/context/pugiignore.js +316 -0
  11. package/dist/core/context/repo-skeleton.js +533 -0
  12. package/dist/core/context/watcher.js +342 -0
  13. package/dist/core/context/working-set.js +165 -0
  14. package/dist/core/edits/dispatch.js +185 -0
  15. package/dist/core/edits/index.js +15 -0
  16. package/dist/core/edits/layer-a-apply.js +217 -0
  17. package/dist/core/edits/layer-b-apply.js +211 -0
  18. package/dist/core/edits/layer-c-apply.js +160 -0
  19. package/dist/core/edits/layer-d-ast.js +29 -0
  20. package/dist/core/edits/marker-parser.js +401 -0
  21. package/dist/core/edits/security-gate.js +223 -0
  22. package/dist/core/edits/worktree.js +229 -0
  23. package/dist/core/engine/native-pugi.js +6 -1
  24. package/dist/core/engine/prompts.js +4 -1
  25. package/dist/core/engine/tool-bridge.js +33 -1
  26. package/dist/core/lsp/client.js +631 -0
  27. package/dist/core/repl/ask.js +512 -0
  28. package/dist/core/repl/cancellation.js +98 -0
  29. package/dist/core/repl/dispatch-fsm.js +220 -0
  30. package/dist/core/repl/privacy-banner.js +71 -0
  31. package/dist/core/repl/session.js +1896 -13
  32. package/dist/core/repl/slash-commands.js +59 -32
  33. package/dist/core/repl/store/index.js +12 -0
  34. package/dist/core/repl/store/jsonl-log.js +321 -0
  35. package/dist/core/repl/store/lockfile.js +155 -0
  36. package/dist/core/repl/store/session-store.js +792 -0
  37. package/dist/core/repl/store/types.js +44 -0
  38. package/dist/core/repl/store/uuid-v7.js +68 -0
  39. package/dist/core/repl/workspace-context.js +72 -1
  40. package/dist/core/skills/loader.js +454 -0
  41. package/dist/core/skills/sources.js +480 -0
  42. package/dist/core/skills/trust.js +172 -0
  43. package/dist/runtime/cli.js +767 -10
  44. package/dist/runtime/commands/agents.js +385 -0
  45. package/dist/runtime/commands/config.js +338 -8
  46. package/dist/runtime/commands/lsp.js +184 -0
  47. package/dist/runtime/commands/patch.js +111 -0
  48. package/dist/runtime/commands/review-consensus.js +399 -0
  49. package/dist/runtime/commands/skills.js +401 -0
  50. package/dist/runtime/commands/worktree.js +133 -0
  51. package/dist/tools/apply-patch.js +314 -0
  52. package/dist/tools/file-tools.js +90 -0
  53. package/dist/tools/lsp-tools.js +189 -0
  54. package/dist/tools/registry.js +18 -0
  55. package/dist/tools/web-fetch.js +1 -1
  56. package/dist/tui/agent-tree-pane.js +9 -0
  57. package/dist/tui/ask-cli.js +52 -0
  58. package/dist/tui/ask-modal.js +211 -0
  59. package/dist/tui/conversation-pane.js +48 -3
  60. package/dist/tui/input-box.js +48 -5
  61. package/dist/tui/markdown-render.js +266 -0
  62. package/dist/tui/repl-render.js +185 -0
  63. package/dist/tui/repl-splash-mascot.js +130 -0
  64. package/dist/tui/repl-splash.js +7 -1
  65. package/dist/tui/repl.js +82 -11
  66. package/dist/tui/status-bar.js +63 -3
  67. package/dist/tui/tool-stream-pane.js +91 -0
  68. package/package.json +11 -5
@@ -4,7 +4,9 @@ import { dirname, resolve } from 'node:path';
4
4
  import { z } from 'zod';
5
5
  import { loadMcpRegistry } from '../../core/mcp/registry.js';
6
6
  import { listMcpTrust, setMcpTrust, } from '../../core/mcp/trust.js';
7
+ import { request } from 'undici';
7
8
  import { trustWorkspace } from '../../core/trust.js';
9
+ import { resolveActiveCredential } from '../../core/credentials.js';
8
10
  /**
9
11
  * `pugi config` — operator-level configuration surface.
10
12
  *
@@ -53,24 +55,90 @@ export async function runConfigCommand(args, ctx) {
53
55
  'pugi config mcp trust <name>',
54
56
  'pugi config mcp deny <name>',
55
57
  'pugi config mcp list',
58
+ 'pugi config get routing',
59
+ 'pugi config set routing.<tag>.<budget>=<model>',
60
+ 'pugi config unset routing.<tag>.<budget>',
61
+ 'pugi config get privacy',
62
+ 'pugi config set privacy=strict|balanced|permissive',
56
63
  ],
57
64
  }, [
58
65
  'Usage:',
59
- ' pugi config get <key> Read a config value.',
60
- ' pugi config set <key> <value> Write a config value.',
61
- ' pugi config list Show all config values.',
62
- ' pugi config trust . Trust the current workspace for hooks + MCP.',
63
- ' pugi config mcp trust <name> Mark an MCP server as trusted.',
64
- ' pugi config mcp deny <name> Block an MCP server.',
65
- ' pugi config mcp list Show declared MCP servers + trust state.',
66
+ ' pugi config get <key> Read a config value.',
67
+ ' pugi config set <key> <value> Write a config value.',
68
+ ' pugi config list Show all config values.',
69
+ ' pugi config trust . Trust the current workspace for hooks + MCP.',
70
+ ' pugi config mcp trust <name> Mark an MCP server as trusted.',
71
+ ' pugi config mcp deny <name> Block an MCP server.',
72
+ ' pugi config mcp list Show declared MCP servers + trust state.',
73
+ ' pugi config get routing Show effective routing table (defaults + tenant overrides).',
74
+ ' pugi config set routing.<tag>.<budget>=<model> Override the model for one (tag, budget) lane.',
75
+ ' pugi config unset routing.<tag>.<budget> Remove a routing override (revert to default).',
76
+ ' pugi config get privacy Show current tenant privacy mode + last-flip metadata.',
77
+ ' pugi config set privacy=<mode> Flip privacy mode (strict | balanced | permissive).',
66
78
  ].join('\n'));
67
79
  return;
68
80
  }
69
81
  switch (sub) {
70
82
  case 'get':
83
+ // Special form: `pugi config get routing` hits the admin-api surface,
84
+ // not the local config file. Anything else is a local-config read.
85
+ if (args[1] === 'routing') {
86
+ return runRoutingGet(ctx);
87
+ }
88
+ // alpha 6.13: `pugi config get privacy` hits the admin-api
89
+ // /api/admin/privacy/mode surface. The privacy mode is a tenant-
90
+ // scoped server-side setting (so the Anvil filter can enforce it),
91
+ // not a local-only preference.
92
+ if (args[1] === 'privacy') {
93
+ return runPrivacyGet(ctx);
94
+ }
71
95
  return runConfigGet(args.slice(1), ctx);
72
96
  case 'set':
97
+ // Special form: `pugi config set routing.<tag>.<budget>=<model>` hits
98
+ // the admin-api routing override surface.
99
+ if (args[1] && args[1].startsWith('routing.')) {
100
+ return runRoutingSet(args.slice(1), ctx);
101
+ }
102
+ // alpha 6.13: `pugi config set privacy=<mode>` (or `privacy <mode>`)
103
+ // flips the tenant-scoped server-side mode IFF <mode> is one of
104
+ // the new closed set (strict | balanced | permissive). Legacy
105
+ // values (local-only | metadata | full) still hit the local
106
+ // config schema via runConfigSet so existing operators do not
107
+ // get a surprise 4xx when their playbook still uses the old
108
+ // names. The unit spec for config.ts has a regression test for
109
+ // both code paths.
110
+ //
111
+ // Triple-review P2 fix (2026-05-25): the prior disambiguation
112
+ // only excluded the bare form (`privacy local-only`) - the `=`
113
+ // form (`privacy=local-only`) still routed to runPrivacySet and
114
+ // 4xx'd. We now check the value AFTER `=` and route legacy local
115
+ // values to runConfigSet; new-style values + unknown values
116
+ // continue to runPrivacySet so its client-side validator surfaces
117
+ // a structured "Unknown privacy mode" error (preserves the
118
+ // existing UX for typos like `privacy=paranoid`).
119
+ if (args[1]) {
120
+ const equalsForm = args[1].startsWith('privacy=');
121
+ const bareForm = args[1] === 'privacy';
122
+ if (equalsForm) {
123
+ const valueAfterEquals = args[1].slice('privacy='.length);
124
+ if (isLegacyLocalPrivacyValue(valueAfterEquals)) {
125
+ // Legacy local form (`privacy=local-only|metadata|full`) -
126
+ // split into `['privacy', '<value>']` so runConfigSet sees
127
+ // the same shape it would for the bare form.
128
+ return runConfigSet(['privacy', valueAfterEquals], ctx);
129
+ }
130
+ return runPrivacySet(args.slice(1), ctx);
131
+ }
132
+ if (bareForm && isNewPrivacyModeValue(args[2])) {
133
+ return runPrivacySet(args.slice(1), ctx);
134
+ }
135
+ }
73
136
  return runConfigSet(args.slice(1), ctx);
137
+ case 'unset':
138
+ if (args[1] && args[1].startsWith('routing.')) {
139
+ return runRoutingUnset(args.slice(1), ctx);
140
+ }
141
+ throw new Error(`Unknown sub-command "pugi config unset ${args[1] ?? ''}". Only routing.<tag>.<budget> is supported today.`);
74
142
  case 'list':
75
143
  return runConfigList(ctx);
76
144
  case 'trust':
@@ -78,7 +146,7 @@ export async function runConfigCommand(args, ctx) {
78
146
  case 'mcp':
79
147
  return runConfigMcp(args.slice(1), ctx);
80
148
  default:
81
- throw new Error(`Unknown sub-command "pugi config ${sub}". Expected get, set, list, trust, or mcp.`);
149
+ throw new Error(`Unknown sub-command "pugi config ${sub}". Expected get, set, unset, list, trust, or mcp.`);
82
150
  }
83
151
  }
84
152
  function configPath() {
@@ -228,4 +296,266 @@ async function runConfigMcpFlip(args, ctx, state) {
228
296
  ? `MCP server "${name}" is now trusted.`
229
297
  : `MCP server "${name}" is now denied.`);
230
298
  }
299
+ /* ------------------------------------------------------------------ */
300
+ /* α6.10 multi-model routing — config.routing.* subcommands */
301
+ /* ------------------------------------------------------------------ */
302
+ /**
303
+ * Closed sets — match
304
+ * `apps/admin-api/src/mira/routing/dispatch-tag.ts` verbatim. Pinning
305
+ * them in the CLI lets us reject typos client-side before round-tripping
306
+ * to the admin-api (better UX, smaller blast radius for a wrong typo on
307
+ * a flaky network).
308
+ */
309
+ const ROUTING_TAGS = [
310
+ 'classify',
311
+ 'reason',
312
+ 'codegen',
313
+ 'summarize',
314
+ 'vision',
315
+ 'embed',
316
+ ];
317
+ const ROUTING_BUDGETS = ['min', 'std', 'max'];
318
+ function isRoutingTag(value) {
319
+ return ROUTING_TAGS.includes(value);
320
+ }
321
+ function isRoutingBudget(value) {
322
+ return ROUTING_BUDGETS.includes(value);
323
+ }
324
+ /**
325
+ * Resolve the admin-api host + bearer token from the CLI credential
326
+ * store. Throws a structured "anonymous" error when the operator has
327
+ * not logged in — same shape as `pugi whoami` so the harness exit
328
+ * codes stay aligned.
329
+ */
330
+ function resolveAdminApi() {
331
+ const credential = resolveActiveCredential();
332
+ if (!credential) {
333
+ throw new Error('pugi config routing requires authentication. Run `pugi login` first.');
334
+ }
335
+ return { apiUrl: credential.apiUrl, apiKey: credential.apiKey };
336
+ }
337
+ /**
338
+ * `pugi config get routing` — fetch the static default table + the
339
+ * tenant's override table, merge, and render as `routing.<tag>.<budget> = <model>`.
340
+ * Shows which lanes are overridden vs default.
341
+ */
342
+ async function runRoutingGet(ctx) {
343
+ const { apiUrl, apiKey } = resolveAdminApi();
344
+ const [defaults, overrides] = await Promise.all([
345
+ fetchJson(`${apiUrl}/api/admin/model-routing/defaults`, apiKey),
346
+ fetchJson(`${apiUrl}/api/admin/model-routing/overrides`, apiKey),
347
+ ]);
348
+ const overrideMap = new Map();
349
+ for (const row of overrides.overrides) {
350
+ overrideMap.set(`${row.tag}.${row.budgetHint}`, row.model);
351
+ }
352
+ const cells = defaults.defaults.map((cell) => {
353
+ const overridden = overrideMap.get(`${cell.tag}.${cell.budgetHint}`);
354
+ return {
355
+ tag: cell.tag,
356
+ budgetHint: cell.budgetHint,
357
+ model: overridden ?? cell.model,
358
+ source: overridden ? 'override' : 'default',
359
+ };
360
+ });
361
+ const text = [
362
+ 'Routing table (effective = override | default):',
363
+ ...cells.map((cell) => ` routing.${cell.tag.padEnd(10)}.${cell.budgetHint.padEnd(3)} = ${cell.model.padEnd(28)} (${cell.source})`),
364
+ ].join('\n');
365
+ ctx.writeOutput({
366
+ command: 'config.routing.get',
367
+ apiUrl,
368
+ cells,
369
+ }, text);
370
+ }
371
+ /**
372
+ * `pugi config set routing.<tag>.<budget>=<model>` — PUT to the admin-api
373
+ * override surface. Validates tag + budget client-side before round-tripping
374
+ * so a typo fails fast.
375
+ */
376
+ async function runRoutingSet(args, ctx) {
377
+ // The original arg is `routing.<tag>.<budget>=<model>` — args[0] holds
378
+ // everything up to the first whitespace, but the value may have been
379
+ // split. Re-join and re-split on `=` to be robust against a
380
+ // model slug containing `/` or `-`.
381
+ const raw = args.join(' ').trim();
382
+ const eqIdx = raw.indexOf('=');
383
+ if (eqIdx === -1) {
384
+ throw new Error('pugi config set routing.<tag>.<budget>=<model> requires an =<model> suffix.');
385
+ }
386
+ const lhs = raw.slice(0, eqIdx).trim();
387
+ const value = raw.slice(eqIdx + 1).trim();
388
+ const lhsParts = lhs.split('.');
389
+ if (lhsParts.length !== 3 || lhsParts[0] !== 'routing') {
390
+ throw new Error(`Expected routing.<tag>.<budget>, got "${lhs}".`);
391
+ }
392
+ const tag = lhsParts[1] ?? '';
393
+ const budget = lhsParts[2] ?? '';
394
+ if (!isRoutingTag(tag)) {
395
+ throw new Error(`Unknown routing tag "${tag}". Allowed: ${ROUTING_TAGS.join(', ')}.`);
396
+ }
397
+ if (!isRoutingBudget(budget)) {
398
+ throw new Error(`Unknown routing budget "${budget}". Allowed: ${ROUTING_BUDGETS.join(', ')}.`);
399
+ }
400
+ if (value.length === 0) {
401
+ throw new Error('Model slug must be non-empty.');
402
+ }
403
+ const { apiUrl, apiKey } = resolveAdminApi();
404
+ await fetchJson(`${apiUrl}/api/admin/model-routing/overrides/${tag}/${budget}`, apiKey, { method: 'PUT', body: { model: value } });
405
+ ctx.writeOutput({
406
+ command: 'config.routing.set',
407
+ tag,
408
+ budget,
409
+ model: value,
410
+ }, `routing.${tag}.${budget} = ${value}`);
411
+ }
412
+ /**
413
+ * `pugi config unset routing.<tag>.<budget>` — DELETE the override and
414
+ * revert the lane to its static default. Idempotent.
415
+ */
416
+ async function runRoutingUnset(args, ctx) {
417
+ const lhs = (args[0] ?? '').trim();
418
+ const lhsParts = lhs.split('.');
419
+ if (lhsParts.length !== 3 || lhsParts[0] !== 'routing') {
420
+ throw new Error(`Expected routing.<tag>.<budget>, got "${lhs}".`);
421
+ }
422
+ const tag = lhsParts[1] ?? '';
423
+ const budget = lhsParts[2] ?? '';
424
+ if (!isRoutingTag(tag)) {
425
+ throw new Error(`Unknown routing tag "${tag}". Allowed: ${ROUTING_TAGS.join(', ')}.`);
426
+ }
427
+ if (!isRoutingBudget(budget)) {
428
+ throw new Error(`Unknown routing budget "${budget}". Allowed: ${ROUTING_BUDGETS.join(', ')}.`);
429
+ }
430
+ const { apiUrl, apiKey } = resolveAdminApi();
431
+ const result = await fetchJson(`${apiUrl}/api/admin/model-routing/overrides/${tag}/${budget}`, apiKey, { method: 'DELETE' });
432
+ ctx.writeOutput({
433
+ command: 'config.routing.unset',
434
+ tag,
435
+ budget,
436
+ removed: result.removed,
437
+ }, result.removed
438
+ ? `routing.${tag}.${budget} reverted to default.`
439
+ : `routing.${tag}.${budget} had no override (nothing to remove).`);
440
+ }
441
+ /* ------------------------------------------------------------------ */
442
+ /* alpha 6.13 privacy 3-mode - config.privacy.* subcommands */
443
+ /* ------------------------------------------------------------------ */
444
+ /**
445
+ * Closed mirror of the server-side PRIVACY_MODES enum
446
+ * (apps/admin-api/src/privacy/privacy-mode.ts). Pinning the literal
447
+ * set here lets the CLI reject typos client-side before the round-
448
+ * trip to admin-api (better UX, smaller blast radius on a flaky
449
+ * network).
450
+ */
451
+ const PRIVACY_MODES = ['strict', 'balanced', 'permissive'];
452
+ function isNewPrivacyModeValue(value) {
453
+ return typeof value === 'string' && PRIVACY_MODES.includes(value);
454
+ }
455
+ function isPrivacyMode(value) {
456
+ return PRIVACY_MODES.includes(value);
457
+ }
458
+ /**
459
+ * Legacy local-config privacy values from before alpha 6.13. Kept so
460
+ * `pugi config set privacy=local-only` continues to write to the local
461
+ * config file (matching the bare-form behaviour). Triple-review P2 fix
462
+ * (2026-05-25): the prior disambiguation only excluded the bare form;
463
+ * the `=` form routed to runPrivacySet and 4xx'd on the unknown mode.
464
+ */
465
+ const LEGACY_LOCAL_PRIVACY_VALUES = [
466
+ 'local-only',
467
+ 'metadata',
468
+ 'full',
469
+ ];
470
+ function isLegacyLocalPrivacyValue(value) {
471
+ return (typeof value === 'string' &&
472
+ LEGACY_LOCAL_PRIVACY_VALUES.includes(value));
473
+ }
474
+ /**
475
+ * `pugi config get privacy` - fetch the current privacy mode snapshot
476
+ * from /api/admin/privacy/mode + render it in human-readable form.
477
+ */
478
+ async function runPrivacyGet(ctx) {
479
+ const { apiUrl, apiKey } = resolveAdminApi();
480
+ const snapshot = await fetchJson(`${apiUrl}/api/admin/privacy/mode`, apiKey);
481
+ const lastUpdatedLine = snapshot.lastUpdated
482
+ ? `(last set by ${snapshot.lastUpdatedBy ?? 'unknown'} on ${snapshot.lastUpdated})`
483
+ : '(no flips recorded; on implicit default)';
484
+ const text = [
485
+ `privacy.mode = ${snapshot.mode}`,
486
+ `privacy.defaultMode = ${snapshot.defaultMode}`,
487
+ lastUpdatedLine,
488
+ ].join('\n');
489
+ ctx.writeOutput({
490
+ command: 'config.privacy.get',
491
+ apiUrl,
492
+ snapshot,
493
+ }, text);
494
+ }
495
+ /**
496
+ * `pugi config set privacy=<mode>` - PUT to /api/admin/privacy/mode.
497
+ * Validates the mode client-side against the closed set before
498
+ * round-tripping.
499
+ *
500
+ * Accepts both `privacy <mode>` and `privacy=<mode>` argument forms so
501
+ * the operator can type it either way.
502
+ */
503
+ async function runPrivacySet(args, ctx) {
504
+ const raw = args.join(' ').trim();
505
+ let mode;
506
+ if (raw.startsWith('privacy=')) {
507
+ mode = raw.slice('privacy='.length).trim();
508
+ }
509
+ else if (raw === 'privacy') {
510
+ throw new Error('pugi config set privacy requires a mode. Try: pugi config set privacy=balanced');
511
+ }
512
+ else if (raw.startsWith('privacy ')) {
513
+ mode = raw.slice('privacy '.length).trim();
514
+ }
515
+ else {
516
+ throw new Error(`pugi config set privacy: unrecognised argument "${raw}". Try: pugi config set privacy=balanced`);
517
+ }
518
+ if (mode.length === 0) {
519
+ throw new Error('pugi config set privacy requires a mode. Try: pugi config set privacy=balanced');
520
+ }
521
+ if (!isPrivacyMode(mode)) {
522
+ throw new Error(`Unknown privacy mode "${mode}". Allowed: ${PRIVACY_MODES.join(', ')}.`);
523
+ }
524
+ const { apiUrl, apiKey } = resolveAdminApi();
525
+ const snapshot = await fetchJson(`${apiUrl}/api/admin/privacy/mode`, apiKey, { method: 'PUT', body: { mode } });
526
+ ctx.writeOutput({
527
+ command: 'config.privacy.set',
528
+ mode: snapshot.mode,
529
+ snapshot,
530
+ }, `privacy.mode = ${snapshot.mode}`);
531
+ }
532
+ /**
533
+ * Thin authenticated fetch helper. Adds the bearer token + accepts JSON +
534
+ * surfaces structured errors. Uses undici `request` (not native `fetch`)
535
+ * because the test suite intercepts via `MockAgent` + `setGlobalDispatcher`
536
+ * — undici's `request` honours the global dispatcher reliably across the
537
+ * pinned undici version. Kept local (not shared with `pugi whoami`) so
538
+ * the routing surface is self-contained — extracting a common helper is
539
+ * α6.10b cleanup once we see two callers.
540
+ */
541
+ async function fetchJson(url, apiKey, options = {}) {
542
+ const method = options.method ?? 'GET';
543
+ const headers = {
544
+ authorization: `Bearer ${apiKey}`,
545
+ accept: 'application/json',
546
+ };
547
+ let body;
548
+ if (options.body !== undefined) {
549
+ body = JSON.stringify(options.body);
550
+ headers['content-type'] = 'application/json';
551
+ }
552
+ const res = await request(url, { method, headers, body });
553
+ if (res.statusCode < 200 || res.statusCode >= 300) {
554
+ const detail = await res.body.text().catch(() => '');
555
+ throw new Error(`pugi config routing: HTTP ${res.statusCode} on ${method} ${url}${detail ? ` -- ${detail.slice(0, 200)}` : ''}`);
556
+ }
557
+ // undici's `request` already returns `body` as a stream wrapped with
558
+ // helpers — `.json()` parses + closes for us.
559
+ return (await res.body.json());
560
+ }
231
561
  //# sourceMappingURL=config.js.map
@@ -0,0 +1,184 @@
1
+ /**
2
+ * `pugi lsp <op> <file> [args...]` — α7.7 Phase 1.
3
+ *
4
+ * Direct LSP queries from the CLI surface. Operators use this for
5
+ * debugging and scripting; the agent loop reaches the same operations
6
+ * via the `lsp_hover` / `lsp_definition` / `lsp_references` /
7
+ * `lsp_diagnostics` tool wrappers in `src/tools/lsp-tools.ts`.
8
+ *
9
+ * Supported subcommands:
10
+ *
11
+ * pugi lsp hover <file> <line> <col> [--lang ts|js|py|go|rust]
12
+ * pugi lsp definition <file> <line> <col> [--lang ...]
13
+ * pugi lsp references <file> <line> <col> [--lang ...]
14
+ * pugi lsp diagnostics <file> [--lang ...]
15
+ *
16
+ * When `--lang` is omitted we infer from the file extension. An unknown
17
+ * extension surfaces `language_unsupported` so the operator can specify
18
+ * the language explicitly.
19
+ *
20
+ * Lifecycle: we spawn an LSP server per invocation and stop it before
21
+ * returning. This is slow on cold start (TS server takes ~2-3s the
22
+ * first time) but the single-shot scripting path doesn't need a
23
+ * persistent daemon. Future work (α7.7b) wires a per-REPL daemon.
24
+ *
25
+ * Brand voice: ASCII only, no emoji, no banned words.
26
+ */
27
+ import { extname } from 'node:path';
28
+ import { startLspClient } from '../../core/lsp/client.js';
29
+ export async function runLspCommand(args, opts) {
30
+ const [op, file, ...rest] = args;
31
+ if (!op || !file) {
32
+ return usage();
33
+ }
34
+ if (!['hover', 'definition', 'references', 'diagnostics'].includes(op)) {
35
+ return {
36
+ ok: false,
37
+ text: `unknown lsp operation: ${op}. Supported: hover, definition, references, diagnostics`,
38
+ exitCode: 2,
39
+ };
40
+ }
41
+ const { lang: explicitLang, positional } = pullLangFlag(rest);
42
+ const lang = explicitLang ?? inferLanguage(file);
43
+ if (!lang) {
44
+ return {
45
+ ok: false,
46
+ text: `cannot infer language from ${file}; pass --lang ts|js|py|go|rust. ` +
47
+ `Supported extensions: .ts/.tsx, .js/.jsx/.mjs, .py, .go, .rs`,
48
+ exitCode: 2,
49
+ };
50
+ }
51
+ const clientResult = await startLspClient(lang, { cwd: opts.cwd });
52
+ if (!clientResult.ok) {
53
+ return {
54
+ ok: false,
55
+ text: `lsp_unavailable: ${clientResult.detail}`,
56
+ exitCode: 1,
57
+ };
58
+ }
59
+ const client = clientResult.value;
60
+ try {
61
+ if (op === 'diagnostics') {
62
+ const result = await client.diagnostics(file);
63
+ if (!result.ok) {
64
+ return { ok: false, text: `${result.reason}: ${result.detail}`, exitCode: 1 };
65
+ }
66
+ if (opts.json) {
67
+ return { ok: true, text: JSON.stringify(result.value, null, 2), exitCode: 0 };
68
+ }
69
+ if (result.value.length === 0) {
70
+ return { ok: true, text: `${file}: no diagnostics`, exitCode: 0 };
71
+ }
72
+ const lines = result.value.map((d) => `${d.severityLabel}\t${file}:${d.range.start.line + 1}:${d.range.start.character + 1}\t${d.message}`);
73
+ return { ok: true, text: lines.join('\n'), exitCode: 0 };
74
+ }
75
+ const line = Number.parseInt(positional[0] ?? '', 10);
76
+ const col = Number.parseInt(positional[1] ?? '', 10);
77
+ if (!Number.isFinite(line) || !Number.isFinite(col)) {
78
+ return {
79
+ ok: false,
80
+ text: `lsp ${op} requires <line> <col> arguments (1-based)`,
81
+ exitCode: 2,
82
+ };
83
+ }
84
+ // LSP positions are 0-based; we accept 1-based input from the CLI
85
+ // (matches every other editor convention) and convert here.
86
+ const pos = { line: Math.max(0, line - 1), character: Math.max(0, col - 1) };
87
+ if (op === 'hover') {
88
+ const result = await client.hover(file, pos);
89
+ if (!result.ok) {
90
+ return { ok: false, text: `${result.reason}: ${result.detail}`, exitCode: 1 };
91
+ }
92
+ if (opts.json) {
93
+ return { ok: true, text: JSON.stringify(result.value ?? null, null, 2), exitCode: 0 };
94
+ }
95
+ if (!result.value) {
96
+ return { ok: true, text: `${file}:${line}:${col}: no hover available`, exitCode: 0 };
97
+ }
98
+ return { ok: true, text: result.value.content, exitCode: 0 };
99
+ }
100
+ if (op === 'definition') {
101
+ const result = await client.definition(file, pos);
102
+ if (!result.ok) {
103
+ return { ok: false, text: `${result.reason}: ${result.detail}`, exitCode: 1 };
104
+ }
105
+ if (opts.json) {
106
+ return { ok: true, text: JSON.stringify(result.value, null, 2), exitCode: 0 };
107
+ }
108
+ const lines = result.value.map((loc) => `${loc.path || loc.uri}:${loc.range.start.line + 1}:${loc.range.start.character + 1}`);
109
+ return { ok: true, text: lines.join('\n') || 'no definition', exitCode: 0 };
110
+ }
111
+ // references
112
+ const result = await client.references(file, pos);
113
+ if (!result.ok) {
114
+ return { ok: false, text: `${result.reason}: ${result.detail}`, exitCode: 1 };
115
+ }
116
+ if (opts.json) {
117
+ return { ok: true, text: JSON.stringify(result.value, null, 2), exitCode: 0 };
118
+ }
119
+ const lines = result.value.map((loc) => `${loc.path || loc.uri}:${loc.range.start.line + 1}:${loc.range.start.character + 1}`);
120
+ return { ok: true, text: lines.join('\n') || 'no references', exitCode: 0 };
121
+ }
122
+ finally {
123
+ await client.stop();
124
+ }
125
+ }
126
+ function usage() {
127
+ return {
128
+ ok: false,
129
+ text: 'Usage: pugi lsp <op> <file> [line] [col] [--lang ts|js|py|go|rust]\n' +
130
+ ' pugi lsp hover <file> <line> <col>\n' +
131
+ ' pugi lsp definition <file> <line> <col>\n' +
132
+ ' pugi lsp references <file> <line> <col>\n' +
133
+ ' pugi lsp diagnostics <file>',
134
+ exitCode: 2,
135
+ };
136
+ }
137
+ function pullLangFlag(args) {
138
+ let lang;
139
+ const positional = [];
140
+ for (let i = 0; i < args.length; i += 1) {
141
+ const arg = args[i] ?? '';
142
+ if (arg === '--lang') {
143
+ const value = args[i + 1];
144
+ if (isLspLanguage(value))
145
+ lang = value;
146
+ i += 1;
147
+ continue;
148
+ }
149
+ if (arg.startsWith('--lang=')) {
150
+ const value = arg.slice('--lang='.length);
151
+ if (isLspLanguage(value))
152
+ lang = value;
153
+ continue;
154
+ }
155
+ positional.push(arg);
156
+ }
157
+ return { lang, positional };
158
+ }
159
+ function isLspLanguage(value) {
160
+ return value === 'ts' || value === 'js' || value === 'py' || value === 'go' || value === 'rust';
161
+ }
162
+ export function inferLanguage(file) {
163
+ const ext = extname(file).toLowerCase();
164
+ switch (ext) {
165
+ case '.ts':
166
+ case '.tsx':
167
+ return 'ts';
168
+ case '.js':
169
+ case '.jsx':
170
+ case '.mjs':
171
+ case '.cjs':
172
+ return 'js';
173
+ case '.py':
174
+ case '.pyi':
175
+ return 'py';
176
+ case '.go':
177
+ return 'go';
178
+ case '.rs':
179
+ return 'rust';
180
+ default:
181
+ return undefined;
182
+ }
183
+ }
184
+ //# sourceMappingURL=lsp.js.map
@@ -0,0 +1,111 @@
1
+ /**
2
+ * `pugi patch` — α7.7 Phase 1.
3
+ *
4
+ * Apply a unified-diff patch from stdin or a file. The dominant use is
5
+ * the `pugi patch < patch.diff` shell pattern that lets external tools
6
+ * (Codex, manual `git diff`) hand off changes through pugi's same
7
+ * security gate the layers use.
8
+ *
9
+ * Surface:
10
+ *
11
+ * pugi patch # read patch from stdin
12
+ * pugi patch <file.diff> # read patch from file
13
+ * pugi patch --dry-run # run --check only, report
14
+ * pugi patch --3way --base=<sha> # enable git apply --3way fuzz
15
+ *
16
+ * Exit codes:
17
+ *
18
+ * 0 patch applied (or dry-run check passed)
19
+ * 1 patch rejected (any non-security reason)
20
+ * 2 usage error
21
+ * 3 security gate refused the patch (path traversal / protected file / symlink escape)
22
+ *
23
+ * Distinct exit codes let CI loops differentiate "operator typo" from
24
+ * "model produced a hostile patch" — the latter is a security event
25
+ * worth alerting on.
26
+ *
27
+ * Brand voice: ASCII only, no emoji, no banned words.
28
+ */
29
+ import { readFileSync } from 'node:fs';
30
+ import { resolve } from 'node:path';
31
+ import { applyPatch } from '../../tools/apply-patch.js';
32
+ import { FileReadCache } from '../../core/file-cache.js';
33
+ import { openSession } from '../../core/session.js';
34
+ import { loadSettings } from '../../core/settings.js';
35
+ const SECURITY_REASONS = new Set(['path_outside_workspace', 'protected_file', 'symlink_escape']);
36
+ export async function runPatchCommand(args, opts) {
37
+ const positional = [];
38
+ const applyOpts = {};
39
+ for (let i = 0; i < args.length; i += 1) {
40
+ const arg = args[i] ?? '';
41
+ if (arg === '--dry-run')
42
+ applyOpts.dryRun = true;
43
+ else if (arg === '--3way') {
44
+ // honored only when --base is also supplied
45
+ }
46
+ else if (arg === '--base') {
47
+ const next = args[i + 1];
48
+ if (next)
49
+ applyOpts.baseSha = next;
50
+ i += 1;
51
+ }
52
+ else if (arg.startsWith('--base=')) {
53
+ applyOpts.baseSha = arg.slice('--base='.length);
54
+ }
55
+ else if (arg === '--json') {
56
+ // already parsed by the outer CLI
57
+ }
58
+ else {
59
+ positional.push(arg);
60
+ }
61
+ }
62
+ let patch;
63
+ try {
64
+ patch = await readPatchSource(positional[0], opts);
65
+ }
66
+ catch (error) {
67
+ const message = error instanceof Error ? error.message : String(error);
68
+ return failure({ ok: false, filesChanged: [], reason: 'invalid_patch', detail: message }, opts.json, 2);
69
+ }
70
+ const ctx = {
71
+ root: opts.cwd,
72
+ settings: loadSettings(opts.cwd),
73
+ session: openSession(opts.cwd),
74
+ readCache: new FileReadCache(),
75
+ };
76
+ const result = applyPatch(ctx, patch, applyOpts);
77
+ if (!result.ok) {
78
+ const exitCode = result.reason && SECURITY_REASONS.has(result.reason) ? 3 : 1;
79
+ return failure(result, opts.json, exitCode);
80
+ }
81
+ const text = opts.json
82
+ ? JSON.stringify(result, null, 2)
83
+ : `applied ${result.filesChanged.length} files:\n ${result.filesChanged.join('\n ')}`;
84
+ return { ok: true, text, exitCode: 0, result };
85
+ }
86
+ function failure(result, json, exitCode) {
87
+ const text = json
88
+ ? JSON.stringify(result, null, 2)
89
+ : `patch refused: ${result.reason ?? 'unknown'}${result.detail ? `\n ${result.detail}` : ''}`;
90
+ return { ok: false, text, exitCode, result };
91
+ }
92
+ async function readPatchSource(filePath, opts) {
93
+ if (filePath) {
94
+ const resolved = resolve(opts.cwd, filePath);
95
+ return readFileSync(resolved, 'utf8');
96
+ }
97
+ if (opts.stdinOverride !== undefined)
98
+ return opts.stdinOverride;
99
+ // Read all of stdin. The process pipe is the canonical CLI handoff
100
+ // for inbound diffs (e.g. `git diff origin/main | pugi patch`).
101
+ return new Promise((resolveFn, rejectFn) => {
102
+ let body = '';
103
+ process.stdin.setEncoding('utf8');
104
+ process.stdin.on('data', (chunk) => {
105
+ body += chunk;
106
+ });
107
+ process.stdin.on('end', () => resolveFn(body));
108
+ process.stdin.on('error', (error) => rejectFn(error));
109
+ });
110
+ }
111
+ //# sourceMappingURL=patch.js.map