development-companion 1.7.0 → 1.8.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.
- package/CHANGELOG.md +56 -0
- package/README.md +114 -32
- package/RELEASE.md +41 -24
- package/adapters/README.md +11 -5
- package/adapters/opencode/README.md +87 -12
- package/adapters/opencode/plugin/devcomp/gates.mjs +688 -0
- package/adapters/opencode/plugin/devcomp/index.ts +487 -7
- package/core/guidelines/coordination.md +138 -4
- package/core/process.md +141 -7
- package/core/quality-gates.md +41 -1
- package/core/roles/README.md +4 -1
- package/core/roles/backend-engineer.md +10 -0
- package/core/roles/coordinator.md +83 -25
- package/core/roles/desktop-linux-engineer.md +10 -0
- package/core/roles/desktop-macos-engineer.md +10 -0
- package/core/roles/desktop-windows-engineer.md +10 -0
- package/core/roles/frontend-engineer.md +10 -0
- package/core/roles/mobile-engineer.md +10 -0
- package/core/roles/multiplatform-engineer.md +10 -0
- package/core/roles/sre-engineer.md +10 -0
- package/core/workflow.md +62 -9
- package/package.json +1 -1
- package/skills/delivery-orchestration/SKILL.md +58 -3
- package/skills/development-workflow/SKILL.md +44 -8
- package/skills/test-strategy/SKILL.md +12 -0
- package/src/cli.mjs +86 -6
- package/src/install.mjs +106 -21
- package/templates/artifacts/01-operational-brief.md +14 -1
- package/templates/artifacts/11-feature-plan.md +83 -0
- package/templates/artifacts/README.md +8 -5
- package/templates/rules/AGENTS.block.md +99 -10
|
@@ -0,0 +1,688 @@
|
|
|
1
|
+
import { existsSync, realpathSync, statSync } from "node:fs";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { basename, dirname, isAbsolute, relative, resolve } from "node:path";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Pure gates for the Development Companion runtime adapter.
|
|
7
|
+
*
|
|
8
|
+
* The plugin imports these functions; the tests import them directly. Keep this module free
|
|
9
|
+
* of OpenCode types so it can run under plain Node.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
function normalizeText(text) {
|
|
13
|
+
return String(text ?? "").replace(/\s+/g, " ").trim();
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const AFFIRMATIVE_PLAN_APPROVAL =
|
|
17
|
+
/^(?:s[ií]|si|yes|approved?|aprobad[oa]|dale|adelante|ok(?:ay)?)(?=\s|$|[.,;:!—–-])/i;
|
|
18
|
+
|
|
19
|
+
const APPROVAL_VERB =
|
|
20
|
+
/\b(?:apruebo|aprobamos|aprueba|aprobad[oa]|approve|approved|dale|adelante|procede|proceed|go\s+ahead|lgtm|ship\s+it)\b/i;
|
|
21
|
+
const PLAN_WORD = /\b(?:plan|planes|propuesta|enfoque|approach)\b/i;
|
|
22
|
+
const STRONG_APPROVAL = /\b(?:sin\s+observaciones|me\s+parece\s+bien|lgtm|ship\s+it|go\s+ahead|proceed)\b/i;
|
|
23
|
+
const OBSERVATION =
|
|
24
|
+
/\b(?:observaciones|cambia|cambiar|corrige|ajusta|revisa|rechazo|rechazado|rechazada|espera|detente|vistazo|change|changes|changed|fix|fixes|adjust|adjusts|review|reviews|wait|stop|later|maybe|nope|not\s+approved|not\s+yet|no)\b/i;
|
|
25
|
+
// For approval detection, a delegation instruction is excluded separately. A stray "no" in
|
|
26
|
+
// unrelated text ("no leas nada") must not turn a real approval into an observation.
|
|
27
|
+
const APPROVAL_OBSERVATION =
|
|
28
|
+
/\b(?:observaciones|cambia|cambiar|corrige|ajusta|revisa|rechazo|espera|detente|vistazo|change|changes|changed|fix|fixes|adjust|adjusts|review|reviews|wait|stop|later|maybe|nope|not\s+approved|not\s+yet)\b/i;
|
|
29
|
+
|
|
30
|
+
const NEGATIVE_APPROVAL = [
|
|
31
|
+
/\bno\s+(?:lo\s+)?(?:apruebo|aprobado|aprobada|approve|approved)\b/i,
|
|
32
|
+
/\b(?:no\s+est[áa]|no\s+fue|no\s+ha\s+sido)\s+aprobad[oa]\b/i,
|
|
33
|
+
/\bnot\s+approved\b/i,
|
|
34
|
+
/\bnot\s+yet\b/i,
|
|
35
|
+
/\b(?:nope|maybe|later|wait)\b/i,
|
|
36
|
+
/\b(?:rechazo|rechazado|rechazada|rejected)\b/i,
|
|
37
|
+
/\bno\s+estoy\s+de\s+acuerdo\b/i,
|
|
38
|
+
/\bno\s+procede\b/i,
|
|
39
|
+
/\bm[áa]s\s+adelante\b/i
|
|
40
|
+
];
|
|
41
|
+
|
|
42
|
+
const PAST_OR_NARRATIVE = [
|
|
43
|
+
/\b(?:estaba|estuvo|era|fue|han?\s+sido)\s+aprobad[oa]\b/i,
|
|
44
|
+
/\baprobad[oa]\s+en\s+otra\s+sesi[oó]n\b/i,
|
|
45
|
+
/\bwas\s+(?:it\s+)?approved\b/i
|
|
46
|
+
];
|
|
47
|
+
|
|
48
|
+
const INTERROGATIVE = /[?¿]/;
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* A user message marks the session as approved. Heuristic on purpose: the plan gate still
|
|
52
|
+
* requires a plan file whose `Aprobado:` is affirmative.
|
|
53
|
+
*/
|
|
54
|
+
export function isApprovalMessage(text) {
|
|
55
|
+
const value = normalizeText(text);
|
|
56
|
+
if (!value) return false;
|
|
57
|
+
// A delegation instruction is not an approval, even if its description says "approved".
|
|
58
|
+
if (/\bPlan\s*:/i.test(value) && /\bScope\s*:/i.test(value)) return false;
|
|
59
|
+
if (INTERROGATIVE.test(value)) return false;
|
|
60
|
+
if (NEGATIVE_APPROVAL.some((pattern) => pattern.test(value))) return false;
|
|
61
|
+
if (PAST_OR_NARRATIVE.some((pattern) => pattern.test(value))) return false;
|
|
62
|
+
|
|
63
|
+
// Observation language wins over a strong phrase: "sin observaciones, pero cambia..." is
|
|
64
|
+
// not an approval. The literal "sin observaciones" is removed first so it still approves.
|
|
65
|
+
const withoutNoObservation = value.replace(/\bsin\s+observaciones\b/gi, "");
|
|
66
|
+
if (APPROVAL_OBSERVATION.test(withoutNoObservation)) return false;
|
|
67
|
+
if (STRONG_APPROVAL.test(value)) return true;
|
|
68
|
+
|
|
69
|
+
const words = value.replace(/[.!;:—–-]+/g, " ").replace(/\s+/g, " ").trim();
|
|
70
|
+
if (!/[a-záéíóúñ]/i.test(words)) return false;
|
|
71
|
+
if (/^(?:ok|okay|oki|okey)$/i.test(words)) return true;
|
|
72
|
+
if (/^(?:s[ií]|si|yes|apruebo|aprobamos|aprobado|aprobada|approved?|dale|adelante|procede|proceed)$/i.test(words)) {
|
|
73
|
+
return true;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// A message made only of approval words ("dale, adelante", "ok dale") is an approval.
|
|
77
|
+
const remainder = words
|
|
78
|
+
.replace(/\b(?:s[ií]|si|yes|apruebo|aprobamos|aprueba|aprobad[oa]|approve|approved|dale|adelante|procede|proceed|ok|okay|oki|okey|y|and)\b/gi, "")
|
|
79
|
+
.replace(/[^a-záéíóúñ]+/gi, "")
|
|
80
|
+
.trim();
|
|
81
|
+
if (remainder === "") return true;
|
|
82
|
+
|
|
83
|
+
// Multi-word messages need an approval verb and a plan reference.
|
|
84
|
+
if (APPROVAL_VERB.test(words) && PLAN_WORD.test(words)) return true;
|
|
85
|
+
if (/\bok\b/i.test(words) && PLAN_WORD.test(words)) return true;
|
|
86
|
+
return false;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Observation or rejection language revokes a previously recorded session approval.
|
|
91
|
+
*/
|
|
92
|
+
export function isObservationMessage(text) {
|
|
93
|
+
const value = normalizeText(text);
|
|
94
|
+
if (!value) return false;
|
|
95
|
+
if (isApprovalMessage(value)) return false;
|
|
96
|
+
// A delegation instruction contains Plan/Scope and often "no leas nada más"; it must not
|
|
97
|
+
// revoke the approval that authorized it.
|
|
98
|
+
if (/\bPlan\s*:/i.test(value) && /\bScope\s*:/i.test(value)) return false;
|
|
99
|
+
return OBSERVATION.test(value);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* The prompt hook's state transition: approve, revoke, or leave unchanged.
|
|
104
|
+
*/
|
|
105
|
+
export function approvalStateChange(text) {
|
|
106
|
+
if (isApprovalMessage(text)) return "set";
|
|
107
|
+
if (isObservationMessage(text)) return "clear";
|
|
108
|
+
return "keep";
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function stripToken(value) {
|
|
112
|
+
return String(value ?? "")
|
|
113
|
+
.trim()
|
|
114
|
+
.replace(/^`+|`+$/g, "")
|
|
115
|
+
.replace(/^["']+|["']+$/g, "")
|
|
116
|
+
.replace(/^<\/?[^>]+>$/g, "")
|
|
117
|
+
.trim();
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function field(text, name) {
|
|
121
|
+
const pattern = new RegExp(
|
|
122
|
+
`^[ \\t]*(?:[-*][ \\t]+)?(?:\\*\\*)?${name}(?:\\*\\*)?[ \\t]*:[ \\t]*(?:\\*\\*)?[ \\t]*(.+)$`,
|
|
123
|
+
"im"
|
|
124
|
+
);
|
|
125
|
+
const match = String(text ?? "").match(pattern);
|
|
126
|
+
return match ? match[1] : null;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function parseScope(text) {
|
|
130
|
+
if (text === null || text === undefined) return [];
|
|
131
|
+
return String(text)
|
|
132
|
+
.split(/[,\n;]+/)
|
|
133
|
+
.flatMap((part) => part.trim().split(/\s+/))
|
|
134
|
+
.map(stripToken)
|
|
135
|
+
.filter(Boolean);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Extract `Plan:` and `Scope:` from a delegation prompt. `missing` lists what the runtime
|
|
140
|
+
* plan gate must reject.
|
|
141
|
+
*/
|
|
142
|
+
export function parseDelegation(text) {
|
|
143
|
+
const plan = field(text, "Plan");
|
|
144
|
+
const scopeText = field(text, "Scope");
|
|
145
|
+
const scope = parseScope(scopeText);
|
|
146
|
+
const missing = [];
|
|
147
|
+
if (!plan || !stripToken(plan)) missing.push("Plan");
|
|
148
|
+
if (scope.length === 0) missing.push("Scope");
|
|
149
|
+
return {
|
|
150
|
+
planPath: plan ? stripToken(plan) : null,
|
|
151
|
+
scope,
|
|
152
|
+
step: field(text, "Step")?.trim() ?? null,
|
|
153
|
+
acceptance: field(text, "Acceptance")?.trim() ?? null,
|
|
154
|
+
missing
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* `Aprobado:` must be affirmative. A denylist let "not yet", "maybe", "wait" and "0" pass.
|
|
160
|
+
*/
|
|
161
|
+
export function readPlanApproval(content) {
|
|
162
|
+
const pattern = /^[ \t]*(?:[-*][ \t]+)?(?:\*\*)?Aprobado(?:\*\*)?[ \t]*:[ \t]*(?:\*\*)?[ \t]*(.*)$/im;
|
|
163
|
+
const match = String(content ?? "").match(pattern);
|
|
164
|
+
if (!match) return { approved: false, value: null };
|
|
165
|
+
const value = match[1].replace(/\*+/g, "").trim();
|
|
166
|
+
return { approved: AFFIRMATIVE_PLAN_APPROVAL.test(value), value };
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export function isPlanApproved(content) {
|
|
170
|
+
return readPlanApproval(content).approved;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function tableCells(line) {
|
|
174
|
+
const trimmed = line.trim();
|
|
175
|
+
if (!trimmed.startsWith("|")) return null;
|
|
176
|
+
return trimmed.replace(/^\|/, "").replace(/\|$/, "").split("|").map((cell) => cell.trim());
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Read the plan's scope declarations: the top-level `Scope:` line and the `Scope` column of the
|
|
181
|
+
* development plan table. The table entries are narrowed per step.
|
|
182
|
+
*/
|
|
183
|
+
export function parsePlanScope(content) {
|
|
184
|
+
const declared = parseScope(field(content, "Scope"));
|
|
185
|
+
const steps = [];
|
|
186
|
+
let hasTable = false;
|
|
187
|
+
let header = null;
|
|
188
|
+
let scopeIndex = -1;
|
|
189
|
+
let stepIndex = -1;
|
|
190
|
+
let agentIndex = -1;
|
|
191
|
+
|
|
192
|
+
for (const line of String(content ?? "").split(/\r?\n/)) {
|
|
193
|
+
const cells = tableCells(line);
|
|
194
|
+
if (!cells) {
|
|
195
|
+
header = null;
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
if (!header) {
|
|
199
|
+
const lower = cells.map((cell) => cell.toLowerCase());
|
|
200
|
+
const scopeColumn = lower.findIndex((cell) => cell === "scope");
|
|
201
|
+
if (scopeColumn === -1) continue;
|
|
202
|
+
header = cells;
|
|
203
|
+
hasTable = true;
|
|
204
|
+
scopeIndex = scopeColumn;
|
|
205
|
+
stepIndex = lower.findIndex((cell) => cell === "#" || cell === "step" || cell === "paso");
|
|
206
|
+
agentIndex = lower.findIndex((cell) => cell === "agent" || cell === "agente");
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
if (cells.every((cell) => /^:?-{3,}:?$/.test(cell))) continue;
|
|
210
|
+
const scope = parseScope(cells[scopeIndex] ?? "");
|
|
211
|
+
if (scope.length === 0) continue;
|
|
212
|
+
steps.push({
|
|
213
|
+
step: stepIndex >= 0 ? stripToken(cells[stepIndex] ?? "") : "",
|
|
214
|
+
agent: agentIndex >= 0 ? stripToken(cells[agentIndex] ?? "") : "",
|
|
215
|
+
scope
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
return { declared, steps, hasTable };
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
function sameStep(rowStep, delegationStep) {
|
|
223
|
+
if (!rowStep || !delegationStep) return false;
|
|
224
|
+
const row = rowStep.toLowerCase().trim();
|
|
225
|
+
const step = delegationStep.toLowerCase().trim();
|
|
226
|
+
return step === row || step.startsWith(`${row} `) || step.startsWith(`${row}:`);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* The scope that bounds a delegation. A plan with a development table requires a Step and a
|
|
231
|
+
* row whose Step and declared agent match; only a table-less plan (a short brief) falls back to
|
|
232
|
+
* the top-level Scope.
|
|
233
|
+
*/
|
|
234
|
+
export function planScopeFor(content, { step, agent } = {}) {
|
|
235
|
+
const parsed = parsePlanScope(content);
|
|
236
|
+
if (parsed.declared.length === 0) {
|
|
237
|
+
return { tokens: [], ambiguous: false, source: "none", error: "the plan declares no top-level `Scope:`" };
|
|
238
|
+
}
|
|
239
|
+
if (!parsed.hasTable) {
|
|
240
|
+
return { tokens: parsed.declared, ambiguous: false, source: "plan" };
|
|
241
|
+
}
|
|
242
|
+
if (!step) {
|
|
243
|
+
return {
|
|
244
|
+
tokens: [],
|
|
245
|
+
ambiguous: false,
|
|
246
|
+
source: "missing-step",
|
|
247
|
+
error: "the plan has a development table; `Step:` is required"
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
const role = String(agent ?? "").toLowerCase().trim();
|
|
252
|
+
const rows = parsed.steps.filter((row) => sameStep(row.step, step));
|
|
253
|
+
if (rows.length === 0) {
|
|
254
|
+
return {
|
|
255
|
+
tokens: [],
|
|
256
|
+
ambiguous: false,
|
|
257
|
+
source: "no-row",
|
|
258
|
+
error: `the plan has no development row for Step ${step}`
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
const matching = rows.filter((row) => !row.agent || !role || row.agent.toLowerCase() === role);
|
|
263
|
+
if (matching.length === 0) {
|
|
264
|
+
const agents = [...new Set(rows.map((row) => row.agent).filter(Boolean))].join(", ");
|
|
265
|
+
return {
|
|
266
|
+
tokens: [],
|
|
267
|
+
ambiguous: true,
|
|
268
|
+
source: "agent",
|
|
269
|
+
error: `the plan row for Step ${step} names ${agents || "another agent"}, not ${role}`
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
if (matching.length === 1) {
|
|
273
|
+
return { tokens: matching[0].scope, ambiguous: false, source: "step" };
|
|
274
|
+
}
|
|
275
|
+
const exact = role ? matching.filter((row) => row.agent.toLowerCase() === role) : [];
|
|
276
|
+
if (exact.length === 1) {
|
|
277
|
+
return { tokens: exact[0].scope, ambiguous: false, source: "step" };
|
|
278
|
+
}
|
|
279
|
+
return {
|
|
280
|
+
tokens: [],
|
|
281
|
+
ambiguous: true,
|
|
282
|
+
source: "ambiguous",
|
|
283
|
+
error: `more than one development row matches Step ${step}${role ? ` and ${role}` : ""}`
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
function normalizeScope(value) {
|
|
288
|
+
return String(value ?? "").trim().replace(/\\/g, "/").replace(/^\.\//, "").replace(/\/+$/, "");
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* True when the requested token cannot exceed the allowed token. The supported narrowing is
|
|
293
|
+
* equality, `prefix/**` (any descendant) and a single-segment `prefix/*`.
|
|
294
|
+
*/
|
|
295
|
+
export function isScopeSubset(requested, allowed) {
|
|
296
|
+
const request = normalizeScope(requested);
|
|
297
|
+
const allow = normalizeScope(allowed);
|
|
298
|
+
if (!request || !allow) return false;
|
|
299
|
+
if (request === allow) return true;
|
|
300
|
+
if (allow === "**") return true;
|
|
301
|
+
if (allow.endsWith("/**")) {
|
|
302
|
+
const prefix = allow.slice(0, -3);
|
|
303
|
+
if (request === prefix) return true;
|
|
304
|
+
if (!request.startsWith(`${prefix}/`)) return false;
|
|
305
|
+
return !request.includes("..");
|
|
306
|
+
}
|
|
307
|
+
if (allow.endsWith("/*")) {
|
|
308
|
+
const prefix = allow.slice(0, -2);
|
|
309
|
+
if (!request.startsWith(`${prefix}/`)) return false;
|
|
310
|
+
const rest = request.slice(prefix.length + 1);
|
|
311
|
+
return rest.length > 0 && !rest.includes("/") && !rest.includes("**");
|
|
312
|
+
}
|
|
313
|
+
return false;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* A plan must be more than an approval line. Scope is mandatory so a delegation can be bounded.
|
|
318
|
+
*/
|
|
319
|
+
export function validatePlanContent(content) {
|
|
320
|
+
const text = String(content ?? "");
|
|
321
|
+
const compact = text.replace(/\s+/g, " ").trim();
|
|
322
|
+
if (compact.length < 200) {
|
|
323
|
+
return { ok: false, reason: "plan is too short; include problem, scope, acceptance and evidence" };
|
|
324
|
+
}
|
|
325
|
+
const scope = parsePlanScope(text);
|
|
326
|
+
if (scope.declared.length === 0) {
|
|
327
|
+
return { ok: false, reason: "plan has no top-level `Scope:` line" };
|
|
328
|
+
}
|
|
329
|
+
if (!/\b(?:test|testing|prueba|verification|verify|evidence|evidencia)\b/i.test(text)) {
|
|
330
|
+
return {
|
|
331
|
+
ok: false,
|
|
332
|
+
reason: "plan has no Test, Verification, or Evidence content; a Scope and approval alone are not a plan"
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
return { ok: true, scope };
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* A plan approval is bound to the plan content the user saw. Any later content change, or a
|
|
340
|
+
* different plan in the same session, revokes the mark and requires a new approval.
|
|
341
|
+
*/
|
|
342
|
+
export function planContentHash(content) {
|
|
343
|
+
return createHash("sha256").update(String(content ?? ""), "utf8").digest("hex");
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
export function planRevisionDecision(binding, next, approved) {
|
|
347
|
+
if (!approved) return { action: "fallback" };
|
|
348
|
+
if (!binding) return { action: "bind" };
|
|
349
|
+
if (binding.path !== next.path) return { action: "different-plan", previousPath: binding.path };
|
|
350
|
+
if (binding.hash !== next.hash) return { action: "changed" };
|
|
351
|
+
return { action: "same" };
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* Resolve a plan path. It must exist, be a regular file, and stay inside the workspace even
|
|
356
|
+
* after resolving symlinks.
|
|
357
|
+
*/
|
|
358
|
+
export function resolvePlan({ planPath, workspaceRoot, cwd = workspaceRoot, fs = {} }) {
|
|
359
|
+
const exists = fs.exists ?? existsSync;
|
|
360
|
+
const realpath = fs.realpath ?? realpathSync;
|
|
361
|
+
const stat = fs.stat ?? statSync;
|
|
362
|
+
|
|
363
|
+
const cleaned = stripToken(planPath);
|
|
364
|
+
if (!cleaned) return { ok: false, reason: "Plan path is empty" };
|
|
365
|
+
if (cleaned.includes("\0") || /^[a-z][a-z0-9+.-]*:\/\//i.test(cleaned)) {
|
|
366
|
+
return { ok: false, reason: "Plan must be a local file path" };
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
const root = resolve(workspaceRoot);
|
|
370
|
+
const candidates = isAbsolute(cleaned)
|
|
371
|
+
? [resolve(cleaned)]
|
|
372
|
+
: [...new Set([resolve(cwd, cleaned), resolve(root, cleaned)])];
|
|
373
|
+
|
|
374
|
+
let outside = false;
|
|
375
|
+
for (const candidate of candidates) {
|
|
376
|
+
if (!exists(candidate)) continue;
|
|
377
|
+
let real;
|
|
378
|
+
let rootReal;
|
|
379
|
+
try {
|
|
380
|
+
real = realpath(candidate);
|
|
381
|
+
rootReal = realpath(root);
|
|
382
|
+
} catch {
|
|
383
|
+
return { ok: false, reason: "Plan path cannot be resolved" };
|
|
384
|
+
}
|
|
385
|
+
const rel = relative(rootReal, real);
|
|
386
|
+
if (rel === "" || rel.startsWith("..") || isAbsolute(rel)) {
|
|
387
|
+
outside = true;
|
|
388
|
+
continue;
|
|
389
|
+
}
|
|
390
|
+
try {
|
|
391
|
+
const info = stat(real);
|
|
392
|
+
if (!info.isFile()) return { ok: false, reason: "Plan path is not a file" };
|
|
393
|
+
if (info.size > 1_000_000) return { ok: false, reason: "Plan file is too large" };
|
|
394
|
+
} catch {
|
|
395
|
+
return { ok: false, reason: "Plan path cannot be read" };
|
|
396
|
+
}
|
|
397
|
+
return { ok: true, path: real, relative: rel.split("\\").join("/") };
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
if (outside) return { ok: false, reason: "Plan must be inside the workspace" };
|
|
401
|
+
return { ok: false, reason: "Plan file not found; write it and get it approved first" };
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
function escapeRegex(char) {
|
|
405
|
+
return char.replace(/[.+^${}()|[\]\\]/g, "\\$&");
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
export function globToRegExp(glob) {
|
|
409
|
+
let value = String(glob ?? "").replace(/\\/g, "/").replace(/^\.\//, "");
|
|
410
|
+
if (!value) return /^$/;
|
|
411
|
+
if (value.endsWith("/")) value += "**";
|
|
412
|
+
|
|
413
|
+
let pattern = "";
|
|
414
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
415
|
+
const char = value[index];
|
|
416
|
+
if (char === "*") {
|
|
417
|
+
if (value[index + 1] === "*") {
|
|
418
|
+
index += 1;
|
|
419
|
+
if (value[index + 1] === "/") {
|
|
420
|
+
index += 1;
|
|
421
|
+
pattern += "(?:.*/)?";
|
|
422
|
+
} else {
|
|
423
|
+
pattern += ".*";
|
|
424
|
+
}
|
|
425
|
+
} else {
|
|
426
|
+
pattern += "[^/]*";
|
|
427
|
+
}
|
|
428
|
+
} else if (char === "?") {
|
|
429
|
+
pattern += "[^/]";
|
|
430
|
+
} else {
|
|
431
|
+
pattern += escapeRegex(char);
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
return new RegExp(`^${pattern}$`);
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
function posix(value) {
|
|
438
|
+
return value.split("\\").join("/");
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/**
|
|
442
|
+
* Resolve the nearest existing ancestor and append the missing remainder. A symlinked directory
|
|
443
|
+
* with a new nested directory cannot smuggle a write outside the workspace.
|
|
444
|
+
*/
|
|
445
|
+
function realpathNearest(target) {
|
|
446
|
+
let current = resolve(target);
|
|
447
|
+
const suffix = [];
|
|
448
|
+
while (true) {
|
|
449
|
+
try {
|
|
450
|
+
const real = realpathSync(current);
|
|
451
|
+
return suffix.length > 0 ? resolve(real, ...[...suffix].reverse()) : real;
|
|
452
|
+
} catch {
|
|
453
|
+
const parent = dirname(current);
|
|
454
|
+
if (parent === current) return resolve(target);
|
|
455
|
+
suffix.push(basename(current));
|
|
456
|
+
current = parent;
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/**
|
|
462
|
+
* True when the file path falls inside any of the approved scope globs. Relative globs are
|
|
463
|
+
* resolved against the workspace root; absolute globs are also supported. Symlinked parents are
|
|
464
|
+
* resolved so a link cannot smuggle a write outside the approved tree.
|
|
465
|
+
*/
|
|
466
|
+
export function inScope(filePath, globs, { workspaceRoot, cwd = workspaceRoot } = {}) {
|
|
467
|
+
const list = Array.isArray(globs) ? globs : parseScope(globs);
|
|
468
|
+
if (list.length === 0 || !filePath) return false;
|
|
469
|
+
const root = resolve(workspaceRoot ?? ".");
|
|
470
|
+
const lexicalPath = isAbsolute(filePath) ? resolve(filePath) : resolve(cwd ?? root, filePath);
|
|
471
|
+
const absolutePath = realpathNearest(lexicalPath);
|
|
472
|
+
let realRoot = root;
|
|
473
|
+
try {
|
|
474
|
+
realRoot = realpathSync(root);
|
|
475
|
+
} catch {
|
|
476
|
+
realRoot = root;
|
|
477
|
+
}
|
|
478
|
+
const relativePath = posix(relative(realRoot, absolutePath));
|
|
479
|
+
if (relativePath === "" || relativePath.startsWith("../") || isAbsolute(relativePath)) {
|
|
480
|
+
return false;
|
|
481
|
+
}
|
|
482
|
+
const absolutePosix = posix(absolutePath);
|
|
483
|
+
|
|
484
|
+
return list.some((glob) => {
|
|
485
|
+
const normalized = posix(String(glob ?? "").trim());
|
|
486
|
+
if (!normalized) return false;
|
|
487
|
+
if (normalized.startsWith("/")) {
|
|
488
|
+
return globToRegExp(normalized).test(absolutePosix);
|
|
489
|
+
}
|
|
490
|
+
return globToRegExp(normalized.replace(/^\.\//, "")).test(relativePath);
|
|
491
|
+
});
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
function parsePatchPaths(patchText) {
|
|
495
|
+
const paths = new Set();
|
|
496
|
+
const add = (value, stripDiffPrefix = false) => {
|
|
497
|
+
let cleaned = stripToken(value);
|
|
498
|
+
if (stripDiffPrefix) cleaned = cleaned.replace(/^[ab]\//, "");
|
|
499
|
+
if (cleaned && cleaned !== "/dev/null") paths.add(cleaned);
|
|
500
|
+
};
|
|
501
|
+
for (const line of String(patchText ?? "").split(/\r?\n/)) {
|
|
502
|
+
const section = line.match(/^\*\*\*\s+(?:Add|Update|Delete|Move)\s+(?:File|to):\s*(.+)$/i);
|
|
503
|
+
if (section) add(section[1]);
|
|
504
|
+
const diff = line.match(/^diff --git\s+(?:a\/)?(\S+)\s+(?:b\/)?(\S+)$/);
|
|
505
|
+
if (diff) {
|
|
506
|
+
add(diff[1], true);
|
|
507
|
+
add(diff[2], true);
|
|
508
|
+
}
|
|
509
|
+
const plus = line.match(/^\+\+\+\s+(?:b\/)?(.+)$/);
|
|
510
|
+
if (plus) add(plus[1], true);
|
|
511
|
+
const minus = line.match(/^---\s+(?:a\/)?(.+)$/);
|
|
512
|
+
if (minus) add(minus[1], true);
|
|
513
|
+
}
|
|
514
|
+
return [...paths];
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/**
|
|
518
|
+
* Paths an edit-like tool will touch. `edit` and `write` carry `path`; `patch` carries a
|
|
519
|
+
* patchText with one or more file sections; `multiedit` carries an `edits` array.
|
|
520
|
+
*/
|
|
521
|
+
export function extractToolPaths(tool, input) {
|
|
522
|
+
if (!input || typeof input !== "object") return [];
|
|
523
|
+
const name = String(tool ?? "").toLowerCase();
|
|
524
|
+
if (name === "multiedit") {
|
|
525
|
+
if (Array.isArray(input.edits)) {
|
|
526
|
+
return input.edits
|
|
527
|
+
.map((edit) => stripToken(edit?.filePath ?? edit?.path ?? edit?.file_path ?? ""))
|
|
528
|
+
.filter(Boolean);
|
|
529
|
+
}
|
|
530
|
+
const path = input.path ?? input.filePath ?? input.file_path;
|
|
531
|
+
return path ? [stripToken(path)] : [];
|
|
532
|
+
}
|
|
533
|
+
if (name === "edit" || name === "write") {
|
|
534
|
+
const path = input.path ?? input.filePath ?? input.file_path;
|
|
535
|
+
return path ? [stripToken(path)] : [];
|
|
536
|
+
}
|
|
537
|
+
if (name === "patch" || name === "apply_patch") {
|
|
538
|
+
const text = input.patchText ?? input.patch ?? input.diff ?? input.content;
|
|
539
|
+
return parsePatchPaths(text);
|
|
540
|
+
}
|
|
541
|
+
return [];
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
function commandTokenPattern(names) {
|
|
545
|
+
// A command token is not a substring of a flag (so `--rm` is safe), but it may be wrapped in
|
|
546
|
+
// quotes, a path, a backslash, a subshell or a variable expansion.
|
|
547
|
+
return new RegExp(
|
|
548
|
+
`(?:^|[^\\w-])(?:sudo\\s+)?(?:[/\\\\]\\S*[/\\\\])?(?:${names})(?=\\s|$|[)"'\`])`,
|
|
549
|
+
"im"
|
|
550
|
+
);
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
const DESTRUCTIVE_RULES = [
|
|
554
|
+
{ reason: "force-clean Git working tree", pattern: /\bgit\s+clean\b[^;&|\n]*(?:-[a-z]*f[a-z]*|--force)(?=\s|$|["'])/i },
|
|
555
|
+
{ reason: "hard Git reset", pattern: /\bgit\s+reset\s+--hard\b/i },
|
|
556
|
+
{ reason: "discard working-tree changes", pattern: /\bgit\s+checkout\b[^;&|\n]*\s(?:--\s+\S+|\.(?=\s|$|["']))/i },
|
|
557
|
+
{ reason: "file deletion", pattern: commandTokenPattern("rm|rmdir|unlink|shred") },
|
|
558
|
+
{ reason: "file or table truncation", pattern: commandTokenPattern("truncate") },
|
|
559
|
+
{ reason: "file truncation by redirection", pattern: /(?:^|[\s;&|]):\s*>\s*\S/ },
|
|
560
|
+
{ reason: "block device copy", pattern: /(?:^|[^\w-])dd\s+[^;&|\n]*\bof=/i },
|
|
561
|
+
{ reason: "PowerShell file deletion", pattern: /\bRemove-Item\b/i },
|
|
562
|
+
{ reason: "recursive file deletion", pattern: /\bfind\b[^;&|\n]*\s-delete\b/i },
|
|
563
|
+
{ reason: "database drop", pattern: /\bdrop\s+(?:table|database|schema|index|view|materialized\s+view)\b/i },
|
|
564
|
+
{ reason: "database drop", pattern: /\bdropdb\b|\bdropDatabase\s*\(/i },
|
|
565
|
+
{ reason: "database truncation", pattern: /\btruncate\s+(?:table\s+)?["'`\w]/i },
|
|
566
|
+
{ reason: "database flush", pattern: /\bflushall\b|\bflushdb\b/i },
|
|
567
|
+
{ reason: "migration reset", pattern: /\bflyway\b[^;&|\n]*\bclean\b/i },
|
|
568
|
+
{ reason: "migration reset", pattern: /\bprisma\s+migrate\s+reset\b|\balembic\s+downgrade\s+base\b/i },
|
|
569
|
+
{ reason: "document deletion", pattern: /\bdeleteMany\s*\(\s*\{\s*\}\s*\)/i },
|
|
570
|
+
{ reason: "volume deletion", pattern: /\bdocker\s+volume\s+(?:rm|prune)\b/i },
|
|
571
|
+
{ reason: "volume deletion", pattern: /\bdocker(?:-compose|\s+compose)\s+down\b[^;&|\n]*\s(?:-v|--volumes)(?=\s|$)/i },
|
|
572
|
+
{ reason: "Docker system prune", pattern: /\bdocker\s+system\s+prune\b/i },
|
|
573
|
+
{ reason: "cluster resource deletion", pattern: /\bkubectl\s+delete\b/i },
|
|
574
|
+
{ reason: "infrastructure destruction", pattern: /\bterraform\s+destroy\b/i },
|
|
575
|
+
{ reason: "infrastructure destruction", pattern: /\bterraform\s+apply\b[^;&|\n]*-destroy\b/i },
|
|
576
|
+
{ reason: "object storage deletion", pattern: /\b(?:aws\s+s3\s+rm|gsutil\s+rm|mc\s+rm)\b/i },
|
|
577
|
+
{ reason: "object storage deletion", pattern: /\baws\s+s3\s+sync\b[^;&|\n]*\s--delete\b/i },
|
|
578
|
+
{ reason: "remote deletion", pattern: /\brclone\s+delete\b/i },
|
|
579
|
+
{ reason: "mirror deletion", pattern: /\brsync\b[^;&|\n]*\s--del(?:ete)?\b/i }
|
|
580
|
+
];
|
|
581
|
+
|
|
582
|
+
function stripOuterQuotes(value) {
|
|
583
|
+
const trimmed = value.trim();
|
|
584
|
+
if (
|
|
585
|
+
(trimmed.startsWith('"') && trimmed.endsWith('"')) ||
|
|
586
|
+
(trimmed.startsWith("'") && trimmed.endsWith("'"))
|
|
587
|
+
) {
|
|
588
|
+
return trimmed.slice(1, -1);
|
|
589
|
+
}
|
|
590
|
+
return trimmed;
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
function unwrapShell(value) {
|
|
594
|
+
const shell = value.match(
|
|
595
|
+
/\b(?:bash|sh|zsh|dash)\b(?:\s+-[a-z]+)*\s+-[a-z]*c[a-z]*\s+([\s\S]+)$/i
|
|
596
|
+
);
|
|
597
|
+
if (shell) return stripOuterQuotes(shell[1]);
|
|
598
|
+
const evaluated = value.match(/\beval\s+([\s\S]+)$/i);
|
|
599
|
+
if (evaluated) return stripOuterQuotes(evaluated[1]);
|
|
600
|
+
return null;
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
function destructiveReason(value) {
|
|
604
|
+
for (const rule of DESTRUCTIVE_RULES) {
|
|
605
|
+
if (rule.pattern.test(value)) return rule.reason;
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
if (/\bgit\s+restore\b/i.test(value)) {
|
|
609
|
+
const stagedOnly = /--staged\b/i.test(value) && !/--worktree\b/i.test(value);
|
|
610
|
+
if (!stagedOnly) return "discard working-tree changes";
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
const deletes = value.match(/\bdelete\s+from\b[^;]*/gi) ?? [];
|
|
614
|
+
for (const statement of deletes) {
|
|
615
|
+
if (!/\bwhere\b/i.test(statement)) return "unbounded row deletion";
|
|
616
|
+
if (/\bwhere\s+(?:true|'true'|\d+\s*=\s*\d+)\b/i.test(statement)) return "unbounded row deletion";
|
|
617
|
+
}
|
|
618
|
+
return null;
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
/**
|
|
622
|
+
* Best-effort detection of commands that can delete data. It returns a category, never the
|
|
623
|
+
* command, so permission messages can stay free of secrets. Shell wrappers are unwrapped once.
|
|
624
|
+
*/
|
|
625
|
+
export function isDestructiveCommand(command) {
|
|
626
|
+
const value = String(command ?? "");
|
|
627
|
+
if (!value.trim()) return { destructive: false, reason: null };
|
|
628
|
+
|
|
629
|
+
const direct = destructiveReason(value);
|
|
630
|
+
if (direct) return { destructive: true, reason: direct };
|
|
631
|
+
|
|
632
|
+
const unwrapped = unwrapShell(value);
|
|
633
|
+
if (unwrapped && unwrapped !== value) {
|
|
634
|
+
const nested = destructiveReason(unwrapped);
|
|
635
|
+
if (nested) return { destructive: true, reason: nested };
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
return { destructive: false, reason: null };
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
/**
|
|
642
|
+
* Choose the pending scope for a child session without guessing: a mapped child wins, then
|
|
643
|
+
* exactly one matching unclaimed delegation; more than one is ambiguous and must deny.
|
|
644
|
+
*/
|
|
645
|
+
export function selectPendingScope(records, { sessionID, parentID, role = "", now = Date.now(), ttl = 30 * 60 * 1000 } = {}) {
|
|
646
|
+
const fresh = records
|
|
647
|
+
.map((record, index) => ({ record, index }))
|
|
648
|
+
.filter(({ record }) => now - record.createdAt <= ttl);
|
|
649
|
+
const mapped = fresh.find(({ record }) => record.childSessionID === sessionID);
|
|
650
|
+
if (mapped) return { status: "mapped", index: mapped.index };
|
|
651
|
+
|
|
652
|
+
const candidates = fresh.filter(({ record }) =>
|
|
653
|
+
record.parentSessionID === parentID && (!role || record.agent === role));
|
|
654
|
+
const claimable = candidates.filter(({ record }) => !record.childSessionID);
|
|
655
|
+
if (claimable.length === 1) return { status: "single", index: claimable[0].index };
|
|
656
|
+
if (claimable.length > 1) return { status: "ambiguous" };
|
|
657
|
+
return { status: "none" };
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
/**
|
|
661
|
+
* A global adapter must no-op only when the running copy is actually the global one. A path
|
|
662
|
+
* inequality is not enough: a symlinked project root or a case difference made the local copy
|
|
663
|
+
* look foreign and disabled every gate. Check the lexical and resolved path against the global
|
|
664
|
+
* plugin roots instead.
|
|
665
|
+
*/
|
|
666
|
+
export function isGlobalPluginPath(selfPath, globalRoots = []) {
|
|
667
|
+
if (!selfPath || !Array.isArray(globalRoots) || globalRoots.length === 0) return false;
|
|
668
|
+
const selfCandidates = [resolve(selfPath)];
|
|
669
|
+
try {
|
|
670
|
+
selfCandidates.push(realpathSync(selfPath));
|
|
671
|
+
} catch {
|
|
672
|
+
// The loaded file should exist; keep the lexical path as the fallback.
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
return globalRoots.some((root) => {
|
|
676
|
+
const rootCandidates = [resolve(root)];
|
|
677
|
+
try {
|
|
678
|
+
rootCandidates.push(realpathSync(root));
|
|
679
|
+
} catch {
|
|
680
|
+
// A missing global root cannot contain the running copy.
|
|
681
|
+
}
|
|
682
|
+
return rootCandidates.some((realRoot) =>
|
|
683
|
+
selfCandidates.some((self) => {
|
|
684
|
+
const rel = relative(realRoot, self);
|
|
685
|
+
return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel);
|
|
686
|
+
}));
|
|
687
|
+
});
|
|
688
|
+
}
|