@gtrabanco/agentic-workflow 0.1.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/README.md ADDED
@@ -0,0 +1,19 @@
1
+ # `@gtrabanco/agentic-workflow`
2
+
3
+ Producer crate for the deterministic agentic-workflow scripts. Feature 37
4
+ created it as the vehicle the roadmap mandated (rows 37/38/42/45, declined 43):
5
+ the first producer feature creates the crate, later producers land their scripts
6
+ as subcommands of it.
7
+
8
+ - **Private, zero dependencies, no build step.** Repository tooling runs with
9
+ bun first and node as the guaranteed fallback (`AGENTS.md` §Verification).
10
+ - **Scratch convention:** `.agentic-workflow/tmp/` at the repository root holds
11
+ throwaway producer output. It is committed as a directory (`.gitkeep`) so the
12
+ convention exists on a fresh clone.
13
+
14
+ Current producers: none yet. `scripts/phase-lint.mjs` deliberately stays in the
15
+ repository's `scripts/` tree (feature 37 ED1). Feature 38's
16
+ `scripts/workflow-status.mjs` landed in that same repository tree before this
17
+ crate existed, so re-homing it here is a recorded follow-up (feature 37
18
+ ED8.4c) with no unit assigned yet; feature 42 is the next candidate to add the
19
+ first crate subcommand.
package/bin/agwo.mjs ADDED
@@ -0,0 +1,237 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * agwo — CLI router for agentic-workflow typed file services.
4
+ *
5
+ * Usage:
6
+ * agwo unit-doc <NN-slug> [--dir <root>] <op> [args...]
7
+ * agwo roadmap <op> [args...]
8
+ * agwo changelog <op> [args...]
9
+ * agwo budgets <op> [args...]
10
+ * agwo manifest <op> [args...]
11
+ *
12
+ * --json prints the operation receipt as JSON.
13
+ * Every operation prints a fixed receipt block to stdout.
14
+ *
15
+ * Refusals exit 2 with "EDIT REFUSAL — <reason>" before writing anything.
16
+ */
17
+
18
+ import { readFileSync } from "node:fs";
19
+ import { join, resolve, basename } from "node:path";
20
+
21
+ // Import SDK modules
22
+ import { create, setSection, evidence_addRow, progress_logEntry, validate } from "../src/edit/UnitDoc.mjs";
23
+ import { rowUpsert, annotate as roadmapAnnotate } from "../src/edit/Roadmap.mjs";
24
+ import { rowAdd } from "../src/edit/Changelog.mjs";
25
+ import { ceilingRebase } from "../src/edit/Budgets.mjs";
26
+ import { skillAdd, skillRemove } from "../src/edit/Manifest.mjs";
27
+
28
+ // ── Helpers ──────────────────────────────────────────────────────────────
29
+
30
+ function printReceipt(receipt) {
31
+ console.log("");
32
+ console.log(`EDIT ${receipt.service}.${receipt.op} — ${receipt.path}`);
33
+ console.log(`Schema: ${receipt.schema} · Receipt: ${receipt.ok ? "pass" : "fail"}`);
34
+ console.log(`Before: ${receipt.before} · After: ${receipt.after}`);
35
+ }
36
+
37
+ function parseArgs(args) {
38
+ const result = {};
39
+ const positions = [];
40
+ let i = 0;
41
+ while (i < args.length) {
42
+ if (args[i] === "--json") {
43
+ result.json = true;
44
+ i++;
45
+ } else if (args[i] === "--dir") {
46
+ result.dir = args[i + 1];
47
+ i += 2;
48
+ } else {
49
+ positions.push(args[i]);
50
+ i++;
51
+ }
52
+ }
53
+ result.args = positions;
54
+ return result;
55
+ }
56
+
57
+ function refuse(reason) {
58
+ process.stderr.write(`EDIT REFUSAL — ${reason}\n`);
59
+ process.exit(2);
60
+ }
61
+
62
+ // ── Router ───────────────────────────────────────────────────────────────
63
+
64
+ const command = process.argv[2];
65
+ if (!command) {
66
+ console.error("usage: agwo <unit-doc|roadmap|changelog|budgets|manifest> ...");
67
+ process.exit(1);
68
+ }
69
+
70
+ const restArgs = process.argv.slice(3);
71
+ const parsed = parseArgs(restArgs);
72
+ const rawArgs = parsed.args;
73
+
74
+ switch (command) {
75
+ // ── unit-doc ─────────────────────────────────────────────────────────
76
+ case "unit-doc": {
77
+ const slug = rawArgs[0];
78
+ const op = rawArgs[1];
79
+ if (!slug || !op) refuse("unit-doc requires <slug> <operation> [args...]");
80
+
81
+ const rootDir = parsed.dir ? resolve(parsed.dir) : process.cwd();
82
+ const unitDir = join(rootDir, "docs", "features", slug);
83
+
84
+ if (op === "create") {
85
+ try {
86
+ const receipt = create(unitDir, slug);
87
+ if (parsed.json) console.log(JSON.stringify(receipt, null, 2));
88
+ else printReceipt(receipt);
89
+ } catch (e) {
90
+ refuse(e.message);
91
+ }
92
+ } else if (op === "setSection") {
93
+ if (rawArgs.length < 4) refuse("setSection requires <slug> <section> <body_file|body>");
94
+ const section = rawArgs[2];
95
+ let body;
96
+ try {
97
+ body = readFileSync(rawArgs[3], "utf8");
98
+ } catch {
99
+ body = rawArgs[3];
100
+ }
101
+ try {
102
+ const receipt = setSection(join(unitDir, "SPEC.md"), section, body);
103
+ if (parsed.json) console.log(JSON.stringify(receipt, null, 2));
104
+ else printReceipt(receipt);
105
+ } catch (e) {
106
+ refuse(e.message);
107
+ }
108
+ } else if (op === "evidence") {
109
+ try {
110
+ const body = rawArgs[2] ? JSON.parse(rawArgs[2]) : {};
111
+ const receipt = evidence_addRow(join(unitDir, "SPEC.md"), body);
112
+ if (parsed.json) console.log(JSON.stringify(receipt, null, 2));
113
+ else printReceipt(receipt);
114
+ } catch (e) {
115
+ refuse(e.message);
116
+ }
117
+ } else if (op === "progress") {
118
+ try {
119
+ const body = rawArgs[2] ? JSON.parse(rawArgs[2]) : {};
120
+ const receipt = progress_logEntry(join(unitDir, "SPEC.md"), body);
121
+ if (parsed.json) console.log(JSON.stringify(receipt, null, 2));
122
+ else printReceipt(receipt);
123
+ } catch (e) {
124
+ refuse(e.message);
125
+ }
126
+ } else if (op === "validate") {
127
+ try {
128
+ const content = readFileSync(join(unitDir, "SPEC.md"), "utf8");
129
+ const result = validate(content);
130
+ if (parsed.json) console.log(JSON.stringify(result, null, 2));
131
+ else console.log(JSON.stringify(result, null, 2));
132
+ } catch (e) {
133
+ refuse(e.message);
134
+ }
135
+ } else {
136
+ refuse(`Unknown unit-doc operation: ${op}`);
137
+ }
138
+ break;
139
+ }
140
+
141
+ // ── roadmap ──────────────────────────────────────────────────────────
142
+ case "roadmap": {
143
+ const filePath = rawArgs[0] ? resolve(rawArgs[0]) : join(process.cwd(), "ROADMAP.md");
144
+
145
+ if (rawArgs[0] === "rowUpsert" || (rawArgs[0] && rawArgs[1] === "rowUpsert")) {
146
+ // Skip file path if it's the first positional
147
+ const data = rawArgs[1] === "rowUpsert" ? (rawArgs[2] ? JSON.parse(rawArgs[2]) : {}) : JSON.parse(rawArgs[1] || "{}");
148
+ try {
149
+ const receipt = rowUpsert(filePath, data);
150
+ if (parsed.json) console.log(JSON.stringify(receipt, null, 2));
151
+ else printReceipt(receipt);
152
+ } catch (e) {
153
+ refuse(e.message);
154
+ }
155
+ } else if (rawArgs[0] === "annotate" || (rawArgs[0] && rawArgs[1] === "annotate")) {
156
+ const nn = rawArgs[1] === "annotate" ? rawArgs[2] : rawArgs[1];
157
+ const note = rawArgs[1] === "annotate" ? rawArgs[3] || "" : (rawArgs[2] || "");
158
+ try {
159
+ const receipt = roadmapAnnotate(filePath, nn, note);
160
+ if (parsed.json) console.log(JSON.stringify(receipt, null, 2));
161
+ else printReceipt(receipt);
162
+ } catch (e) {
163
+ refuse(e.message);
164
+ }
165
+ } else {
166
+ refuse(`Unknown roadmap operation`);
167
+ }
168
+ break;
169
+ }
170
+
171
+ // ── changelog ────────────────────────────────────────────────────────
172
+ case "changelog": {
173
+ const filePath = rawArgs[0] ? resolve(rawArgs[0]) : join(process.cwd(), "CHANGELOG.md");
174
+ const data = rawArgs[1] ? JSON.parse(rawArgs[1]) : {};
175
+
176
+ try {
177
+ // Format: changelog <data_json> — sectionName inferred from data or first arg
178
+ const sectionName = data.section || data.skill || rawArgs[1] ? "default" : "default";
179
+ const receipt = rowAdd(filePath, sectionName, data);
180
+ if (parsed.json) console.log(JSON.stringify(receipt, null, 2));
181
+ printReceipt(receipt);
182
+ } catch (e) {
183
+ refuse(e.message);
184
+ }
185
+ break;
186
+ }
187
+
188
+ // ── budgets ──────────────────────────────────────────────────────────
189
+ case "budgets": {
190
+ const filePath = rawArgs[0] ? resolve(rawArgs[0]) : join(process.cwd(), "budgets.json");
191
+ const data = rawArgs[1] ? JSON.parse(rawArgs[1]) : {};
192
+ const { version, date, type, what, section, skill } = {};
193
+
194
+ try {
195
+ const receipt = ceilingRebase(filePath, data.route, data.estimateMax, data.linesMax, data.growthSource);
196
+ if (parsed.json) console.log(JSON.stringify(receipt, null, 2));
197
+ printReceipt(receipt);
198
+ if (!receipt.ok) refuse("Ceiling shrinkage without growth source");
199
+ } catch (e) {
200
+ refuse(e.message);
201
+ }
202
+ break;
203
+ }
204
+
205
+ // ── manifest ─────────────────────────────────────────────────────────
206
+ case "manifest": {
207
+ const pluginJson = rawArgs[0] ? resolve(rawArgs[0]) : join(process.cwd(), ".claude-plugin", "plugin.json");
208
+ const op = rawArgs[1] || "";
209
+
210
+ if (op === "skillAdd") {
211
+ const skillName = rawArgs[2] || "";
212
+ const meta = rawArgs[3] ? JSON.parse(rawArgs[3]) : {};
213
+ try {
214
+ const receipt = skillAdd(pluginJson, skillName, meta);
215
+ if (parsed.json) console.log(JSON.stringify(receipt, null, 2));
216
+ else printReceipt(receipt);
217
+ } catch (e) {
218
+ refuse(e.message);
219
+ }
220
+ } else if (op === "skillRemove") {
221
+ const skillName = rawArgs[2] || "";
222
+ try {
223
+ const receipt = skillRemove(pluginJson, skillName);
224
+ if (parsed.json) console.log(JSON.stringify(receipt, null, 2));
225
+ else printReceipt(receipt);
226
+ } catch (e) {
227
+ refuse(e.message);
228
+ }
229
+ } else {
230
+ refuse(`Unknown manifest operation: ${op}`);
231
+ }
232
+ break;
233
+ }
234
+
235
+ default:
236
+ refuse(`Unknown service: ${command}`);
237
+ }
@@ -0,0 +1,263 @@
1
+ #!/usr/bin/env node
2
+ // Tier 1 path-protection gate (feature 60).
3
+ //
4
+ // Deterministic, read-only, offline: it reads the effective policy, the plan
5
+ // declaration, the escape records, and the changed paths derived from git,
6
+ // evaluates every (path, operation) pair, and prints one fixed block. It writes
7
+ // nothing (the git reads use `--no-optional-locks`, so not even `.git/index`).
8
+ //
9
+ // usage: path-guard --unit <unit-dir> --phase <P<n>> [--base <ref>] [--help]
10
+ // prints:
11
+ // PATH-GUARD <pass|fail> — <code>
12
+ // offenders: <path:operation:reason[, …]|none>
13
+ // phase: <P<n>> · freeze-after: <P<m>|none|n/a> · checked: <n> (n/a when no declaration)
14
+ // DEGRADED — <code>: <detail> (only when a degradation is reported; code ∈
15
+ // missing-config | malformed-config | ignored-removal | ignored-lowering)
16
+ // exit: 0 pass | 1 fail | 2 usage error
17
+
18
+ import { spawnSync } from "node:child_process";
19
+ import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
20
+ import path from "node:path";
21
+
22
+ import {
23
+ CHANGED_PATH_LIMIT,
24
+ PATH_POLICY_MAX_BYTES,
25
+ SHIPPED_PATH_POLICY,
26
+ evaluatePathGuard,
27
+ parsePathPolicy,
28
+ parsePlanDeclaration,
29
+ parseRecords,
30
+ resolvePathPolicy,
31
+ } from "../src/path-policy.mjs";
32
+
33
+ const USAGE =
34
+ "usage: path-guard --unit <unit-dir> --phase <P<n>> [--base <ref>] [--help]\n\n" +
35
+ " --unit <dir> the unit directory holding the plan declaration and records\n" +
36
+ " --phase <P<n>> the phase whose protected changes are checked\n" +
37
+ " --base <ref> union the committed range <ref>..HEAD into the changed paths\n" +
38
+ " --help print this usage and exit 0\n";
39
+
40
+ /** Run git. `ok` is false when the process could not run or exited non-zero. */
41
+ function runGit(root, args) {
42
+ const result = spawnSync("git", ["--no-optional-locks", "-C", root, ...args], {
43
+ encoding: "utf8",
44
+ stdio: ["ignore", "pipe", "ignore"],
45
+ });
46
+ return { ok: result.status === 0 && result.error === undefined, stdout: result.status === 0 ? result.stdout : "" };
47
+ }
48
+
49
+ const PHASE_RE = /^P\d+$/;
50
+
51
+ /** Map a porcelain v1 `-z` status pair to an operation. Both columns count: an unstaged deletion (` D`) is a delete. */
52
+ function operationFor(index, worktree) {
53
+ if (index === "?" || worktree === "?") return "create";
54
+ if (index === "A" || index === "C") return "create";
55
+ if (index === "D" || worktree === "D") return "delete";
56
+ return "modify";
57
+ }
58
+
59
+ function parsePorcelain(raw) {
60
+ const changes = [];
61
+ const tokens = raw.split("\0");
62
+ for (let index = 0; index < tokens.length; index += 1) {
63
+ const entry = tokens[index];
64
+ if (entry === "") continue;
65
+ const x = entry[0];
66
+ const y = entry[1];
67
+ const target = entry.slice(3);
68
+ if (x === "R" || x === "C") {
69
+ const original = tokens[(index += 1)] ?? "";
70
+ changes.push({ path: target, operation: "create" });
71
+ if (original !== "") changes.push({ path: original, operation: "delete" });
72
+ continue;
73
+ }
74
+ if (target === "") continue;
75
+ const operation = operationFor(x, y);
76
+ if (operation === "rename") {
77
+ changes.push({ path: target, operation: "create" });
78
+ changes.push({ path: target, operation: "delete" });
79
+ continue;
80
+ }
81
+ changes.push({ path: target, operation });
82
+ }
83
+ return changes;
84
+ }
85
+
86
+ function parseNameStatus(raw) {
87
+ const changes = [];
88
+ const tokens = raw.split("\0");
89
+ for (let index = 0; index < tokens.length; index += 1) {
90
+ const status = tokens[index];
91
+ if (status === "") continue;
92
+ const code = status[0];
93
+ if (code === "R" || code === "C") {
94
+ const original = tokens[(index += 1)] ?? "";
95
+ const target = tokens[(index += 1)] ?? "";
96
+ if (target) changes.push({ path: target, operation: "create" });
97
+ if (original) changes.push({ path: original, operation: "delete" });
98
+ continue;
99
+ }
100
+ const target = tokens[(index += 1)];
101
+ if (!target) continue;
102
+ const operation = code === "A" ? "create" : code === "D" ? "delete" : "modify";
103
+ changes.push({ path: target, operation });
104
+ }
105
+ return changes;
106
+ }
107
+
108
+ function dedupe(changes) {
109
+ const seen = new Set();
110
+ const out = [];
111
+ for (const change of changes) {
112
+ const key = `${change.path}\0${change.operation}`;
113
+ if (seen.has(key)) continue;
114
+ seen.add(key);
115
+ out.push(change);
116
+ }
117
+ return out;
118
+ }
119
+
120
+ function fail(message) {
121
+ process.stderr.write(`path-guard: ${message}\n`);
122
+ process.stderr.write(USAGE);
123
+ return 2;
124
+ }
125
+
126
+ function main(argv) {
127
+ const args = [...argv];
128
+ let unit = "";
129
+ let phase = "";
130
+ let base = "";
131
+ while (args.length > 0) {
132
+ const arg = args.shift();
133
+ if (arg === "--help") {
134
+ process.stdout.write(USAGE);
135
+ return 0;
136
+ }
137
+ if (arg === "--unit") unit = args.shift() ?? "";
138
+ else if (arg === "--phase") phase = args.shift() ?? "";
139
+ else if (arg === "--base") base = args.shift() ?? "";
140
+ else return fail(`unknown argument: ${arg}`);
141
+ }
142
+ if (unit === "") return fail("--unit is required");
143
+ if (phase === "" || !PHASE_RE.test(phase)) return fail("--phase must be P<n>");
144
+
145
+ const cwd = process.cwd();
146
+ const top = runGit(cwd, ["rev-parse", "--show-toplevel"]);
147
+ if (!top.ok || top.stdout.trim() === "") return fail("not inside a git repository");
148
+ const repoRoot = top.stdout.trimEnd();
149
+
150
+ // The unit directory must stay inside the repository: an out-of-root --unit
151
+ // could read a fabricated declaration/records and flip a failing gate to pass
152
+ // (F22). The containment test runs on the resolved (realpath) unit, because a
153
+ // lexical comparison lets an in-repo symlink point the reads outside the root
154
+ // (F26). A unit that does not resolve keeps its lexical spelling, and the
155
+ // missing declaration then fails closed below.
156
+ const unitPath = path.resolve(cwd, unit);
157
+ let realRepoRoot = repoRoot;
158
+ try {
159
+ realRepoRoot = realpathSync(repoRoot);
160
+ } catch {
161
+ // `git rev-parse --show-toplevel` names an existing directory; keep the lexical root.
162
+ }
163
+ let realUnitPath = unitPath;
164
+ try {
165
+ realUnitPath = realpathSync(unitPath);
166
+ } catch {
167
+ // The unit directory does not exist (or is unreadable): keep the lexical path.
168
+ }
169
+ const unitRelative = path.relative(realRepoRoot, realUnitPath);
170
+ if (
171
+ unitRelative === "" ||
172
+ unitRelative === ".." ||
173
+ unitRelative.startsWith(`..${path.sep}`) ||
174
+ path.isAbsolute(unitRelative)
175
+ ) {
176
+ return fail("--unit must be a directory inside the repository");
177
+ }
178
+
179
+ // Changed paths: the dirty working tree, unioned with the committed range.
180
+ // A git failure is a gate error, never an empty change list (F5): an
181
+ // unresolvable `--base` must not read as "nothing changed".
182
+ const status = runGit(repoRoot, ["status", "--porcelain=v1", "-z", "--untracked-files=all"]);
183
+ if (!status.ok) return fail("git status failed; cannot determine the changed paths");
184
+ let changes = parsePorcelain(status.stdout);
185
+ if (base !== "") {
186
+ // Resolve the ref first and diff the resolved commit, so a value beginning
187
+ // with `-` can never reach git's option parser (F6).
188
+ const resolved = runGit(repoRoot, ["rev-parse", "--verify", "--quiet", "--end-of-options", `${base}^{commit}`]);
189
+ const baseCommit = resolved.stdout.trim().split(/\r?\n/).pop() ?? "";
190
+ if (!resolved.ok || baseCommit === "") return fail(`unknown base ref: ${base}`);
191
+ // `T` (typechange, e.g. a committed file replaced by a symlink) is a
192
+ // protected modification; excluding it made the committed-range gate a
193
+ // fail-open on exactly the invocation the preflight mandates (F25).
194
+ const diff = runGit(repoRoot, ["diff", "--name-status", "-z", "--diff-filter=ACMRDT", baseCommit]);
195
+ if (!diff.ok) return fail("git diff failed; cannot determine the committed range");
196
+ changes = changes.concat(parseNameStatus(diff.stdout));
197
+ }
198
+ changes = dedupe(changes);
199
+ if (changes.length > CHANGED_PATH_LIMIT) return fail(`changed-path list exceeds ${CHANGED_PATH_LIMIT} entries`);
200
+
201
+ // Effective policy: the project doc config over the shipped defaults.
202
+ const degradations = [];
203
+ const policyPath = path.join(repoRoot, ".agentic-workflow", "path-policy.json");
204
+ let policy = resolvePathPolicy(SHIPPED_PATH_POLICY, null);
205
+ if (!existsSync(policyPath)) {
206
+ degradations.push({ code: "missing-config", detail: "shipped defaults in force" });
207
+ } else {
208
+ let malformed = null;
209
+ try {
210
+ if (statSync(policyPath).size > PATH_POLICY_MAX_BYTES) malformed = "policy exceeds the size bound";
211
+ else {
212
+ const parsed = parsePathPolicy(readFileSync(policyPath, "utf8"));
213
+ if (parsed.ok) policy = resolvePathPolicy(SHIPPED_PATH_POLICY, parsed.policy);
214
+ else malformed = parsed.message;
215
+ }
216
+ } catch (error) {
217
+ malformed = error instanceof Error ? error.message : String(error);
218
+ }
219
+ if (malformed !== null) {
220
+ policy = resolvePathPolicy(SHIPPED_PATH_POLICY, null);
221
+ degradations.push({ code: "malformed-config", detail: `shipped defaults in force — ${malformed}` });
222
+ }
223
+ }
224
+ for (const record of policy.degradations) degradations.push(record);
225
+
226
+ // Plan declaration (PLAN.md, else the SPEC's own block).
227
+ const planFile = path.join(unitPath, "PLAN.md");
228
+ const specFile = path.join(unitPath, "SPEC.md");
229
+ let declaration = null;
230
+ if (existsSync(planFile)) declaration = parsePlanDeclaration(readFileSync(planFile, "utf8"));
231
+ else if (existsSync(specFile)) declaration = parsePlanDeclaration(readFileSync(specFile, "utf8"));
232
+ if (declaration !== null && declaration.ok) declaration = declaration.declaration;
233
+ else if (declaration !== null) declaration = null;
234
+
235
+ // Escape records (the unit's decisions ledger; a missing block means none).
236
+ const decisionsFile = path.join(unitPath, "decisions.md");
237
+ let records = [];
238
+ if (existsSync(decisionsFile)) {
239
+ const parsed = parseRecords(readFileSync(decisionsFile, "utf8"));
240
+ if (!parsed.ok) declaration = null;
241
+ else records = parsed.records;
242
+ }
243
+
244
+ const result = evaluatePathGuard({ changes, policy, declaration, records, phase });
245
+ const offenders =
246
+ result.offenders.length === 0
247
+ ? "none"
248
+ : result.offenders.map((offender) => `${offender.path}:${offender.operation}:${offender.reason}`).join(", ");
249
+ const freezeAfter =
250
+ declaration === null || declaration.freezeAfter === undefined ? "n/a" : (declaration.freezeAfter ?? "none");
251
+
252
+ const lines = [
253
+ `PATH-GUARD ${result.verdict} — ${result.reason}`,
254
+ `offenders: ${offenders}`,
255
+ `phase: ${phase} · freeze-after: ${freezeAfter} · checked: ${changes.length}`,
256
+ ];
257
+ for (const degradation of degradations) lines.push(`DEGRADED — ${degradation.code}: ${degradation.detail}`);
258
+ process.stdout.write(`${lines.join("\n")}\n`);
259
+
260
+ return result.verdict === "pass" ? 0 : 1;
261
+ }
262
+
263
+ process.exitCode = main(process.argv.slice(2));