@warpgogol/forge 10.1.1 → 10.2.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.
@@ -10,7 +10,7 @@ spawn, no git mutation. This is auditability, not a sandbox.
10
10
  <CHANGE_SUMMARY><item>RFC-1648 (WP-5): initial capability-enforcing context.</item></CHANGE_SUMMARY>
11
11
  */
12
12
 
13
- import { access, mkdir, readFile, readdir, writeFile } from "node:fs/promises";
13
+ import { access, lstat, mkdir, readFile, readdir, readlink, rename, rm, stat, symlink, unlink, writeFile } from "node:fs/promises";
14
14
  import { execFile } from "node:child_process";
15
15
  import { dirname, resolve as pathResolve } from "node:path";
16
16
  import { promisify } from "node:util";
@@ -29,6 +29,58 @@ export interface ContextHostServices {
29
29
  };
30
30
  }
31
31
 
32
+ /* Dual-use commands (tag/branch/config) are conservative-denied: listing refs
33
+ belongs to for-each-ref plumbing, config reads to file parsing. A security
34
+ boundary refuses false negatives at the cost of false-positive friction. */
35
+ const MUTATING_GIT_OPS = new Set(["commit", "push", "update-ref", "checkout", "reset", "rebase", "merge", "cherry-pick", "apply", "commit-tree", "tag", "branch", "am", "stash", "rm", "mv", "clean", "gc", "fetch", "pull", "clone", "init", "add", "notes", "replace", "filter-branch", "update-index", "write-tree", "symbolic-ref", "worktree", "reflog", "config"]);
36
+
37
+ /* Git global flags consuming a separate value token — the subcommand is the first
38
+ positional after these are skipped. `--flag=value` forms self-skip. */
39
+ const GIT_VALUE_FLAGS = new Set(["-C", "-c", "--git-dir", "--work-tree", "--namespace", "--config-env", "--exec-path"]);
40
+
41
+ export function gitSubcommand(args: string[]): string | undefined {
42
+ let i = 0;
43
+ while (i < args.length) {
44
+ const a = args[i];
45
+ if (GIT_VALUE_FLAGS.has(a)) {
46
+ i += 2;
47
+ continue;
48
+ }
49
+ if (a.startsWith("-")) {
50
+ i += 1;
51
+ continue;
52
+ }
53
+ return a;
54
+ }
55
+ return undefined;
56
+ }
57
+
58
+ /* Resolve the git COMMON dir without spawning git: in a primary checkout .git is the
59
+ dir itself; in a worktree it is a pointer file (`gitdir: <common>/worktrees/<name>`)
60
+ and the common dir is two levels up. Returns null when no git state exists. */
61
+ export async function resolveGitCommonDir(workspaceRoot: string): Promise<string | null> {
62
+ const dotGit = pathResolve(workspaceRoot, ".git");
63
+ try {
64
+ const st = await lstat(dotGit);
65
+ if (st.isDirectory()) return dotGit;
66
+ if (!st.isFile()) return null;
67
+ } catch {
68
+ return null;
69
+ }
70
+ try {
71
+ const content = await readFile(dotGit, "utf8");
72
+ const m = content.match(/^gitdir:\s*(.+)$/m);
73
+ if (!m) return null;
74
+ const gitdirPath = pathResolve(workspaceRoot, m[1].trim());
75
+ // <common>/worktrees/<name> — strip the two trailing segments.
76
+ const parts = gitdirPath.split("/").filter((p) => p.length > 0);
77
+ if (parts.length < 3) return null;
78
+ return "/" + parts.slice(0, -2).join("/");
79
+ } catch {
80
+ return null;
81
+ }
82
+ }
83
+
32
84
  /** Build a capability-enforcing PluginContext for one activated plugin. */
33
85
  export function createPluginContext(manifest: PluginManifest, host: ContextHostServices): PluginContext {
34
86
  const caps = manifest.capabilities ?? {};
@@ -72,6 +124,40 @@ export function createPluginContext(manifest: PluginManifest, host: ContextHostS
72
124
  if (fsGrant === "none") deny("filesystem", "list with filesystem:none");
73
125
  return readdir(scoped(dir));
74
126
  },
127
+ async readlink(path) {
128
+ if (fsGrant === "none") deny("filesystem", "readlink with filesystem:none");
129
+ return readlink(scoped(path));
130
+ },
131
+ async symlink(target, linkPath) {
132
+ if (fsGrant !== "readwrite") deny("filesystem", `symlink with filesystem:${fsGrant}`);
133
+ // The link PATH is sandboxed; the link TARGET is not re-validated — scoped()
134
+ // is a textual check, so a link pointing outside the root escapes on follow.
135
+ // readwrite is a trusted-within-workspace grant (it can already overwrite
136
+ // forge.yaml and hooks); symlink creation is consistent with that trust level.
137
+ // Plugins needing strict containment must not receive readwrite.
138
+ await symlink(target, scoped(linkPath));
139
+ },
140
+ async unlink(path) {
141
+ if (fsGrant !== "readwrite") deny("filesystem", `unlink with filesystem:${fsGrant}`);
142
+ await unlink(scoped(path));
143
+ },
144
+ async readFileBytes(path) {
145
+ if (fsGrant === "none") deny("filesystem", "readFileBytes with filesystem:none");
146
+ return new Uint8Array(await readFile(scoped(path)));
147
+ },
148
+ async rename(from, to) {
149
+ if (fsGrant !== "readwrite") deny("filesystem", `rename with filesystem:${fsGrant}`);
150
+ await rename(scoped(from), scoped(to));
151
+ },
152
+ async rm(path, opts) {
153
+ if (fsGrant !== "readwrite") deny("filesystem", `rm with filesystem:${fsGrant}`);
154
+ await rm(scoped(path), { recursive: opts?.recursive ?? false, force: true });
155
+ },
156
+ async stat(path) {
157
+ if (fsGrant === "none") deny("filesystem", "stat with filesystem:none");
158
+ const st = await stat(scoped(path));
159
+ return { size: st.size, mtimeMs: st.mtimeMs, isDirectory: st.isDirectory() };
160
+ },
75
161
  },
76
162
  evidence: {
77
163
  consult: host.hooks?.evidenceConsult ?? (async () => ({ hit: false })),
@@ -91,8 +177,17 @@ export function createPluginContext(manifest: PluginManifest, host: ContextHostS
91
177
  },
92
178
  git: {
93
179
  async exec(args) {
94
- if (!caps.gitMutation && ["commit", "push", "update-ref", "checkout", "reset", "rebase", "merge", "cherry-pick", "apply"].some((m) => args[0] === m)) {
95
- deny("gitMutation", `mutating git op refused: git ${args[0]}`);
180
+ // Redirection flags escape the workspace scope for reads AND writes — refused outright.
181
+ for (const a of args) {
182
+ if (a === "-C" || a === "--git-dir" || a === "--work-tree" || a.startsWith("--git-dir=") || a.startsWith("--work-tree=")) {
183
+ deny("filesystem", `git scope redirection refused: ${a}`);
184
+ }
185
+ }
186
+ if (!caps.gitMutation) {
187
+ const subcommand = gitSubcommand(args);
188
+ if (subcommand && MUTATING_GIT_OPS.has(subcommand)) {
189
+ deny("gitMutation", `mutating git op refused: git ${subcommand}`);
190
+ }
96
191
  }
97
192
  const { stdout } = await execFileAsync("git", args, { cwd: host.workspaceRoot });
98
193
  return stdout;
@@ -122,6 +217,54 @@ export function createPluginContext(manifest: PluginManifest, host: ContextHostS
122
217
  return { status: res.status, body: await res.text() };
123
218
  },
124
219
  },
220
+ forgeState: {
221
+ journal: {
222
+ async tail(count) {
223
+ if ((caps.forgeState ?? "none") === "none") deny("forgeState", "journal.tail with forgeState:none");
224
+ const common = await resolveGitCommonDir(host.workspaceRoot);
225
+ if (!common) return [];
226
+ const journalPath = pathResolve(common, "forge", "journal.jsonl");
227
+ let text: string;
228
+ try {
229
+ text = await readFile(journalPath, "utf8");
230
+ } catch {
231
+ return [];
232
+ }
233
+ const lines = text.split("\n").filter((l) => l.trim().length > 0);
234
+ const records = [];
235
+ for (const line of lines.slice(-count)) {
236
+ try {
237
+ records.push(JSON.parse(line));
238
+ } catch {
239
+ records.push({ event: "torn-line" });
240
+ }
241
+ }
242
+ return records;
243
+ },
244
+ async size() {
245
+ if ((caps.forgeState ?? "none") === "none") deny("forgeState", "journal.size with forgeState:none");
246
+ const common = await resolveGitCommonDir(host.workspaceRoot);
247
+ if (!common) return 0;
248
+ try {
249
+ const text = await readFile(pathResolve(common, "forge", "journal.jsonl"), "utf8");
250
+ return text.split("\n").filter((l) => l.trim().length > 0).length;
251
+ } catch {
252
+ return 0;
253
+ }
254
+ },
255
+ },
256
+ },
257
+ env: {
258
+ get(key) {
259
+ if (!(caps.envKeys ?? []).includes(key)) {
260
+ deny("env", `env key not declared in manifest envKeys: ${key}`);
261
+ }
262
+ return process.env[key];
263
+ },
264
+ declared(key) {
265
+ return (caps.envKeys ?? []).includes(key);
266
+ },
267
+ },
125
268
  log: {
126
269
  info: (msg) => console.log(`[${pid}] ${msg}`),
127
270
  warn: (msg) => console.warn(`[${pid}] ${msg}`),
package/src/sdk/loader.ts CHANGED
@@ -22,12 +22,20 @@ import { LIFECYCLE_HOOKS, PluginLoadError, type CommandModule, type HookModule,
22
22
 
23
23
  /** The running core version — plugins' forgeRange is checked against this. */
24
24
  export function coreVersion(): string {
25
- try {
26
- const pkg = JSON.parse(readFileSync(join(import.meta.dirname ?? __dirname, "../../package.json"), "utf8"));
27
- return pkg.version as string;
28
- } catch {
29
- return "10.0.0";
25
+ // The compiled artifact lives one level deeper than the source module
26
+ // (dist/src/sdk/loader.js vs src/sdk/loader.ts) — probe both layouts.
27
+ const here = import.meta.dirname ?? __dirname;
28
+ for (const candidate of ["../../package.json", "../../../package.json"]) { // pkg-health-10: defensive probe — each candidate intentionally misses in one layout (src vs dist) and hits in the other; miss is the designed path
29
+ try {
30
+ const pkg = JSON.parse(readFileSync(join(here, candidate), "utf8")) as { name?: string; version?: string };
31
+ if (pkg.name === "@warpgogol/forge" && typeof pkg.version === "string") {
32
+ return pkg.version;
33
+ }
34
+ } catch {
35
+ // try the next layout candidate
36
+ }
30
37
  }
38
+ return "10.0.0";
31
39
  }
32
40
 
33
41
  function semverSatisfies(version: string, range: string): boolean {
package/src/sdk/types.ts CHANGED
@@ -23,6 +23,9 @@ export interface PluginManifest {
23
23
  processSpawn?: boolean;
24
24
  gitMutation?: boolean;
25
25
  envKeys?: string[];
26
+ /* forge's own state space (.git/forge/) lives outside the workspace sandbox in
27
+ worktrees — access is a distinct grant, never a widening of filesystem. */
28
+ forgeState?: "none" | "read";
26
29
  };
27
30
  registers: {
28
31
  commands?: string[];
@@ -80,6 +83,15 @@ export interface WorkspaceIOPort {
80
83
  writeFile(path: string, content: string): Promise<void>;
81
84
  exists(path: string): Promise<boolean>;
82
85
  list(dir: string, pattern?: string): Promise<string[]>;
86
+ /* Symlink primitives — atomic deploy swaps and artifact layouts are link-based;
87
+ readFile follows links and can never observe the link itself. */
88
+ readlink(path: string): Promise<string>;
89
+ symlink(target: string, linkPath: string): Promise<void>;
90
+ unlink(path: string): Promise<void>;
91
+ readFileBytes(path: string): Promise<Uint8Array>;
92
+ rename(from: string, to: string): Promise<void>;
93
+ rm(path: string, opts?: { recursive?: boolean }): Promise<void>;
94
+ stat(path: string): Promise<{ size: number; mtimeMs: number; isDirectory: boolean }>;
83
95
  }
84
96
 
85
97
  export interface EvidenceAccessPort {
@@ -128,6 +140,40 @@ export interface PluginContext {
128
140
  network: NetworkPort;
129
141
  log: LoggerPort;
130
142
  paths: PathResolverPort;
143
+ env: EnvPort;
144
+ forgeState: ForgeStatePort;
145
+ }
146
+
147
+ /* The journal record shape is open-ended by design — the flow machinery evolves
148
+ the schema; the measured discriminator is `event` (never `kind`). */
149
+ export interface JournalRecord {
150
+ at?: string;
151
+ event?: string;
152
+ branch?: string;
153
+ sha?: string;
154
+ detail?: string;
155
+ [key: string]: unknown;
156
+ }
157
+
158
+ /* Host-implemented reads of forge's own state space — plugins never observe
159
+ gitdir layout, matching the evidence.consult pattern. */
160
+ export interface ForgeStatePort {
161
+ journal: {
162
+ /* Last count records, oldest-first; empty when no journal exists. */
163
+ tail(count: number): Promise<JournalRecord[]>;
164
+ /* Total line count — cheaper than reading when only existence matters. */
165
+ size(): Promise<number>;
166
+ };
167
+ }
168
+
169
+ /* Env access is allowlist-enforced: the manifest's envKeys declares exactly which
170
+ variables the plugin may read — secrets-adjacent access stays transparent and
171
+ auditable at the manifest surface, never a blanket process.env passthrough. */
172
+ export interface EnvPort {
173
+ /** Declared key → value or undefined; undeclared key → CapabilityViolation. */
174
+ get(key: string): string | undefined;
175
+ /** Whether the key is declared in the manifest — no leakage of presence vs value. */
176
+ declared(key: string): boolean;
131
177
  }
132
178
 
133
179
  /** Typed incompatibility error — fail-closed, no degraded modes. */