flowtask-permission-gate 0.0.0-stage → 2.0.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/LICENSE +21 -0
- package/README.md +90 -2
- package/dist/authorizer.d.ts +16 -0
- package/dist/authorizer.js +473 -0
- package/dist/context-budget.d.ts +138 -0
- package/dist/context-budget.js +369 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +642 -0
- package/dist/layers.d.ts +104 -0
- package/dist/layers.js +185 -0
- package/dist/registration.d.ts +44 -0
- package/dist/registration.js +135 -0
- package/dist/worktree-manager-location.d.ts +17 -0
- package/dist/worktree-manager-location.js +30 -0
- package/package.json +41 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,642 @@
|
|
|
1
|
+
import { Plugin } from "@opencode/plugin";
|
|
2
|
+
import { execFileSync } from "node:child_process";
|
|
3
|
+
import { readFileSync, statSync } from "node:fs";
|
|
4
|
+
import { isAbsolute, resolve } from "node:path";
|
|
5
|
+
import { RUNNER_DELEGATION_MESSAGE, isAuthorizedRunnerCommand, isAuthorizedRunnerSubagent, isAuthorityCommand, isWorktreeManagerMcpTool, } from "./authorizer.js";
|
|
6
|
+
import { buildLayerBlockMessage, readOperationalLayers, readOperationalLayersAt } from "./layers.js";
|
|
7
|
+
import { evaluateOpencodeActivation, findOpencodeRegistration, } from "./registration.js";
|
|
8
|
+
import { applyReducedDelivery, buildAttachmentDelivery, buildDegradationMetadata, buildNarrowingNotice, buildReducedDelivery, isImageOrPdfOutput, loadContextBudgetConfig, readDeliveredText, readRequestedPath, registerNarrowingNotice, resetNarrowingNotices, shouldPreventiveBlockGlob, shouldPreventiveBlockGrep, shouldPreventiveBlockRead, } from "./context-budget.js";
|
|
9
|
+
/**
|
|
10
|
+
* Candidate configuration paths, tried in order within each directory.
|
|
11
|
+
* Precedence: commit workdir first; sessionDir only as a fallback for
|
|
12
|
+
* the other settings. The `stampPath` is ALWAYS resolved against the workdir.
|
|
13
|
+
*/
|
|
14
|
+
const CONFIG_CANDIDATES = [
|
|
15
|
+
".opencode/flowtask/config/review.json",
|
|
16
|
+
".flowtask/config/review.json",
|
|
17
|
+
];
|
|
18
|
+
/** Default review-stamp TTL; overridable with `stampTtlMinutes` in review.json. */
|
|
19
|
+
const DEFAULT_STAMP_TTL_MINUTES = 30;
|
|
20
|
+
/** Triviality criterion for the --no-verify bypass: changes with ≤ TRIVIAL_CHANGE_LINES lines. */
|
|
21
|
+
const TRIVIAL_CHANGE_LINES = 5;
|
|
22
|
+
const SESSION_AGENTS = new Map();
|
|
23
|
+
/**
|
|
24
|
+
* Accumulated per runner turn (GAP-002): turn = cycle opened by each `prompt`
|
|
25
|
+
* event of the same sessionID. `TURN_STATE` stores the sum of delivered (not
|
|
26
|
+
* omitted) chars and the turn number; `TURN_SEQ` numbers the turns.
|
|
27
|
+
*/
|
|
28
|
+
const TURN_STATE = new Map();
|
|
29
|
+
const TURN_SEQ = new Map();
|
|
30
|
+
/**
|
|
31
|
+
* Normalizes an agent identity to a comparable canonical form:
|
|
32
|
+
* trim + lowercase, and `_` or whitespace collapsed to `-`. Covers
|
|
33
|
+
* case-insensitive variants such as "FlowTask-Runner", "FLOWTASK_RUNNER", " flowtask-runner ".
|
|
34
|
+
*/
|
|
35
|
+
function normalizeAgent(agent) {
|
|
36
|
+
return String(agent).trim().toLowerCase().replace(/_/g, "-").replace(/\s+/g, "-");
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Is this agent the FlowTask runner? The gate validates the PERSONALITY
|
|
40
|
+
* (flowtask-runner), not the model: only an exact case-insensitive match of
|
|
41
|
+
* the normalized identity qualifies.
|
|
42
|
+
*/
|
|
43
|
+
function isRunner(agent) {
|
|
44
|
+
return typeof agent === "string" && normalizeAgent(agent) === "flowtask-runner";
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Resolves the identity exposed by the V2 event. An explicit non-empty agent
|
|
48
|
+
* wins as-is: only the runner is registered per session for later phases that
|
|
49
|
+
* arrive without an identity. The session fallback applies only when the event
|
|
50
|
+
* carries no agent, so a non-runner cannot inherit the recorded runner.
|
|
51
|
+
*/
|
|
52
|
+
function resolveSessionAgent(sessionID, eventAgent) {
|
|
53
|
+
if (typeof eventAgent === "string" && eventAgent.trim()) {
|
|
54
|
+
if (isRunner(eventAgent))
|
|
55
|
+
SESSION_AGENTS.set(sessionID, eventAgent);
|
|
56
|
+
return eventAgent;
|
|
57
|
+
}
|
|
58
|
+
return SESSION_AGENTS.get(sessionID);
|
|
59
|
+
}
|
|
60
|
+
/** Commit workdir precedence: explicit workdir, explicit cwd, then the session directory. */
|
|
61
|
+
function readWorkdir(args, fallback) {
|
|
62
|
+
const candidate = args.workdir ?? args.cwd;
|
|
63
|
+
return typeof candidate === "string" && candidate ? candidate : fallback;
|
|
64
|
+
}
|
|
65
|
+
/** Global git options that consume the next token as their value. */
|
|
66
|
+
const GIT_GLOBAL_OPTIONS_WITH_VALUE = new Set([
|
|
67
|
+
"-C",
|
|
68
|
+
"-c",
|
|
69
|
+
"--git-dir",
|
|
70
|
+
"--work-tree",
|
|
71
|
+
"--namespace",
|
|
72
|
+
"--exec-path",
|
|
73
|
+
]);
|
|
74
|
+
/** Global git options written with `=<value>`. */
|
|
75
|
+
const GIT_GLOBAL_OPTIONS_WITH_EQUALS = ["--git-dir=", "--work-tree=", "--namespace=", "--exec-path="];
|
|
76
|
+
/** Splits a command on `&&` without breaking quoted segments. */
|
|
77
|
+
function splitCommandSegments(command) {
|
|
78
|
+
const segments = [];
|
|
79
|
+
let current = "";
|
|
80
|
+
let quote = null;
|
|
81
|
+
for (let index = 0; index < command.length; index += 1) {
|
|
82
|
+
const char = command[index];
|
|
83
|
+
if (quote) {
|
|
84
|
+
current += char;
|
|
85
|
+
if (char === quote)
|
|
86
|
+
quote = null;
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
if (char === '"' || char === "'") {
|
|
90
|
+
quote = char;
|
|
91
|
+
current += char;
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
if (char === "&" && command[index + 1] === "&") {
|
|
95
|
+
segments.push(current);
|
|
96
|
+
current = "";
|
|
97
|
+
index += 1;
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
current += char;
|
|
101
|
+
}
|
|
102
|
+
segments.push(current);
|
|
103
|
+
return segments;
|
|
104
|
+
}
|
|
105
|
+
/** Whitespace tokenization that keeps a quoted value in one token. */
|
|
106
|
+
function tokenizeSegment(segment) {
|
|
107
|
+
const tokens = [];
|
|
108
|
+
let current = "";
|
|
109
|
+
let quote = null;
|
|
110
|
+
for (const char of segment) {
|
|
111
|
+
if (quote) {
|
|
112
|
+
current += char;
|
|
113
|
+
if (char === quote)
|
|
114
|
+
quote = null;
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
if (char === '"' || char === "'") {
|
|
118
|
+
quote = char;
|
|
119
|
+
current += char;
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
if (/\s/.test(char)) {
|
|
123
|
+
if (current) {
|
|
124
|
+
tokens.push(current);
|
|
125
|
+
current = "";
|
|
126
|
+
}
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
current += char;
|
|
130
|
+
}
|
|
131
|
+
if (current)
|
|
132
|
+
tokens.push(current);
|
|
133
|
+
return tokens;
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Detects a commit in any `&&` segment, including the global git options that
|
|
137
|
+
* precede the subcommand (`-C`, `-c`, `--git-dir`, and their value forms).
|
|
138
|
+
* A leading `cd` belongs to its own segment, so `cd ... && git commit` is seen.
|
|
139
|
+
*/
|
|
140
|
+
function isGitCommitCommand(command) {
|
|
141
|
+
for (const segment of splitCommandSegments(command)) {
|
|
142
|
+
const tokens = tokenizeSegment(segment);
|
|
143
|
+
for (let start = 0; start < tokens.length; start += 1) {
|
|
144
|
+
if (tokens[start] !== "git")
|
|
145
|
+
continue;
|
|
146
|
+
let index = start + 1;
|
|
147
|
+
while (index < tokens.length) {
|
|
148
|
+
const token = tokens[index];
|
|
149
|
+
if (token === "commit")
|
|
150
|
+
return true;
|
|
151
|
+
if (GIT_GLOBAL_OPTIONS_WITH_VALUE.has(token)) {
|
|
152
|
+
index += 2;
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
if (GIT_GLOBAL_OPTIONS_WITH_EQUALS.some((prefix) => token.startsWith(prefix))) {
|
|
156
|
+
index += 1;
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
if (token.startsWith("-")) {
|
|
160
|
+
index += 1;
|
|
161
|
+
continue;
|
|
162
|
+
}
|
|
163
|
+
break;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
return false;
|
|
168
|
+
}
|
|
169
|
+
function runnerToolAllowed(tool, args) {
|
|
170
|
+
if (isWorktreeManagerMcpTool(tool))
|
|
171
|
+
return true;
|
|
172
|
+
if (tool === "bash")
|
|
173
|
+
return isAuthorizedRunnerCommand(String(args.command ?? ""));
|
|
174
|
+
if (tool === "read" || tool === "glob" || tool === "grep" || tool === "skill" || tool.startsWith("engram_"))
|
|
175
|
+
return true;
|
|
176
|
+
// MCP Graphify: the only MCP tool authorized for the runner (path 1 of the research chain).
|
|
177
|
+
// Do not expand to other graphify tools — only the exact enumerated tool.
|
|
178
|
+
if (tool === "graphify_query_graph")
|
|
179
|
+
return true;
|
|
180
|
+
if (tool === "subagent")
|
|
181
|
+
return isAuthorizedRunnerSubagent(args.agent);
|
|
182
|
+
return false;
|
|
183
|
+
}
|
|
184
|
+
function runnerBlocked() { throw new Error(RUNNER_DELEGATION_MESSAGE); }
|
|
185
|
+
/** A V2 content part that carries an attachment payload instead of text. */
|
|
186
|
+
function isFilePart(part) {
|
|
187
|
+
return Boolean(part) && typeof part === "object" && part.type === "file";
|
|
188
|
+
}
|
|
189
|
+
function gateError(operation, cause, action) {
|
|
190
|
+
const detail = cause instanceof Error ? cause.message : String(cause);
|
|
191
|
+
return new Error(`[FlowTask Permission Gate] Commit blocked.\n` +
|
|
192
|
+
`Failed operation: ${operation}.\n` +
|
|
193
|
+
`Cause: ${detail}.\n` +
|
|
194
|
+
`Recommended action: ${action}`);
|
|
195
|
+
}
|
|
196
|
+
/** Structural validation: an unusable file is reported, never silently ignored. */
|
|
197
|
+
function parseReviewConfig(raw, path) {
|
|
198
|
+
let value;
|
|
199
|
+
try {
|
|
200
|
+
value = JSON.parse(raw);
|
|
201
|
+
}
|
|
202
|
+
catch {
|
|
203
|
+
return { ok: false, cause: "the file is not parseable JSON" };
|
|
204
|
+
}
|
|
205
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
206
|
+
return { ok: false, cause: "the file does not contain a JSON object" };
|
|
207
|
+
}
|
|
208
|
+
const config = value;
|
|
209
|
+
if (typeof config.enabled !== "boolean") {
|
|
210
|
+
return { ok: false, cause: 'the "enabled" field is missing or is not boolean' };
|
|
211
|
+
}
|
|
212
|
+
if (typeof config.stampPath !== "string" || !config.stampPath) {
|
|
213
|
+
return { ok: false, cause: 'the "stampPath" field is missing or empty' };
|
|
214
|
+
}
|
|
215
|
+
let stampTtlMinutes = DEFAULT_STAMP_TTL_MINUTES;
|
|
216
|
+
if (config.stampTtlMinutes !== undefined) {
|
|
217
|
+
if (typeof config.stampTtlMinutes === "number" && Number.isFinite(config.stampTtlMinutes) && config.stampTtlMinutes > 0) {
|
|
218
|
+
stampTtlMinutes = config.stampTtlMinutes;
|
|
219
|
+
}
|
|
220
|
+
else {
|
|
221
|
+
return { ok: false, cause: 'the "stampTtlMinutes" field is not a positive number' };
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
return {
|
|
225
|
+
ok: true,
|
|
226
|
+
config: {
|
|
227
|
+
enabled: config.enabled,
|
|
228
|
+
stampPath: config.stampPath,
|
|
229
|
+
stampTtlMinutes,
|
|
230
|
+
sourcePath: path,
|
|
231
|
+
},
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Looks for review.json in `directory` by trying the canonical paths in order.
|
|
236
|
+
* Missing lets the caller continue to the next directory; an existing but
|
|
237
|
+
* unreadable or invalid file is returned as such so the gate can fail closed.
|
|
238
|
+
*/
|
|
239
|
+
function findConfigIn(directory) {
|
|
240
|
+
for (const candidate of CONFIG_CANDIDATES) {
|
|
241
|
+
const path = resolve(directory, candidate);
|
|
242
|
+
let raw;
|
|
243
|
+
try {
|
|
244
|
+
raw = readFileSync(path, "utf8");
|
|
245
|
+
}
|
|
246
|
+
catch (error) {
|
|
247
|
+
if (error.code === "ENOENT")
|
|
248
|
+
continue;
|
|
249
|
+
return { status: "invalid", path, cause: "the file could not be read" };
|
|
250
|
+
}
|
|
251
|
+
const parsed = parseReviewConfig(raw, path);
|
|
252
|
+
if (!parsed.ok)
|
|
253
|
+
return { status: "invalid", path, cause: parsed.cause };
|
|
254
|
+
return { status: "found", config: parsed.config };
|
|
255
|
+
}
|
|
256
|
+
return { status: "missing" };
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* Documented precedence: workdir-first (the two known paths); the fallback
|
|
260
|
+
* to sessionDir/main contributes only the other settings (enabled, TTL). The
|
|
261
|
+
* resulting `stampPath` is ALWAYS resolved against the commit workdir.
|
|
262
|
+
*/
|
|
263
|
+
function readConfig(workdir, fallbackCwd) {
|
|
264
|
+
const directories = [workdir, fallbackCwd].filter((directory, index, values) => Boolean(directory) && values.indexOf(directory) === index);
|
|
265
|
+
for (const directory of directories) {
|
|
266
|
+
const found = findConfigIn(directory);
|
|
267
|
+
if (found.status !== "missing")
|
|
268
|
+
return found;
|
|
269
|
+
}
|
|
270
|
+
return { status: "missing" };
|
|
271
|
+
}
|
|
272
|
+
function getCurrentBranch(cwd) {
|
|
273
|
+
try {
|
|
274
|
+
return execFileSync("git", ["branch", "--show-current"], { cwd, encoding: "utf8" }).trim();
|
|
275
|
+
}
|
|
276
|
+
catch (error) {
|
|
277
|
+
throw gateError("determine the current branch", error, "verify that the workdir is a valid git repository and retry");
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* Structured format: {"ts":"<ISO-8601>","branch":"<branch>"}. Plain ISO
|
|
282
|
+
* stamps (obsolete format) are rejected with an explicit cause. Fail-closed.
|
|
283
|
+
*/
|
|
284
|
+
function parseStamp(raw) {
|
|
285
|
+
const trimmed = raw.trim();
|
|
286
|
+
let value;
|
|
287
|
+
try {
|
|
288
|
+
value = JSON.parse(trimmed);
|
|
289
|
+
}
|
|
290
|
+
catch {
|
|
291
|
+
if (!Number.isNaN(Date.parse(trimmed))) {
|
|
292
|
+
return {
|
|
293
|
+
ok: false,
|
|
294
|
+
reason: 'obsolete format (plain ISO-8601): generate a new stamp with the format {"ts":"<ISO-8601>","branch":"<branch>"}',
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
return { ok: false, reason: "invalid format: the content is not parseable JSON" };
|
|
298
|
+
}
|
|
299
|
+
if (!value || typeof value !== "object") {
|
|
300
|
+
return { ok: false, reason: "invalid format: the stamp must be a JSON object {ts, branch}" };
|
|
301
|
+
}
|
|
302
|
+
const record = value;
|
|
303
|
+
if (typeof record.ts !== "string" || !record.ts || Number.isNaN(Date.parse(record.ts))) {
|
|
304
|
+
return { ok: false, reason: "invalid format: the \"ts\" field is missing or invalid (ISO-8601)" };
|
|
305
|
+
}
|
|
306
|
+
if (typeof record.branch !== "string" || !record.branch) {
|
|
307
|
+
return { ok: false, reason: "invalid format: the \"branch\" field is missing or invalid" };
|
|
308
|
+
}
|
|
309
|
+
return { ok: true, payload: { ts: Date.parse(record.ts), branch: record.branch } };
|
|
310
|
+
}
|
|
311
|
+
/** Validates TTL and branch binding. Returns the rejection cause or null if valid. */
|
|
312
|
+
function stampIssue(payload, now, currentBranch, ttlMinutes) {
|
|
313
|
+
const ageMinutes = Math.floor((now - payload.ts) / 60000);
|
|
314
|
+
if (now - payload.ts > ttlMinutes * 60000) {
|
|
315
|
+
return `expired ${ageMinutes} min ago (current TTL: ${ttlMinutes} min)`;
|
|
316
|
+
}
|
|
317
|
+
if (payload.branch !== currentBranch) {
|
|
318
|
+
return `branch mismatch (expected '${payload.branch}', found '${currentBranch || "detached/no branch"}')`;
|
|
319
|
+
}
|
|
320
|
+
return null;
|
|
321
|
+
}
|
|
322
|
+
/**
|
|
323
|
+
* Honest diff: `git status --porcelain` counts real pending files
|
|
324
|
+
* (staged + unstaged); `git diff HEAD --stat` provides the +/- lines.
|
|
325
|
+
*/
|
|
326
|
+
function getDiffStats(cwd) {
|
|
327
|
+
let pendingFiles = 0;
|
|
328
|
+
let lines = 0;
|
|
329
|
+
let lastError;
|
|
330
|
+
try {
|
|
331
|
+
const statusOutput = execFileSync("git", ["status", "--porcelain"], { cwd, encoding: "utf8" }).trim();
|
|
332
|
+
pendingFiles = statusOutput ? statusOutput.split("\n").length : 0;
|
|
333
|
+
}
|
|
334
|
+
catch (error) {
|
|
335
|
+
lastError = error;
|
|
336
|
+
}
|
|
337
|
+
try {
|
|
338
|
+
const diffOutput = execFileSync("git", ["diff", "HEAD", "--stat"], { cwd, encoding: "utf8" }).trim();
|
|
339
|
+
if (diffOutput) {
|
|
340
|
+
const summary = diffOutput.split("\n").pop() ?? "";
|
|
341
|
+
const insertions = summary.match(/(\d+)\s+insertions?\(\+\)/);
|
|
342
|
+
const deletions = summary.match(/(\d+)\s+deletions?\(-\)/);
|
|
343
|
+
const files = summary.match(/(\d+)\s+files? changed/);
|
|
344
|
+
if (!insertions && !deletions && !files) {
|
|
345
|
+
throw new Error(`unrecognized git diff output: ${summary}`);
|
|
346
|
+
}
|
|
347
|
+
lines = (insertions ? Number(insertions[1]) : 0) + (deletions ? Number(deletions[1]) : 0);
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
catch (error) {
|
|
351
|
+
lastError = lastError ?? error;
|
|
352
|
+
}
|
|
353
|
+
if (lastError) {
|
|
354
|
+
throw gateError("analyze diff", lastError, "verify the repository and retry");
|
|
355
|
+
}
|
|
356
|
+
return { lines, files: pendingFiles };
|
|
357
|
+
}
|
|
358
|
+
function buildGateMessage(stats) {
|
|
359
|
+
return [
|
|
360
|
+
"[FlowTask Permission Gate] Commit blocked.",
|
|
361
|
+
"",
|
|
362
|
+
`📊 Diff: ${stats.files} file(s), ${stats.lines} line(s).`,
|
|
363
|
+
"",
|
|
364
|
+
"→ Runner: assess whether this change requires pre-commit review.",
|
|
365
|
+
" - If it is trivial (gitignore, docs, chore ≤ 5 lines): re-run the commit with --no-verify.",
|
|
366
|
+
" - If not: invoke flowtask-review-orchestrator and generate the stamp before retrying.",
|
|
367
|
+
].join("\n");
|
|
368
|
+
}
|
|
369
|
+
function buildMissingConfigMessage(workdir, fallbackCwd, registrationPath, stats) {
|
|
370
|
+
const directories = [workdir, fallbackCwd].filter((directory, index, values) => Boolean(directory) && values.indexOf(directory) === index);
|
|
371
|
+
const searched = directories
|
|
372
|
+
.flatMap((directory) => CONFIG_CANDIDATES.map((candidate) => resolve(directory, candidate)))
|
|
373
|
+
.join(" or ");
|
|
374
|
+
return [
|
|
375
|
+
"[FlowTask Permission Gate] Commit blocked.",
|
|
376
|
+
"",
|
|
377
|
+
"Cause: review config missing; run flowtask update.",
|
|
378
|
+
`Searched: ${searched}`,
|
|
379
|
+
...(registrationPath ? [`Registration: ${registrationPath}`] : []),
|
|
380
|
+
"",
|
|
381
|
+
`📊 Diff: ${stats.files} file(s), ${stats.lines} line(s) pending.`,
|
|
382
|
+
"",
|
|
383
|
+
"→ The project is registered, so the gate fails closed instead of allowing an unreviewed commit.",
|
|
384
|
+
].join("\n");
|
|
385
|
+
}
|
|
386
|
+
function buildInvalidConfigMessage(path, cause, stats) {
|
|
387
|
+
return [
|
|
388
|
+
"[FlowTask Permission Gate] Commit blocked.",
|
|
389
|
+
"",
|
|
390
|
+
`Cause: invalid review config at ${path}: ${cause}.`,
|
|
391
|
+
"Recommended action: fix the file or run flowtask update.",
|
|
392
|
+
"",
|
|
393
|
+
`📊 Diff: ${stats.files} file(s), ${stats.lines} line(s) pending.`,
|
|
394
|
+
].join("\n");
|
|
395
|
+
}
|
|
396
|
+
function buildStampBlockMessage(cause, stampPath, configPath, stats) {
|
|
397
|
+
return [
|
|
398
|
+
"[FlowTask Permission Gate] Commit blocked by an invalid review-stamp.",
|
|
399
|
+
"",
|
|
400
|
+
`Cause: ${cause}.`,
|
|
401
|
+
`Stamp looked up at: ${stampPath}`,
|
|
402
|
+
`Applied config: ${configPath}`,
|
|
403
|
+
"",
|
|
404
|
+
`📊 Diff: ${stats.files} file(s), ${stats.lines} line(s) pending.`,
|
|
405
|
+
"",
|
|
406
|
+
"→ Invoke flowtask-review-orchestrator and generate a new stamp at the indicated path:",
|
|
407
|
+
' {"ts":"<ISO-8601>","branch":"<current branch of the target repo>"}',
|
|
408
|
+
].join("\n");
|
|
409
|
+
}
|
|
410
|
+
/**
|
|
411
|
+
* `stat.size` of the read target resolved against the commit workdir/session.
|
|
412
|
+
* Accepts the V2 `path` field with the legacy `file` fallback. Returns undefined
|
|
413
|
+
* on failure (hybrid GAP: the pre-gate is a cheap saving, the post-gate decides).
|
|
414
|
+
*/
|
|
415
|
+
function readStatSizeSafe(args, baseDir) {
|
|
416
|
+
const file = readRequestedPath(args);
|
|
417
|
+
if (!file)
|
|
418
|
+
return undefined;
|
|
419
|
+
const absolute = isAbsolute(file) ? file : resolve(baseDir, file);
|
|
420
|
+
try {
|
|
421
|
+
return statSync(absolute).size;
|
|
422
|
+
}
|
|
423
|
+
catch {
|
|
424
|
+
return undefined;
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
export default Plugin.define({
|
|
428
|
+
id: "flowtask-permission-gate",
|
|
429
|
+
async setup(ctx) {
|
|
430
|
+
const sessionDir = ctx.location.directory || process.cwd();
|
|
431
|
+
const registered = [];
|
|
432
|
+
const runtimeRoot = typeof ctx.options?.runtimeRoot === "string" && ctx.options.runtimeRoot
|
|
433
|
+
? ctx.options.runtimeRoot
|
|
434
|
+
: null;
|
|
435
|
+
// Registration gate: without a registered project, FlowTask agents and
|
|
436
|
+
// skills are not exposed. A broken or unsupported registration is reported
|
|
437
|
+
// through the context hook; an inactive project is removed silently.
|
|
438
|
+
if (runtimeRoot) {
|
|
439
|
+
const activation = evaluateOpencodeActivation({ directory: sessionDir, runtimeRoot });
|
|
440
|
+
if (activation.status !== "active") {
|
|
441
|
+
registered.push(await ctx.agent.transform(async (editor) => {
|
|
442
|
+
for (const agent of editor.list()) {
|
|
443
|
+
const id = String(agent.id ?? "");
|
|
444
|
+
const name = String(agent.name ?? "");
|
|
445
|
+
if (id.startsWith("flowtask-") || name.startsWith("flowtask-"))
|
|
446
|
+
editor.remove(String(agent.id));
|
|
447
|
+
}
|
|
448
|
+
}));
|
|
449
|
+
const normalizedRoot = runtimeRoot.replaceAll("\\", "/");
|
|
450
|
+
registered.push(await ctx.skill.transform(async (editor) => {
|
|
451
|
+
for (const skill of editor.list()) {
|
|
452
|
+
const skillPath = String(skill.path ?? "").replaceAll("\\", "/");
|
|
453
|
+
if (skillPath.startsWith(`${normalizedRoot}/versions/`))
|
|
454
|
+
editor.remove(String(skill.id));
|
|
455
|
+
}
|
|
456
|
+
}));
|
|
457
|
+
if (activation.message) {
|
|
458
|
+
const message = activation.message;
|
|
459
|
+
registered.push(await ctx.session.hook("context", async (event) => {
|
|
460
|
+
event.system.push({ type: "text", text: message });
|
|
461
|
+
}));
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
const beforeHook = await ctx.tool.hook("execute.before", async (event) => {
|
|
466
|
+
const input = event.input && typeof event.input === "object"
|
|
467
|
+
? event.input
|
|
468
|
+
: {};
|
|
469
|
+
const command = String(input.command ?? "");
|
|
470
|
+
const workdir = readWorkdir(input, sessionDir);
|
|
471
|
+
const agent = resolveSessionAgent(event.sessionID, event.agent);
|
|
472
|
+
if (isRunner(agent)) {
|
|
473
|
+
// Permissions layer: autonomy and permissions must exist and be
|
|
474
|
+
// valid in the target before applying the technical allowlist. Autonomy
|
|
475
|
+
// does not authorize: it only checks that the layer is healthy. An
|
|
476
|
+
// absent configuration is also a denial, not a pass.
|
|
477
|
+
const operationalLayers = typeof ctx.options?.configDir === "string" && ctx.options.configDir
|
|
478
|
+
? readOperationalLayersAt(ctx.options.configDir)
|
|
479
|
+
: readOperationalLayers([workdir, sessionDir]);
|
|
480
|
+
if (!operationalLayers.ok) {
|
|
481
|
+
const authorityBypass = event.tool === "bash" && isAuthorityCommand(command);
|
|
482
|
+
if (!authorityBypass)
|
|
483
|
+
throw new Error(buildLayerBlockMessage(operationalLayers));
|
|
484
|
+
}
|
|
485
|
+
if (!runnerToolAllowed(event.tool, input))
|
|
486
|
+
runnerBlocked();
|
|
487
|
+
}
|
|
488
|
+
// --- context budget: cheap pre-gate (runner, closed list, no tree walk) ---
|
|
489
|
+
// Degradation by levels, level 1: the first broad request of the turn is
|
|
490
|
+
// announced with the way to narrow it and is not executed. The same request
|
|
491
|
+
// repeated in the turn is allowed and its delivery is reduced in the post-gate.
|
|
492
|
+
if (isRunner(agent) && (event.tool === "read" || event.tool === "glob" || event.tool === "grep")) {
|
|
493
|
+
const budgetTool = event.tool;
|
|
494
|
+
const budget = loadContextBudgetConfig(workdir, sessionDir);
|
|
495
|
+
const broad = budgetTool === "read"
|
|
496
|
+
? shouldPreventiveBlockRead(input, readStatSizeSafe(input, workdir), budget.preventiveReadStatLimit)
|
|
497
|
+
: budgetTool === "glob"
|
|
498
|
+
? shouldPreventiveBlockGlob(input, budget.preventiveGlobPatterns, budget.blockedPaths)
|
|
499
|
+
: shouldPreventiveBlockGrep(input, budget.blockedPaths);
|
|
500
|
+
if (broad && registerNarrowingNotice(event.sessionID, budgetTool, input)) {
|
|
501
|
+
throw new Error(buildNarrowingNotice(budgetTool, input));
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
if (event.tool !== "bash" || !isGitCommitCommand(command))
|
|
505
|
+
return;
|
|
506
|
+
if (command.includes("--no-verify") || command.includes("--no-review")) {
|
|
507
|
+
// The bypass is only legitimate for trivial changes (≤ TRIVIAL_CHANGE_LINES).
|
|
508
|
+
// If the diff cannot be measured (getDiffStats throws), the error propagates and the commit is blocked (deny-by-default).
|
|
509
|
+
const stats = getDiffStats(workdir);
|
|
510
|
+
if (stats.lines <= TRIVIAL_CHANGE_LINES)
|
|
511
|
+
return; // trivial → legitimate bypass
|
|
512
|
+
throw new Error(buildGateMessage(stats)); // non-trivial → bypass denied, review required
|
|
513
|
+
}
|
|
514
|
+
const configLookup = readConfig(workdir, sessionDir);
|
|
515
|
+
if (configLookup.status === "invalid") {
|
|
516
|
+
throw new Error(buildInvalidConfigMessage(configLookup.path, configLookup.cause, getDiffStats(workdir)));
|
|
517
|
+
}
|
|
518
|
+
if (configLookup.status === "missing") {
|
|
519
|
+
const registration = findOpencodeRegistration(workdir);
|
|
520
|
+
if (registration.status === "active") {
|
|
521
|
+
throw new Error(buildMissingConfigMessage(workdir, sessionDir, registration.path, getDiffStats(workdir)));
|
|
522
|
+
}
|
|
523
|
+
return;
|
|
524
|
+
}
|
|
525
|
+
const config = configLookup.config;
|
|
526
|
+
if (!config.enabled)
|
|
527
|
+
return;
|
|
528
|
+
// Unified resolution: the relative stampPath is ALWAYS resolved against
|
|
529
|
+
// the commit workdir (per-flow isolation: worktrees read/write their own stamps).
|
|
530
|
+
const stampAbsolutePath = isAbsolute(config.stampPath)
|
|
531
|
+
? config.stampPath
|
|
532
|
+
: resolve(workdir, config.stampPath);
|
|
533
|
+
let raw;
|
|
534
|
+
try {
|
|
535
|
+
raw = readFileSync(stampAbsolutePath, "utf8");
|
|
536
|
+
}
|
|
537
|
+
catch (error) {
|
|
538
|
+
if (error.code === "ENOENT") {
|
|
539
|
+
throw new Error(buildStampBlockMessage("missing stamp", stampAbsolutePath, config.sourcePath, getDiffStats(workdir)));
|
|
540
|
+
}
|
|
541
|
+
throw gateError("read stamp", error, "verify permissions and retry");
|
|
542
|
+
}
|
|
543
|
+
const parsed = parseStamp(raw);
|
|
544
|
+
if (!parsed.ok) {
|
|
545
|
+
throw new Error(buildStampBlockMessage(parsed.reason, stampAbsolutePath, config.sourcePath, getDiffStats(workdir)));
|
|
546
|
+
}
|
|
547
|
+
const issue = stampIssue(parsed.payload, Date.now(), getCurrentBranch(workdir), config.stampTtlMinutes);
|
|
548
|
+
if (issue) {
|
|
549
|
+
throw new Error(buildStampBlockMessage(issue, stampAbsolutePath, config.sourcePath, getDiffStats(workdir)));
|
|
550
|
+
}
|
|
551
|
+
// Valid stamp: NOT consumed. Validity is governed by the TTL and branch
|
|
552
|
+
// binding; a later failed commit does not require regenerating the stamp.
|
|
553
|
+
return;
|
|
554
|
+
});
|
|
555
|
+
const afterHook = await ctx.tool.hook("execute.after", async (event) => {
|
|
556
|
+
if (event.status !== "completed")
|
|
557
|
+
return;
|
|
558
|
+
const agent = resolveSessionAgent(event.sessionID, event.agent);
|
|
559
|
+
if (!isRunner(agent))
|
|
560
|
+
return;
|
|
561
|
+
if (event.tool !== "read" && event.tool !== "glob" && event.tool !== "grep")
|
|
562
|
+
return;
|
|
563
|
+
const result = event.result;
|
|
564
|
+
if (result == null)
|
|
565
|
+
return;
|
|
566
|
+
const budgetTool = event.tool;
|
|
567
|
+
const deliveredText = readDeliveredText(result);
|
|
568
|
+
// Image/PDF attachments: the short text lies about the real cost; the
|
|
569
|
+
// runner receives no attachments (v1) and it is delegated to the Inspector.
|
|
570
|
+
if (isImageOrPdfOutput(result)) {
|
|
571
|
+
const actual = deliveredText?.length ?? 0;
|
|
572
|
+
const metadata = { ...(result.metadata ?? {}) };
|
|
573
|
+
delete metadata.attachment;
|
|
574
|
+
result.metadata = metadata;
|
|
575
|
+
const delivery = buildAttachmentDelivery(budgetTool, actual);
|
|
576
|
+
if (Array.isArray(result.content)) {
|
|
577
|
+
const kept = result.content.filter((part) => !isFilePart(part));
|
|
578
|
+
kept.push({ type: "text", text: delivery });
|
|
579
|
+
result.content = kept;
|
|
580
|
+
}
|
|
581
|
+
applyReducedDelivery(result, delivery, "attachment_delegated", {
|
|
582
|
+
omittedChars: actual,
|
|
583
|
+
});
|
|
584
|
+
return;
|
|
585
|
+
}
|
|
586
|
+
// GAP-003: if it cannot be measured, never deliver silently without control:
|
|
587
|
+
// it is observed with a trace and the delivery is marked as unmeasurable. An
|
|
588
|
+
// integration smoke revalidates the mutation.
|
|
589
|
+
if (deliveredText === undefined) {
|
|
590
|
+
console.warn(`[FlowTask Context Budget] could not measure ${budgetTool} output (session ${event.sessionID}); delivering without budgeting.`);
|
|
591
|
+
result.metadata = {
|
|
592
|
+
...(result.metadata ?? {}),
|
|
593
|
+
...buildDegradationMetadata("measurement_unavailable"),
|
|
594
|
+
};
|
|
595
|
+
return;
|
|
596
|
+
}
|
|
597
|
+
const budget = loadContextBudgetConfig(sessionDir || process.cwd(), sessionDir);
|
|
598
|
+
const actual = deliveredText.length;
|
|
599
|
+
// Per-call budget: delivered reduced, without preview, and with the
|
|
600
|
+
// explicit delegation of what was omitted.
|
|
601
|
+
if (actual > (budgetTool === "read" ? budget.readThreshold : budgetTool === "grep" ? budget.grepThreshold : budget.globThreshold)) {
|
|
602
|
+
applyReducedDelivery(result, buildReducedDelivery(budgetTool, actual, "call"), "reduced", {
|
|
603
|
+
budget: "call",
|
|
604
|
+
omittedChars: actual,
|
|
605
|
+
});
|
|
606
|
+
return;
|
|
607
|
+
}
|
|
608
|
+
// Accumulated per-turn budget: even if under the individual threshold, the
|
|
609
|
+
// turn's delivered total cannot exceed the turn budget.
|
|
610
|
+
const state = TURN_STATE.get(event.sessionID) ?? { sum: 0, turn: TURN_SEQ.get(event.sessionID) ?? 0 };
|
|
611
|
+
if (state.sum + actual > budget.turnAccumulated) {
|
|
612
|
+
applyReducedDelivery(result, buildReducedDelivery(budgetTool, actual, "turn"), "turn_omitted", {
|
|
613
|
+
budget: "turn",
|
|
614
|
+
omittedChars: actual,
|
|
615
|
+
});
|
|
616
|
+
return;
|
|
617
|
+
}
|
|
618
|
+
state.sum += actual;
|
|
619
|
+
TURN_STATE.set(event.sessionID, state);
|
|
620
|
+
});
|
|
621
|
+
const promptHook = await ctx.session.hook("prompt", (event) => {
|
|
622
|
+
// Each new prompt opens a turn: it is numbered, the accumulated total is
|
|
623
|
+
// reset, and the turn's narrowing notice state is reset.
|
|
624
|
+
const turn = (TURN_SEQ.get(event.sessionID) ?? 0) + 1;
|
|
625
|
+
TURN_SEQ.set(event.sessionID, turn);
|
|
626
|
+
TURN_STATE.set(event.sessionID, { sum: 0, turn });
|
|
627
|
+
resetNarrowingNotices(event.sessionID);
|
|
628
|
+
});
|
|
629
|
+
return async () => {
|
|
630
|
+
SESSION_AGENTS.clear();
|
|
631
|
+
TURN_STATE.clear();
|
|
632
|
+
TURN_SEQ.clear();
|
|
633
|
+
resetNarrowingNotices();
|
|
634
|
+
await Promise.all([
|
|
635
|
+
promptHook.dispose(),
|
|
636
|
+
beforeHook.dispose(),
|
|
637
|
+
afterHook.dispose(),
|
|
638
|
+
...registered.map((entry) => entry.dispose()),
|
|
639
|
+
]);
|
|
640
|
+
};
|
|
641
|
+
},
|
|
642
|
+
});
|