@luanpdd/kit-mcp 1.35.0 → 1.36.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 (117) hide show
  1. package/bin/cli.js +2 -2
  2. package/bin/mcp.js +6 -6
  3. package/bin/ui.js +74 -74
  4. package/gates/ai-prompt-stability.md +120 -120
  5. package/gates/budget-description.md +68 -68
  6. package/gates/confidence.md +29 -29
  7. package/gates/dependency-check.md +33 -33
  8. package/gates/dept-cycle-prevention.md +179 -179
  9. package/gates/golden-signals-coverage.md +133 -133
  10. package/gates/legacy-refactor-safety.md +178 -178
  11. package/gates/multi-tenant-rls-coverage.md +102 -102
  12. package/gates/no-personal-uuid.md +72 -72
  13. package/gates/obs-agents-mcp-supabase.md +86 -86
  14. package/gates/obs-skills-frontmatter.md +76 -76
  15. package/gates/observability-coverage.md +151 -151
  16. package/gates/omm-no-regression.md +83 -83
  17. package/gates/postmortem-template-required.md +127 -127
  18. package/gates/prr-checklist-coverage.md +128 -128
  19. package/gates/regression.md +32 -32
  20. package/gates/release-pipeline-policy.md +132 -132
  21. package/gates/secrets-scan.md +33 -33
  22. package/gates/service-role-not-in-user-facing.md +113 -113
  23. package/gates/skill-must-include.md +71 -71
  24. package/gates/sync-idempotent.md +62 -62
  25. package/gates/verify-phase-goal.md +34 -34
  26. package/kit/agents/designer-ui.md +216 -216
  27. package/kit/agents/workflow-generator.md +537 -167
  28. package/kit/commands/adicionar-backlog.md +1 -1
  29. package/kit/commands/adicionar-fase.md +1 -1
  30. package/kit/commands/adicionar-tarefa.md +1 -1
  31. package/kit/commands/auditar-observabilidade.md +103 -103
  32. package/kit/commands/auditar-toil.md +129 -129
  33. package/kit/commands/caracterizar-prompt.md +195 -195
  34. package/kit/commands/criar-workflow.md +158 -158
  35. package/kit/commands/definir-perfil.md +1 -1
  36. package/kit/commands/definir-slo.md +108 -108
  37. package/kit/commands/fio.md +1 -1
  38. package/kit/commands/golden-signals.md +142 -142
  39. package/kit/commands/instrumentar-fase.md +200 -200
  40. package/kit/commands/investigar-producao.md +162 -162
  41. package/kit/commands/observabilidade.md +118 -118
  42. package/kit/commands/postmortem.md +179 -179
  43. package/kit/commands/prr.md +205 -205
  44. package/kit/commands/publicar-rapido.md +207 -207
  45. package/kit/commands/risk-budget.md +220 -220
  46. package/kit/commands/sre.md +230 -230
  47. package/kit/file-manifest.json +424 -424
  48. package/kit/framework/references/output-style.md +22 -22
  49. package/kit/hooks/post-apply-migration.js +199 -199
  50. package/kit/hooks/sidecar-tool-publisher.js +210 -210
  51. package/kit/skills/_shared-dados-distribuidos/glossary.md +224 -224
  52. package/kit/skills/_shared-legacy/glossary.md +389 -389
  53. package/kit/skills/_shared-multi-tenant/glossary.md +186 -186
  54. package/kit/skills/_shared-observability/glossary.md +396 -396
  55. package/kit/skills/_shared-sre/glossary.md +712 -712
  56. package/kit/skills/_shared-supabase/glossary.md +234 -234
  57. package/kit/skills/blameless-postmortems/SKILL.md +340 -340
  58. package/kit/skills/burn-rate-alerting/SKILL.md +258 -258
  59. package/kit/skills/cascading-failures/SKILL.md +311 -311
  60. package/kit/skills/core-analysis-loop/SKILL.md +352 -352
  61. package/kit/skills/distributed-tracing/SKILL.md +362 -362
  62. package/kit/skills/dynamic-workflow-authoring/SKILL.md +327 -223
  63. package/kit/skills/eliminating-toil/SKILL.md +243 -243
  64. package/kit/skills/event-based-slos/SKILL.md +296 -296
  65. package/kit/skills/four-golden-signals/SKILL.md +314 -314
  66. package/kit/skills/hermetic-builds/SKILL.md +323 -323
  67. package/kit/skills/legacy-monster-methods/SKILL.md +444 -444
  68. package/kit/skills/llm-as-dependency/SKILL.md +436 -436
  69. package/kit/skills/load-shedding-graceful-degradation/SKILL.md +396 -396
  70. package/kit/skills/observability-driven-development/SKILL.md +315 -315
  71. package/kit/skills/observability-maturity-model/SKILL.md +222 -222
  72. package/kit/skills/opentelemetry-standard/SKILL.md +351 -351
  73. package/kit/skills/production-readiness-review/SKILL.md +305 -305
  74. package/kit/skills/release-engineering/SKILL.md +367 -367
  75. package/kit/skills/retry-strategies/SKILL.md +372 -372
  76. package/kit/skills/sre-risk-management/SKILL.md +221 -221
  77. package/kit/skills/structured-events/SKILL.md +265 -265
  78. package/kit/skills/supabase-cron-queues/SKILL.md +275 -275
  79. package/kit/skills/supabase-database-functions/SKILL.md +332 -332
  80. package/kit/skills/supabase-declarative-schema/SKILL.md +183 -183
  81. package/kit/skills/supabase-pgvector-rag/SKILL.md +253 -253
  82. package/kit/skills/supabase-postgres-style/SKILL.md +138 -138
  83. package/kit/skills/supabase-storage/SKILL.md +234 -234
  84. package/kit/skills/telemetry-pipelines/SKILL.md +259 -259
  85. package/kit/skills/telemetry-sampling/SKILL.md +256 -256
  86. package/kit/skills/ui-anti-padroes-ia/SKILL.md +261 -261
  87. package/kit/skills/ui-contexto-produto/SKILL.md +248 -248
  88. package/kit/skills/ui-cor-estrategia/SKILL.md +213 -213
  89. package/kit/skills/ui-critica-auditoria/SKILL.md +260 -260
  90. package/kit/skills/ui-motion-funcional/SKILL.md +264 -264
  91. package/kit/skills/ui-ritmo-espacial/SKILL.md +259 -259
  92. package/kit/skills/ui-tipografia/SKILL.md +211 -211
  93. package/package.json +1 -1
  94. package/src/cli/index.js +1114 -1114
  95. package/src/cli/render.js +194 -194
  96. package/src/cli/upgrade-check.js +135 -135
  97. package/src/core/error-redaction.js +76 -76
  98. package/src/core/failures.js +153 -153
  99. package/src/core/gate-runner.js +205 -205
  100. package/src/core/gates.js +82 -82
  101. package/src/core/logger.js +170 -170
  102. package/src/core/manifest-verify.js +174 -174
  103. package/src/core/metrics.js +268 -268
  104. package/src/core/notify.js +60 -60
  105. package/src/core/path-safety.js +141 -141
  106. package/src/core/replays.js +120 -120
  107. package/src/core/ui.js +185 -185
  108. package/src/mcp-server/install.js +149 -149
  109. package/src/mcp-server/roots.js +124 -124
  110. package/src/ui/auto-spawn.js +113 -113
  111. package/src/ui/browser.js +78 -78
  112. package/src/ui/client.js +130 -130
  113. package/src/ui/events.js +65 -65
  114. package/src/ui/lockfile.js +191 -191
  115. package/src/ui/port.js +67 -67
  116. package/src/ui/server.js +547 -547
  117. package/src/ui/wrapper.js +129 -129
@@ -1,141 +1,141 @@
1
- // SEC-14-03: validate that a projectRoot supplied via MCP message points to a
2
- // real git workspace before any handler that writes to disk dispatches into
3
- // sync.js / reverse-sync.js.
4
- //
5
- // The helper is intentionally pure (no throw): MCP handlers package errors as
6
- // `{ error: <string> }` envelopes (see src/mcp-server/index.js handleSync,
7
- // handleGates, handleForensics — all use the same shape). Returning a discriminated
8
- // `{ ok, ...}` lets each caller decide between an envelope error or a CLI exit
9
- // without try/catch boilerplate.
10
- //
11
- // Why a directory-existence + walk-up `.git/` check (and not, say, spawning
12
- // `git rev-parse --show-toplevel`):
13
- // - Heuristic is good enough for our threat model. The attacker we are blocking
14
- // is "MCP message says projectRoot=\\evil-host\share or %APPDATA%". Both fail
15
- // the existence-or-`.git`-ancestor test trivially.
16
- // - No child_process means no dependency on `git` being on PATH at runtime, no
17
- // spawn latency on the hot path of every tool call, and no risk of the spawned
18
- // git itself reading config from an attacker-influenced cwd.
19
- // - The walk-up loop is bounded — Windows roots terminate at `D:\`, POSIX at
20
- // `/`, and `path.dirname(cur) === cur` is the universal fixed point. Typical
21
- // workspaces have <8 levels to a `.git/`, so a stat per level is fine.
22
- //
23
- // CLI does NOT call this — `bin/cli.js` trusts whoever invoked it (same trust
24
- // model as Phase 79.01's gates.run guard).
25
-
26
- import path from 'node:path';
27
- import fs from 'node:fs/promises';
28
-
29
- // All rejection reasons embed the literal "git workspace" — MCP clients (and
30
- // our own regression tests) match on that single sentinel regardless of which
31
- // check fired. Keeping the wording uniform means callers don't have to maintain
32
- // six regexes; one suffices.
33
- const SENTINEL = 'MCP sync requires projectRoot to be a git workspace';
34
-
35
- /**
36
- * SEC-14-03: validate that a `projectRoot` supplied via MCP message points to
37
- * a real git workspace before any handler dispatches into sync.js / reverse-sync.js.
38
- *
39
- * Pure function — never throws. Returns a discriminated union so MCP handlers
40
- * can wrap rejections in `{ error }` envelopes without try/catch boilerplate
41
- * (matches handleSync/handleGates/handleForensics in src/mcp-server/index.js).
42
- *
43
- * Validation chain (each step short-circuits on rejection):
44
- * 1. `projectRoot` is non-empty string (rejects nullish, empty, non-string types).
45
- * 2. `path.resolve()` collapses `..` segments and produces an absolute path.
46
- * 3. The resolved path exists and is a directory (UNC failures bubble up here).
47
- * 4. A `.git` entry exists somewhere in the ancestor chain (file or directory —
48
- * `git worktree` uses a file). Walk-up bounded by `path.dirname()` fixed point.
49
- *
50
- * The CLI does NOT call this — `bin/cli.js` trusts whoever invoked it (same
51
- * trust model as Phase 79.01's gates.run guard). Only MCP-message-sourced paths
52
- * need this check.
53
- *
54
- * Rejection reasons all embed the literal `"git workspace"` string — public
55
- * contract relied on by test/unit/mcp-projectroot-guard.test.js and downstream
56
- * MCP clients. Don't rephrase without coordinating callers.
57
- *
58
- * @param {unknown} projectRoot - the candidate path supplied by an MCP client.
59
- * Expected to be an absolute filesystem path; any other shape is rejected.
60
- * @returns {Promise<{ok: true, resolvedPath: string} | {ok: false, reason: string}>}
61
- * On success, `resolvedPath` is the path-resolved absolute form of `projectRoot`
62
- * (callers should use it instead of the raw input). On failure, `reason` is a
63
- * human-readable string suitable for MCP `{error}` envelopes.
64
- */
65
- export async function validateProjectRoot(projectRoot) {
66
- // Reject empty / nullish up-front. We require an explicit projectRoot from
67
- // MCP messages — falling back to `process.cwd()` of the MCP server would let
68
- // an attacker probe wherever the server happened to be launched.
69
- if (projectRoot === undefined || projectRoot === null || projectRoot === '') {
70
- return {
71
- ok: false,
72
- reason: SENTINEL + '; got <empty> (pass an absolute path to a git workspace)',
73
- };
74
- }
75
- if (typeof projectRoot !== 'string') {
76
- return {
77
- ok: false,
78
- reason: SENTINEL + '; got non-string projectRoot of type ' + typeof projectRoot,
79
- };
80
- }
81
-
82
- // path.resolve normalises separators and collapses `..` segments so a later
83
- // attacker payload like `C:\Users\\..\evil` is reduced before the existence
84
- // check happens. resolve() is also a no-op on already-absolute paths.
85
- const resolved = path.resolve(projectRoot);
86
-
87
- // Defensive — path.resolve should always return absolute, but if a future
88
- // Node version changes that we still want to reject.
89
- if (!path.isAbsolute(resolved)) {
90
- return {
91
- ok: false,
92
- reason: SENTINEL + '; projectRoot did not resolve to an absolute path: ' + projectRoot,
93
- };
94
- }
95
-
96
- // The stat doubles as an existence + reachability check. UNC paths to
97
- // unreachable hosts (`\\evil-host\share`) reject here on Windows with ENOENT
98
- // / EHOSTUNREACH within milliseconds; Node treats both as a rejection so we
99
- // never proceed to write a single byte.
100
- let stat;
101
- try {
102
- stat = await fs.stat(resolved);
103
- } catch {
104
- return {
105
- ok: false,
106
- reason: SENTINEL + '; projectRoot does not exist or is unreachable: ' + resolved,
107
- };
108
- }
109
-
110
- if (!stat.isDirectory()) {
111
- return {
112
- ok: false,
113
- reason: SENTINEL + '; projectRoot must be a directory: ' + resolved,
114
- };
115
- }
116
-
117
- // Walk up looking for `.git` (file or directory — `git worktree` uses a file).
118
- // Bounded by the dirname fixed-point check so this terminates on every OS.
119
- let cur = resolved;
120
- // eslint-disable-next-line no-constant-condition
121
- while (true) {
122
- try {
123
- await fs.stat(path.join(cur, '.git'));
124
- return { ok: true, resolvedPath: resolved };
125
- } catch {
126
- // not here — keep walking up
127
- }
128
- const parent = path.dirname(cur);
129
- if (parent === cur) break;
130
- cur = parent;
131
- }
132
-
133
- // No .git/ found anywhere in the chain — the canonical reject. The literal
134
- // "git workspace" string is part of the public contract — tests
135
- // (test/unit/mcp-projectroot-guard.test.js) and downstream MCP clients match
136
- // on it. Don't rephrase without coordinating callers.
137
- return {
138
- ok: false,
139
- reason: SENTINEL + '; got ' + projectRoot,
140
- };
141
- }
1
+ // SEC-14-03: validate that a projectRoot supplied via MCP message points to a
2
+ // real git workspace before any handler that writes to disk dispatches into
3
+ // sync.js / reverse-sync.js.
4
+ //
5
+ // The helper is intentionally pure (no throw): MCP handlers package errors as
6
+ // `{ error: <string> }` envelopes (see src/mcp-server/index.js handleSync,
7
+ // handleGates, handleForensics — all use the same shape). Returning a discriminated
8
+ // `{ ok, ...}` lets each caller decide between an envelope error or a CLI exit
9
+ // without try/catch boilerplate.
10
+ //
11
+ // Why a directory-existence + walk-up `.git/` check (and not, say, spawning
12
+ // `git rev-parse --show-toplevel`):
13
+ // - Heuristic is good enough for our threat model. The attacker we are blocking
14
+ // is "MCP message says projectRoot=\\evil-host\share or %APPDATA%". Both fail
15
+ // the existence-or-`.git`-ancestor test trivially.
16
+ // - No child_process means no dependency on `git` being on PATH at runtime, no
17
+ // spawn latency on the hot path of every tool call, and no risk of the spawned
18
+ // git itself reading config from an attacker-influenced cwd.
19
+ // - The walk-up loop is bounded — Windows roots terminate at `D:\`, POSIX at
20
+ // `/`, and `path.dirname(cur) === cur` is the universal fixed point. Typical
21
+ // workspaces have <8 levels to a `.git/`, so a stat per level is fine.
22
+ //
23
+ // CLI does NOT call this — `bin/cli.js` trusts whoever invoked it (same trust
24
+ // model as Phase 79.01's gates.run guard).
25
+
26
+ import path from 'node:path';
27
+ import fs from 'node:fs/promises';
28
+
29
+ // All rejection reasons embed the literal "git workspace" — MCP clients (and
30
+ // our own regression tests) match on that single sentinel regardless of which
31
+ // check fired. Keeping the wording uniform means callers don't have to maintain
32
+ // six regexes; one suffices.
33
+ const SENTINEL = 'MCP sync requires projectRoot to be a git workspace';
34
+
35
+ /**
36
+ * SEC-14-03: validate that a `projectRoot` supplied via MCP message points to
37
+ * a real git workspace before any handler dispatches into sync.js / reverse-sync.js.
38
+ *
39
+ * Pure function — never throws. Returns a discriminated union so MCP handlers
40
+ * can wrap rejections in `{ error }` envelopes without try/catch boilerplate
41
+ * (matches handleSync/handleGates/handleForensics in src/mcp-server/index.js).
42
+ *
43
+ * Validation chain (each step short-circuits on rejection):
44
+ * 1. `projectRoot` is non-empty string (rejects nullish, empty, non-string types).
45
+ * 2. `path.resolve()` collapses `..` segments and produces an absolute path.
46
+ * 3. The resolved path exists and is a directory (UNC failures bubble up here).
47
+ * 4. A `.git` entry exists somewhere in the ancestor chain (file or directory —
48
+ * `git worktree` uses a file). Walk-up bounded by `path.dirname()` fixed point.
49
+ *
50
+ * The CLI does NOT call this — `bin/cli.js` trusts whoever invoked it (same
51
+ * trust model as Phase 79.01's gates.run guard). Only MCP-message-sourced paths
52
+ * need this check.
53
+ *
54
+ * Rejection reasons all embed the literal `"git workspace"` string — public
55
+ * contract relied on by test/unit/mcp-projectroot-guard.test.js and downstream
56
+ * MCP clients. Don't rephrase without coordinating callers.
57
+ *
58
+ * @param {unknown} projectRoot - the candidate path supplied by an MCP client.
59
+ * Expected to be an absolute filesystem path; any other shape is rejected.
60
+ * @returns {Promise<{ok: true, resolvedPath: string} | {ok: false, reason: string}>}
61
+ * On success, `resolvedPath` is the path-resolved absolute form of `projectRoot`
62
+ * (callers should use it instead of the raw input). On failure, `reason` is a
63
+ * human-readable string suitable for MCP `{error}` envelopes.
64
+ */
65
+ export async function validateProjectRoot(projectRoot) {
66
+ // Reject empty / nullish up-front. We require an explicit projectRoot from
67
+ // MCP messages — falling back to `process.cwd()` of the MCP server would let
68
+ // an attacker probe wherever the server happened to be launched.
69
+ if (projectRoot === undefined || projectRoot === null || projectRoot === '') {
70
+ return {
71
+ ok: false,
72
+ reason: SENTINEL + '; got <empty> (pass an absolute path to a git workspace)',
73
+ };
74
+ }
75
+ if (typeof projectRoot !== 'string') {
76
+ return {
77
+ ok: false,
78
+ reason: SENTINEL + '; got non-string projectRoot of type ' + typeof projectRoot,
79
+ };
80
+ }
81
+
82
+ // path.resolve normalises separators and collapses `..` segments so a later
83
+ // attacker payload like `C:\Users\\..\evil` is reduced before the existence
84
+ // check happens. resolve() is also a no-op on already-absolute paths.
85
+ const resolved = path.resolve(projectRoot);
86
+
87
+ // Defensive — path.resolve should always return absolute, but if a future
88
+ // Node version changes that we still want to reject.
89
+ if (!path.isAbsolute(resolved)) {
90
+ return {
91
+ ok: false,
92
+ reason: SENTINEL + '; projectRoot did not resolve to an absolute path: ' + projectRoot,
93
+ };
94
+ }
95
+
96
+ // The stat doubles as an existence + reachability check. UNC paths to
97
+ // unreachable hosts (`\\evil-host\share`) reject here on Windows with ENOENT
98
+ // / EHOSTUNREACH within milliseconds; Node treats both as a rejection so we
99
+ // never proceed to write a single byte.
100
+ let stat;
101
+ try {
102
+ stat = await fs.stat(resolved);
103
+ } catch {
104
+ return {
105
+ ok: false,
106
+ reason: SENTINEL + '; projectRoot does not exist or is unreachable: ' + resolved,
107
+ };
108
+ }
109
+
110
+ if (!stat.isDirectory()) {
111
+ return {
112
+ ok: false,
113
+ reason: SENTINEL + '; projectRoot must be a directory: ' + resolved,
114
+ };
115
+ }
116
+
117
+ // Walk up looking for `.git` (file or directory — `git worktree` uses a file).
118
+ // Bounded by the dirname fixed-point check so this terminates on every OS.
119
+ let cur = resolved;
120
+ // eslint-disable-next-line no-constant-condition
121
+ while (true) {
122
+ try {
123
+ await fs.stat(path.join(cur, '.git'));
124
+ return { ok: true, resolvedPath: resolved };
125
+ } catch {
126
+ // not here — keep walking up
127
+ }
128
+ const parent = path.dirname(cur);
129
+ if (parent === cur) break;
130
+ cur = parent;
131
+ }
132
+
133
+ // No .git/ found anywhere in the chain — the canonical reject. The literal
134
+ // "git workspace" string is part of the public contract — tests
135
+ // (test/unit/mcp-projectroot-guard.test.js) and downstream MCP clients match
136
+ // on it. Don't rephrase without coordinating callers.
137
+ return {
138
+ ok: false,
139
+ reason: SENTINEL + '; got ' + projectRoot,
140
+ };
141
+ }
@@ -1,120 +1,120 @@
1
- // Replays — capture Task() payloads so an agent can be re-run with the same
2
- // inputs but an updated prompt. Tight feedback loop for iterating on agent
3
- // definitions without re-running the whole workflow.
4
- //
5
- // Storage: .planning/replays/{phase}-{plan?}-{timestamp}-{agent}.json
6
- //
7
- // Payload shape:
8
- // {
9
- // id, agent, phase?, plan?, timestamp,
10
- // subagent_type, model, isolation,
11
- // prompt, files_to_read, agent_skills,
12
- // outcome?: { status, notes }
13
- // }
14
-
15
- import path from 'node:path';
16
- import fs from 'node:fs/promises';
17
- import { redactSecrets } from './error-redaction.js';
18
-
19
- const REPLAY_DIR_REL = path.join('.planning', 'replays');
20
-
21
- // SEC-13-02: replayId path traversal guard. The MCP forensics tool exposes
22
- // load-replay/annotate-replay/record-replay actions; without sanitization,
23
- // a malicious replayId like '../../../etc/passwd' would read/write files
24
- // outside .planning/replays/.
25
- //
26
- // Strategy: allowlist regex (no slashes, no '..', no NUL) + post-resolve assertion
27
- // that the final path stays inside REPLAY_DIR_REL.
28
- const REPLAY_ID_RE = /^[A-Za-z0-9_.-]+$/;
29
-
30
- function validateReplayId(id) {
31
- if (typeof id !== 'string' || !id) {
32
- throw new Error('invalid replay id: must be a non-empty string');
33
- }
34
- if (id === '.' || id === '..' || id.includes('..')) {
35
- throw new Error('invalid replay id: traversal sequences not allowed');
36
- }
37
- if (!REPLAY_ID_RE.test(id)) {
38
- throw new Error(`invalid replay id: only [A-Za-z0-9_.-] allowed, got ${JSON.stringify(id)}`);
39
- }
40
- return id;
41
- }
42
-
43
- function assertPathInside(filePath, baseDir) {
44
- const resolved = path.resolve(filePath);
45
- const base = path.resolve(baseDir);
46
- // Ensure resolved is base or a child of base (handle trailing-sep edge case).
47
- if (resolved !== base && !resolved.startsWith(base + path.sep)) {
48
- throw new Error('invalid replay id: resolved path escapes replay directory');
49
- }
50
- return resolved;
51
- }
52
-
53
- export async function recordReplay(payload, opts = {}) {
54
- const projectRoot = path.resolve(opts.projectRoot ?? process.cwd());
55
- const dir = path.join(projectRoot, REPLAY_DIR_REL);
56
- await fs.mkdir(dir, { recursive: true });
57
-
58
- const ts = new Date().toISOString().replace(/[:.]/g, '-');
59
- // SEC-13-02: validate each slug component independently before concat
60
- const slugParts = [payload.phase, payload.plan, payload.agent].filter(Boolean);
61
- for (const part of slugParts) {
62
- validateReplayId(String(part));
63
- }
64
- const slug = slugParts.join('-') || 'unknown';
65
- const id = `${ts}-${slug}`;
66
- // Re-validate the full id (defense in depth — ts is well-formed but cheap to check)
67
- validateReplayId(id);
68
- const file = path.join(dir, `${id}.json`);
69
- assertPathInside(file, dir);
70
-
71
- const record = { id, recorded_at: new Date().toISOString(), ...payload };
72
- // SEC-14-06: scrub the serialized form before writing. We redact AFTER
73
- // JSON.stringify (rather than deep-mapping the payload tree) so the regex
74
- // walks the entire structure including nested args/headers/env, and so
75
- // the in-memory `record` returned to the caller stays unmutated. Only the
76
- // on-disk artifact is scrubbed; readers of the file via loadReplay see
77
- // the redacted form, which is the desired outcome — secrets must not be
78
- // re-loaded into memory either.
79
- const json = redactSecrets(JSON.stringify(record, null, 2));
80
- await fs.writeFile(file, json, 'utf8');
81
- return { id, file, record };
82
- }
83
-
84
- export async function listReplays(opts = {}) {
85
- const projectRoot = path.resolve(opts.projectRoot ?? process.cwd());
86
- const dir = path.join(projectRoot, REPLAY_DIR_REL);
87
- let entries;
88
- try { entries = await fs.readdir(dir); } catch { return []; }
89
- const items = [];
90
- for (const e of entries) {
91
- if (!e.endsWith('.json')) continue;
92
- try {
93
- const r = JSON.parse(await fs.readFile(path.join(dir, e), 'utf8'));
94
- items.push({ id: r.id, agent: r.agent, phase: r.phase, plan: r.plan, recorded_at: r.recorded_at });
95
- } catch {}
96
- }
97
- return items.sort((a, b) => (b.recorded_at ?? '').localeCompare(a.recorded_at ?? ''));
98
- }
99
-
100
- export async function loadReplay(id, opts = {}) {
101
- validateReplayId(id);
102
- const projectRoot = path.resolve(opts.projectRoot ?? process.cwd());
103
- const dir = path.join(projectRoot, REPLAY_DIR_REL);
104
- const file = path.join(dir, `${id}.json`);
105
- assertPathInside(file, dir);
106
- const raw = await fs.readFile(file, 'utf8');
107
- return JSON.parse(raw);
108
- }
109
-
110
- export async function annotateReplay(id, outcome, opts = {}) {
111
- validateReplayId(id);
112
- const projectRoot = path.resolve(opts.projectRoot ?? process.cwd());
113
- const dir = path.join(projectRoot, REPLAY_DIR_REL);
114
- const file = path.join(dir, `${id}.json`);
115
- assertPathInside(file, dir);
116
- const r = JSON.parse(await fs.readFile(file, 'utf8'));
117
- r.outcome = { ...(r.outcome ?? {}), ...outcome, annotated_at: new Date().toISOString() };
118
- await fs.writeFile(file, JSON.stringify(r, null, 2), 'utf8');
119
- return r;
120
- }
1
+ // Replays — capture Task() payloads so an agent can be re-run with the same
2
+ // inputs but an updated prompt. Tight feedback loop for iterating on agent
3
+ // definitions without re-running the whole workflow.
4
+ //
5
+ // Storage: .planning/replays/{phase}-{plan?}-{timestamp}-{agent}.json
6
+ //
7
+ // Payload shape:
8
+ // {
9
+ // id, agent, phase?, plan?, timestamp,
10
+ // subagent_type, model, isolation,
11
+ // prompt, files_to_read, agent_skills,
12
+ // outcome?: { status, notes }
13
+ // }
14
+
15
+ import path from 'node:path';
16
+ import fs from 'node:fs/promises';
17
+ import { redactSecrets } from './error-redaction.js';
18
+
19
+ const REPLAY_DIR_REL = path.join('.planning', 'replays');
20
+
21
+ // SEC-13-02: replayId path traversal guard. The MCP forensics tool exposes
22
+ // load-replay/annotate-replay/record-replay actions; without sanitization,
23
+ // a malicious replayId like '../../../etc/passwd' would read/write files
24
+ // outside .planning/replays/.
25
+ //
26
+ // Strategy: allowlist regex (no slashes, no '..', no NUL) + post-resolve assertion
27
+ // that the final path stays inside REPLAY_DIR_REL.
28
+ const REPLAY_ID_RE = /^[A-Za-z0-9_.-]+$/;
29
+
30
+ function validateReplayId(id) {
31
+ if (typeof id !== 'string' || !id) {
32
+ throw new Error('invalid replay id: must be a non-empty string');
33
+ }
34
+ if (id === '.' || id === '..' || id.includes('..')) {
35
+ throw new Error('invalid replay id: traversal sequences not allowed');
36
+ }
37
+ if (!REPLAY_ID_RE.test(id)) {
38
+ throw new Error(`invalid replay id: only [A-Za-z0-9_.-] allowed, got ${JSON.stringify(id)}`);
39
+ }
40
+ return id;
41
+ }
42
+
43
+ function assertPathInside(filePath, baseDir) {
44
+ const resolved = path.resolve(filePath);
45
+ const base = path.resolve(baseDir);
46
+ // Ensure resolved is base or a child of base (handle trailing-sep edge case).
47
+ if (resolved !== base && !resolved.startsWith(base + path.sep)) {
48
+ throw new Error('invalid replay id: resolved path escapes replay directory');
49
+ }
50
+ return resolved;
51
+ }
52
+
53
+ export async function recordReplay(payload, opts = {}) {
54
+ const projectRoot = path.resolve(opts.projectRoot ?? process.cwd());
55
+ const dir = path.join(projectRoot, REPLAY_DIR_REL);
56
+ await fs.mkdir(dir, { recursive: true });
57
+
58
+ const ts = new Date().toISOString().replace(/[:.]/g, '-');
59
+ // SEC-13-02: validate each slug component independently before concat
60
+ const slugParts = [payload.phase, payload.plan, payload.agent].filter(Boolean);
61
+ for (const part of slugParts) {
62
+ validateReplayId(String(part));
63
+ }
64
+ const slug = slugParts.join('-') || 'unknown';
65
+ const id = `${ts}-${slug}`;
66
+ // Re-validate the full id (defense in depth — ts is well-formed but cheap to check)
67
+ validateReplayId(id);
68
+ const file = path.join(dir, `${id}.json`);
69
+ assertPathInside(file, dir);
70
+
71
+ const record = { id, recorded_at: new Date().toISOString(), ...payload };
72
+ // SEC-14-06: scrub the serialized form before writing. We redact AFTER
73
+ // JSON.stringify (rather than deep-mapping the payload tree) so the regex
74
+ // walks the entire structure including nested args/headers/env, and so
75
+ // the in-memory `record` returned to the caller stays unmutated. Only the
76
+ // on-disk artifact is scrubbed; readers of the file via loadReplay see
77
+ // the redacted form, which is the desired outcome — secrets must not be
78
+ // re-loaded into memory either.
79
+ const json = redactSecrets(JSON.stringify(record, null, 2));
80
+ await fs.writeFile(file, json, 'utf8');
81
+ return { id, file, record };
82
+ }
83
+
84
+ export async function listReplays(opts = {}) {
85
+ const projectRoot = path.resolve(opts.projectRoot ?? process.cwd());
86
+ const dir = path.join(projectRoot, REPLAY_DIR_REL);
87
+ let entries;
88
+ try { entries = await fs.readdir(dir); } catch { return []; }
89
+ const items = [];
90
+ for (const e of entries) {
91
+ if (!e.endsWith('.json')) continue;
92
+ try {
93
+ const r = JSON.parse(await fs.readFile(path.join(dir, e), 'utf8'));
94
+ items.push({ id: r.id, agent: r.agent, phase: r.phase, plan: r.plan, recorded_at: r.recorded_at });
95
+ } catch {}
96
+ }
97
+ return items.sort((a, b) => (b.recorded_at ?? '').localeCompare(a.recorded_at ?? ''));
98
+ }
99
+
100
+ export async function loadReplay(id, opts = {}) {
101
+ validateReplayId(id);
102
+ const projectRoot = path.resolve(opts.projectRoot ?? process.cwd());
103
+ const dir = path.join(projectRoot, REPLAY_DIR_REL);
104
+ const file = path.join(dir, `${id}.json`);
105
+ assertPathInside(file, dir);
106
+ const raw = await fs.readFile(file, 'utf8');
107
+ return JSON.parse(raw);
108
+ }
109
+
110
+ export async function annotateReplay(id, outcome, opts = {}) {
111
+ validateReplayId(id);
112
+ const projectRoot = path.resolve(opts.projectRoot ?? process.cwd());
113
+ const dir = path.join(projectRoot, REPLAY_DIR_REL);
114
+ const file = path.join(dir, `${id}.json`);
115
+ assertPathInside(file, dir);
116
+ const r = JSON.parse(await fs.readFile(file, 'utf8'));
117
+ r.outcome = { ...(r.outcome ?? {}), ...outcome, annotated_at: new Date().toISOString() };
118
+ await fs.writeFile(file, JSON.stringify(r, null, 2), 'utf8');
119
+ return r;
120
+ }