@massu/core 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/commands/README.md +23 -11
  2. package/commands/massu-deploy.python-docker.md +170 -0
  3. package/commands/massu-deploy.python-fly.md +189 -0
  4. package/commands/massu-deploy.python-launchd.md +144 -0
  5. package/commands/massu-deploy.python-systemd.md +163 -0
  6. package/commands/massu-scaffold-page.swift.md +10 -10
  7. package/commands/massu-scaffold-router.python-django.md +153 -0
  8. package/commands/massu-scaffold-router.python-fastapi.md +145 -0
  9. package/dist/cli.js +9914 -4133
  10. package/dist/hooks/auto-learning-pipeline.js +45 -2
  11. package/dist/hooks/classify-failure.js +45 -2
  12. package/dist/hooks/cost-tracker.js +45 -2
  13. package/dist/hooks/fix-detector.js +45 -2
  14. package/dist/hooks/incident-pipeline.js +45 -2
  15. package/dist/hooks/post-edit-context.js +45 -2
  16. package/dist/hooks/post-tool-use.js +45 -2
  17. package/dist/hooks/pre-compact.js +45 -2
  18. package/dist/hooks/pre-delete-check.js +45 -2
  19. package/dist/hooks/quality-event.js +45 -2
  20. package/dist/hooks/rule-enforcement-pipeline.js +45 -2
  21. package/dist/hooks/session-end.js +45 -2
  22. package/dist/hooks/session-start.js +4790 -406
  23. package/dist/hooks/user-prompt.js +45 -2
  24. package/package.json +13 -4
  25. package/src/cli.ts +22 -2
  26. package/src/commands/config-refresh.ts +91 -23
  27. package/src/commands/init.ts +131 -24
  28. package/src/commands/install-commands.ts +142 -26
  29. package/src/commands/refresh-log.ts +37 -0
  30. package/src/commands/template-engine.ts +260 -0
  31. package/src/commands/watch.ts +430 -0
  32. package/src/config.ts +71 -0
  33. package/src/detect/adapters/nextjs-trpc.ts +166 -0
  34. package/src/detect/adapters/parse-guard.ts +133 -0
  35. package/src/detect/adapters/python-django.ts +208 -0
  36. package/src/detect/adapters/python-fastapi.ts +223 -0
  37. package/src/detect/adapters/query-helpers.ts +170 -0
  38. package/src/detect/adapters/runner.ts +252 -0
  39. package/src/detect/adapters/swift-swiftui.ts +171 -0
  40. package/src/detect/adapters/tree-sitter-loader.ts +467 -0
  41. package/src/detect/adapters/types.ts +173 -0
  42. package/src/detect/codebase-introspector.ts +190 -0
  43. package/src/detect/index.ts +28 -2
  44. package/src/detect/migrate.ts +4 -4
  45. package/src/detect/regex-fallback.ts +449 -0
  46. package/src/hooks/session-start.ts +94 -3
  47. package/src/lib/gitToplevel.ts +22 -0
  48. package/src/lib/installLock.ts +179 -0
  49. package/src/lib/pidLiveness.ts +67 -0
  50. package/src/lsp/auto-detect.ts +98 -0
  51. package/src/lsp/client.ts +776 -0
  52. package/src/lsp/enrich.ts +127 -0
  53. package/src/lsp/types.ts +221 -0
  54. package/src/watch/daemon.ts +385 -0
  55. package/src/watch/lockfile-detector.ts +65 -0
  56. package/src/watch/paths.ts +279 -0
  57. package/src/watch/state.ts +178 -0
@@ -0,0 +1,179 @@
1
+ // Copyright (c) 2026 Massu. All rights reserved.
2
+ // Licensed under BSL 1.1 - see LICENSE file for details.
3
+
4
+ /**
5
+ * Synchronous file lock around installAll() for cross-process safety.
6
+ *
7
+ * Plan 3a Phase 6: installAll() may now be invoked from BOTH the manual
8
+ * `runConfigRefresh` path AND the watcher auto-trigger. Without
9
+ * serialization, two concurrent callers can race on `.claude/commands/`
10
+ * file writes. proper-lockfile gives us atomic mkdir-based locks that
11
+ * work cross-platform; we wrap it to:
12
+ *
13
+ * 1. mkdirSync the lock dir (fresh repos may not have `.massu/`)
14
+ * 2. surface ELOCKED (POSIX) and EBUSY (Windows) as the same error
15
+ * 3. keep installAll() synchronous (lockSync, not lock)
16
+ *
17
+ * Plan §190 retry behavior: "second caller blocks up to 30s, then bails".
18
+ * proper-lockfile's `lockSync` REJECTS `retries>0` (see node_modules/
19
+ * proper-lockfile/lib/adapter.js: `Cannot use retries with the sync api`).
20
+ * We implement the retry-block manually via a `lockfile.checkSync` /
21
+ * `lockSync` loop with a busy-wait sleep.
22
+ *
23
+ * iter-3 (third pass, G3-iter3-1+2): align error message with plan §243
24
+ * format `"installAll already running (PID=X) — try again in <N>s"` AND
25
+ * add the manual retry-block loop.
26
+ */
27
+
28
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'fs';
29
+ import { dirname, resolve } from 'path';
30
+ import * as lockfile from 'proper-lockfile';
31
+
32
+ export interface InstallLockOpts {
33
+ /** Default 30s — proper-lockfile considers a lock stale after this elapses. */
34
+ staleMs?: number;
35
+ /**
36
+ * How long the manual retry loop should block waiting for the holder to
37
+ * release before bailing with `InstallLockBusyError`. Default 30s per
38
+ * plan §190 ("second caller blocks up to 30s, then bails").
39
+ * Pass `0` to bail immediately (used in tests).
40
+ */
41
+ blockMs?: number;
42
+ /** Sleep granularity inside the retry loop. Default 100ms. */
43
+ pollIntervalMs?: number;
44
+ /**
45
+ * Backwards-compat: legacy callers pass `retries: 0` to mean "do not
46
+ * block". When set to a positive integer, used by tests that want to
47
+ * exercise a specific retry count instead of the default time-based loop.
48
+ */
49
+ retries?: number;
50
+ /** Override clock (test seam). */
51
+ now?: () => number;
52
+ /** Override sleep (test seam). Defaults to a busy-wait spinloop. */
53
+ sleep?: (ms: number) => void;
54
+ }
55
+
56
+ export class InstallLockBusyError extends Error {
57
+ constructor(
58
+ public lockPath: string,
59
+ public holderPid: number | null,
60
+ public retryAfterSeconds: number,
61
+ public causeCode?: string,
62
+ ) {
63
+ const pidPart = holderPid != null ? `(PID=${holderPid})` : '(PID=unknown)';
64
+ super(`installAll already running ${pidPart} — try again in ${retryAfterSeconds}s`);
65
+ this.name = 'InstallLockBusyError';
66
+ }
67
+ }
68
+
69
+ /**
70
+ * Best-effort: read the PID of the current lock holder. proper-lockfile
71
+ * stores the lock as a directory at `<lockPath>` containing nothing PID-
72
+ * identifying, so we look at our own sidecar `<lockPath>.pid` file (written
73
+ * by the lock acquirer below). On any read error we return null so the
74
+ * error message degrades gracefully to `(PID=unknown)`.
75
+ */
76
+ function readHolderPid(lockPath: string): number | null {
77
+ try {
78
+ const raw = readFileSync(`${lockPath}.pid`, 'utf-8').trim();
79
+ const pid = Number.parseInt(raw, 10);
80
+ if (!Number.isFinite(pid) || pid <= 0) return null;
81
+ return pid;
82
+ } catch {
83
+ return null;
84
+ }
85
+ }
86
+
87
+ function busyWaitSync(ms: number): void {
88
+ const end = Date.now() + ms;
89
+ // Atomics.wait against a SharedArrayBuffer is the cleanest portable sync
90
+ // sleep; fall back to a tight loop if SharedArrayBuffer is unavailable
91
+ // (older runtimes / sandboxed envs).
92
+ if (typeof SharedArrayBuffer !== 'undefined' && typeof Atomics !== 'undefined') {
93
+ const sab = new SharedArrayBuffer(4);
94
+ const view = new Int32Array(sab);
95
+ Atomics.wait(view, 0, 0, ms);
96
+ return;
97
+ }
98
+ while (Date.now() < end) {
99
+ // Spin — this should never run on modern Node, kept as belt-and-suspenders.
100
+ }
101
+ }
102
+
103
+ /**
104
+ * Acquire the lock, run `fn`, release on every exit path.
105
+ * Synchronous all the way through so installAll() keeps its sync signature.
106
+ */
107
+ export function withInstallLock<T>(projectRoot: string, fn: () => T, opts: InstallLockOpts = {}): T {
108
+ const lockPath = resolve(projectRoot, '.massu', 'installAll.lock');
109
+ // iter-3 G3-A11: ensure parent dir exists (fresh repo case).
110
+ mkdirSync(dirname(lockPath), { recursive: true });
111
+
112
+ const staleMs = opts.staleMs ?? 30_000;
113
+ // `retries: 0` legacy path = bail immediately, no wait.
114
+ // Otherwise default to plan §190's 30s block.
115
+ const blockMs = opts.retries === 0
116
+ ? 0
117
+ : (opts.blockMs ?? 30_000);
118
+ const pollIntervalMs = opts.pollIntervalMs ?? 100;
119
+ const now = opts.now ?? Date.now;
120
+ const sleep = opts.sleep ?? busyWaitSync;
121
+
122
+ let release: (() => void) | null = null;
123
+ const deadline = now() + blockMs;
124
+ let lastErr: NodeJS.ErrnoException | null = null;
125
+
126
+ // Manual retry loop. proper-lockfile.lockSync forbids retries>0, so we
127
+ // wrap it ourselves: try → on ELOCKED/EBUSY, sleep → try again until
128
+ // deadline. This satisfies plan §190 "second caller blocks up to 30s".
129
+ for (;;) {
130
+ try {
131
+ release = lockfile.lockSync(lockPath, {
132
+ stale: staleMs,
133
+ retries: 0,
134
+ realpath: false,
135
+ });
136
+ // Persist our PID alongside the lock so the next contender can include
137
+ // it in the user-friendly error per plan §243 format.
138
+ try {
139
+ writeFileSync(`${lockPath}.pid`, String(process.pid), 'utf-8');
140
+ } catch {
141
+ // best-effort
142
+ }
143
+ break;
144
+ } catch (err) {
145
+ lastErr = err as NodeJS.ErrnoException;
146
+ const code = lastErr.code;
147
+ if (code !== 'ELOCKED' && code !== 'EBUSY') {
148
+ throw err;
149
+ }
150
+ if (now() >= deadline) {
151
+ const holderPid = readHolderPid(lockPath);
152
+ const remainingMs = Math.max(0, deadline - now());
153
+ // Surface a hint about how long the *next* poll cycle should wait.
154
+ // When `blockMs=0` the user got bail-immediately semantics; report
155
+ // the staleness window so they know the lock auto-releases in N s.
156
+ const retryAfterSeconds = blockMs === 0
157
+ ? Math.round(staleMs / 1000)
158
+ : Math.round(remainingMs / 1000);
159
+ throw new InstallLockBusyError(lockPath, holderPid, retryAfterSeconds, code);
160
+ }
161
+ sleep(pollIntervalMs);
162
+ }
163
+ }
164
+
165
+ try {
166
+ return fn();
167
+ } finally {
168
+ try {
169
+ if (release) release();
170
+ } catch {
171
+ // best-effort
172
+ }
173
+ try {
174
+ rmSync(`${lockPath}.pid`, { force: true });
175
+ } catch {
176
+ // best-effort
177
+ }
178
+ }
179
+ }
@@ -0,0 +1,67 @@
1
+ // Copyright (c) 2026 Massu. All rights reserved.
2
+ // Licensed under BSL 1.1 - see LICENSE file for details.
3
+
4
+ /**
5
+ * Cross-platform PID liveness probe.
6
+ *
7
+ * POSIX (macOS / Linux):
8
+ * process.kill(pid, 0) → no-throw == alive; ESRCH → dead; EPERM → alive
9
+ * (the process exists but we lack permission to signal it).
10
+ *
11
+ * Windows:
12
+ * `tasklist /FI "PID eq <pid>" /NH` and grep for the PID. Best-effort.
13
+ *
14
+ * Returns boolean; never throws. Used by hooks/session-start.ts
15
+ * (banner suppression) and watch/daemon.ts (registry sweep).
16
+ */
17
+
18
+ import { spawnSync } from 'child_process';
19
+
20
+ interface ProbeOpts {
21
+ /** When set, override `process.platform` (test seam). */
22
+ platformOverride?: NodeJS.Platform;
23
+ /** When set, override `process.kill` (test seam). */
24
+ killOverride?: (pid: number, signal: number) => boolean;
25
+ }
26
+
27
+ export function isPidAlive(pid: number, opts: ProbeOpts = {}): boolean {
28
+ if (!Number.isFinite(pid) || pid <= 0) return false;
29
+
30
+ const platform = opts.platformOverride ?? process.platform;
31
+
32
+ if (platform === 'win32') {
33
+ return checkWindows(pid);
34
+ }
35
+ return checkPosix(pid, opts.killOverride);
36
+ }
37
+
38
+ function checkPosix(pid: number, killOverride?: (pid: number, signal: number) => boolean): boolean {
39
+ try {
40
+ if (killOverride) {
41
+ killOverride(pid, 0);
42
+ } else {
43
+ process.kill(pid, 0);
44
+ }
45
+ return true;
46
+ } catch (err) {
47
+ const code = (err as NodeJS.ErrnoException).code;
48
+ if (code === 'EPERM') return true;
49
+ // ESRCH or anything else → treat as dead.
50
+ return false;
51
+ }
52
+ }
53
+
54
+ function checkWindows(pid: number): boolean {
55
+ try {
56
+ const res = spawnSync('tasklist', ['/FI', `PID eq ${pid}`, '/NH'], {
57
+ encoding: 'utf-8',
58
+ windowsHide: true,
59
+ });
60
+ if (res.error || res.status !== 0) return false;
61
+ const stdout = res.stdout || '';
62
+ // Each match is a line that starts with the image name and includes the PID.
63
+ return new RegExp(`\\b${pid}\\b`).test(stdout);
64
+ } catch {
65
+ return false;
66
+ }
67
+ }
@@ -0,0 +1,98 @@
1
+ // Copyright (c) 2026 Massu. All rights reserved.
2
+ // Licensed under BSL 1.1 - see LICENSE file for details.
3
+
4
+ /**
5
+ * Plan 3b — Phase 4: LSP server discovery.
6
+ *
7
+ * Per audit-iter-1 fix G4: this module's discovery is **explicit-only by
8
+ * default**. The optional `lsof` port-scan path is GATED behind
9
+ * `lsp.autoDetect.viaPortScan: true` and defaults to `false` (port-scanning
10
+ * local processes is a security-sensitive default — opt-in only at v1).
11
+ *
12
+ * Empty-servers edge case (audit-iter-3 fix Z): when `lsp.enabled: true` AND
13
+ * `lsp.servers` is empty AND `viaPortScan: false`, we log ONE informational
14
+ * stderr line and return an empty list — the caller (`enrich.ts`) then
15
+ * proceeds AST-only without throwing.
16
+ *
17
+ * VR-LSP-AUTODETECT-OFF-BY-DEFAULT: `viaPortScan` MUST be checked BEFORE any
18
+ * `lsof` invocation. The grep `grep -nE 'viaPortScan' auto-detect.ts` MUST
19
+ * show that boolean check ahead of any `lsof` call.
20
+ */
21
+
22
+ import type { LSPConfig } from '../config.ts';
23
+ import type { LSPServerSpec } from './client.ts';
24
+
25
+ /**
26
+ * Find LSP servers to launch / connect to. Pure config-driven by default.
27
+ *
28
+ * @param config - The `lsp` block from `massu.config.yaml`. May be undefined
29
+ * when LSP is not configured at all (returns empty list silently).
30
+ * @returns A list of `LSPServerSpec` ready to feed `LSPClient.fromCommand()`.
31
+ * Empty list is a valid, non-error outcome — callers MUST proceed AST-only.
32
+ */
33
+ export async function findRunningLSPs(
34
+ config: LSPConfig | undefined
35
+ ): Promise<LSPServerSpec[]> {
36
+ // Disabled or absent: silently no-op (no log).
37
+ if (!config || !config.enabled) {
38
+ return [];
39
+ }
40
+
41
+ const explicit = (config.servers ?? []).map((s) => splitCommand(s));
42
+
43
+ // VR-LSP-AUTODETECT-OFF-BY-DEFAULT: this boolean check happens BEFORE any
44
+ // `lsof`/port-scan invocation. Default is false — explicit-only path.
45
+ const viaPortScan = config.autoDetect?.viaPortScan === true;
46
+
47
+ if (explicit.length === 0 && !viaPortScan) {
48
+ // Empty-servers edge case: enabled but nothing configured AND auto-detect
49
+ // is off. Log once, proceed AST-only.
50
+ process.stderr.write(
51
+ '[massu/lsp] INFO: LSP enabled but no servers configured and auto-detect off — skipping LSP enrichment.\n'
52
+ );
53
+ return [];
54
+ }
55
+
56
+ // Port-scan path is opt-in via `viaPortScan: true`. Implementation
57
+ // intentionally minimal at v1 — emits an INFO stderr line and returns
58
+ // explicit servers only. Plan 3d will flesh out actual `lsof` discovery
59
+ // once the threat model is reviewed.
60
+ if (viaPortScan) {
61
+ process.stderr.write(
62
+ '[massu/lsp] INFO: lsp.autoDetect.viaPortScan is enabled but port-scan auto-detect is reserved for Plan 3d — using explicit servers only.\n'
63
+ );
64
+ // (No `lsof` invocation yet. The viaPortScan gate exists so future
65
+ // implementations slot in here without changing the default surface.)
66
+ }
67
+
68
+ return explicit;
69
+ }
70
+
71
+ /**
72
+ * Parse a config-string `command` into an `LSPServerSpec`. Splits on
73
+ * whitespace (no shell evaluation, no globbing). Strict path validation
74
+ * happens later in `LSPClient.fromCommand()` — this just parses the shape.
75
+ *
76
+ * Note: callers passing untrusted commands MUST review the result before
77
+ * passing it to `LSPClient.fromCommand`. The factory rejects relative paths
78
+ * and `..`-containing argv elements.
79
+ */
80
+ function splitCommand(server: {
81
+ language: string;
82
+ command: string;
83
+ allow_setuid?: boolean;
84
+ max_rss_mb?: number;
85
+ }): LSPServerSpec {
86
+ const cmd = (server.command ?? '').trim();
87
+ // Whitespace split — not a full shell parser. Quoted args with spaces are
88
+ // not supported at v1; users with such commands should run a wrapper script.
89
+ const argv = cmd.length === 0 ? [] : cmd.split(/\s+/);
90
+ return {
91
+ language: server.language,
92
+ argv,
93
+ // F-014 / F-015 (closed 2026-05-06): pass through the security knobs
94
+ // from config so the spawn surface enforces them.
95
+ allowSetuid: server.allow_setuid ?? false,
96
+ maxRssMb: server.max_rss_mb ?? undefined,
97
+ };
98
+ }