god-prompt-mcp 1.0.45 → 1.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 CHANGED
@@ -12,6 +12,8 @@ GodPrompt offers a bounded Agent Harness Review for developers and small teams w
12
12
 
13
13
  To buy the review, use the [US$49 one-time GitHub Sponsors tier](https://github.com/sponsors/AKzar1el/sponsorships?tier_id=657478&metadata_campaign=godprompt_rs1&metadata_offer=agent_harness_review&metadata_source=mcp). GitHub sign-in is required. After sponsoring, email `info@tomiseregi.si` with subject `[GP-RS1] Agent Harness Review` and include the GitHub username used for the sponsorship plus the review inputs. Delivery begins after the US$49 sponsorship is independently verified for this review. The free MIT GodPrompt MCP remains unchanged and free. [See a transparent sample deliverable](https://github.com/AKzar1el/god-prompt/blob/main/AGENT_HARNESS_REVIEW_SAMPLE.md) before deciding; it is illustrative, not a client result or benchmark. [Full frozen experiment terms](https://github.com/AKzar1el/god-prompt/blob/main/MONETIZATION_EXPERIMENT.md).
14
14
 
15
+ **Before emailing, sanitize your review inputs:** remove passwords, API keys, access tokens, recovery codes, regulated or unrelated personal data, and unrelated private repository content. Do not send `.env` files, full private repositories, or unredacted logs that might expose credentials. Share only the minimum sanitized instruction excerpts and failure example needed for the review; if those are insufficient, the scope may need to be narrowed or the review declined under the linked terms.
16
+
15
17
  ## Tools
16
18
 
17
19
  | Tool | Description |
@@ -23,6 +25,20 @@ To buy the review, use the [US$49 one-time GitHub Sponsors tier](https://github.
23
25
  | `get_anti_patterns` | `references/03-ANTI-PATTERNS.md` — red flags & recovery (~9KB) |
24
26
  | `classify_task` | Deterministically route a task to one of 9 GodPrompt task types, or `UNCLASSIFIED` when no reliable signal exists |
25
27
  | `get_version` | Version info and server metadata |
28
+ | `create_work_contract` | Create a portable, fingerprinted task contract with explicit scope, acceptance criteria and required verification commands |
29
+ | `review_work_evidence` | Fail-closed review of reported changed paths, verification receipts, acceptance results and forbidden actions |
30
+
31
+ > **Version 1.1.0:** `create_work_contract` and `review_work_evidence` expand the seven original MCP tools to nine. Older hosted or version-pinned installations may still expose only the original seven until separately updated. Both tools remain stateless and read-only, and neither independently authenticates caller-supplied evidence. See the [task-contract workflow and security limitations](docs/task-contracts.md).
32
+
33
+ ### Optional local proof bridge (from v1.1.0)
34
+
35
+ The new **godprompt-proof** CLI (Node 22+, **no additional dependencies**) can normalize pinned GitHub CI checks and exported Codexify command receipts into inputs for the existing GodPrompt evidence reviewer. It also supports an optional **single 256 KiB local JSONL feedback file** for project-scoped generic lessons, **on-demand read-only metrics**, and **versioned workflow previews** from that same file (no telemetry or automatic rule changes). No database server, GPU, background worker or global telemetry is involved.
36
+
37
+ GitHub can be read directly or from a **sanitized snapshot produced with an existing GitHub connector**, with no new token required for that offline path. Codexify is **client-orchestrated**: the authorized coding agent produces a receipt export, not a direct remote connection from the public Worker. The hosted MCP has **no access** to any user's local feedback file. No automatic uploads, training or rule promotion occur.
38
+
39
+ **The optional CLI ships with v1.1.0**, but it is not installed or enabled automatically on a user's computer. The hosted MCP cannot read local files. See [local proof bridge setup, limitations, and examples](docs/local-proof-bridge.md). The CLI is optional; the MCP server continues to work without it.
40
+
41
+ **ChatGPT publishing and storage:** The public hosted MCP remains **stateless** and does **not** create personal memory or store a JSONL file for ChatGPT users. Per-project learning is an **explicitly enabled local CLI**, not a hosted MCP feature. See [the hosting, privacy, local installation and release checklist](docs/chatgpt-local-first.md). Cloud sync is **not** included.
26
42
 
27
43
  ## Progressive Disclosure
28
44
 
@@ -50,7 +66,7 @@ Use the public Streamable HTTP endpoint directly in MCP clients that support rem
50
66
  https://god-prompt-mcp.tomi-seregi99.workers.dev/mcp
51
67
  ```
52
68
 
53
- The hosted endpoint exposes the same seven read-only GodPrompt tools as the local server and requires no API key or local Node.js runtime. It accepts both the deployed `initialize` flow and the current MCP 2026-07-28 `server/discover` flow so clients can connect while the ecosystem transitions between protocol eras. It is also published as a remote option in the Official MCP Registry alongside the installable stdio packages.
69
+ The hosted endpoint exposes the read-only GodPrompt tools included in its **currently deployed release** and requires no API key or local Node.js runtime. An unreleased source branch can have a different tool list; always inspect the live tool catalog after deployment. It accepts both the deployed `initialize` flow and the current MCP 2026-07-28 `server/discover` flow so clients can connect while the ecosystem transitions between protocol eras. It is also published as a remote option in the Official MCP Registry alongside the installable stdio packages.
54
70
 
55
71
  ### Agent Skills over MCP (SEP-2640)
56
72
 
@@ -69,7 +85,7 @@ On ChatGPT web, supported Business and Enterprise/Edu workspaces can connect God
69
85
  1. Open **Plugins**, select **+**, then **Add custom MCP server**. The current Plugins flow does **not** require Developer Mode.
70
86
  2. Enter a name and `https://god-prompt-mcp.tomi-seregi99.workers.dev/mcp` as the public HTTPS MCP endpoint. Choose **no authentication**; GodPrompt requires no API key.
71
87
  3. Review the risk warning and select **I understand and want to continue**, then **Create as a plugin**.
72
- 4. Review the discovered seven read-only GodPrompt tools and metadata, then install the plugin if your workspace permits it.
88
+ 4. Review the discovered read-only GodPrompt tools and metadata (the count depends on the deployed release), then install the plugin if your workspace permits it. Approved ChatGPT tool snapshots may require an admin refresh after a release.
73
89
  5. Start a new ChatGPT chat, type `@`, select the installed GodPrompt plugin, and try a read-only tool. Workspace approval may be required.
74
90
 
75
91
  **Legacy custom-app setup:** If your workspace still uses the older interface, open **Settings > Apps > Create** (or the workspace's app settings, if you are an admin/owner), use the same endpoint with no authentication, choose **Scan Tools**, then **Create**. This remains an alternative, not a prerequisite for the current Plugins flow.
@@ -97,16 +113,16 @@ This is a client-launcher workaround, not a GodPrompt MCP server change. Keep ex
97
113
 
98
114
  ### Docker / GHCR (local stdio; no host Node.js)
99
115
 
100
- For MCP clients that can launch a local process, the [public GHCR image](https://github.com/AKzar1el/god-prompt-mcp/pkgs/container/god-prompt-mcp) runs the same seven read-only tools without requiring Node.js on the host. Docker with Linux-container support is required; no API key is needed.
116
+ For MCP clients that can launch a local process, the [public GHCR image](https://github.com/AKzar1el/god-prompt-mcp/pkgs/container/god-prompt-mcp) runs the read-only tools of its pinned published version without requiring Node.js on the host. Docker with Linux-container support is required; no API key is needed.
101
117
 
102
118
  ```json
103
119
  {
104
120
  "command": "docker",
105
- "args": ["run", "--rm", "-i", "ghcr.io/akzar1el/god-prompt-mcp:1.0.44"]
121
+ "args": ["run", "--rm", "-i", "ghcr.io/akzar1el/god-prompt-mcp:1.1.0"]
106
122
  }
107
123
  ```
108
124
 
109
- Keep `-i` so the MCP client can exchange JSON-RPC over standard input/output; do not add `-t` (a TTY changes the stdio stream). The version tag selects the verified v1.0.44 image; update it deliberately for future releases rather than silently following the moving `latest` tag. The image is Linux/amd64 and runs as non-root user `10001:10001`. If Docker is unavailable, use the [hosted remote endpoint](#hosted-remote-no-nodejs-required) instead.
125
+ Keep `-i` so the MCP client can exchange JSON-RPC over standard input/output; do not add `-t` (a TTY changes the stdio stream). The version tag selects the verified v1.1.0 image; update it deliberately for future releases rather than silently following the moving `latest` tag. The image is Linux/amd64 and runs as non-root user `10001:10001`. If Docker is unavailable, use the [hosted remote endpoint](#hosted-remote-no-nodejs-required) instead.
110
126
 
111
127
  ### Glama
112
128
 
@@ -142,7 +158,7 @@ If you only want the Agent Skill, install it at user scope so VS Code discovers
142
158
  gh skill install AKzar1el/god-prompt-mcp skills/god-prompt --agent github-copilot --scope user
143
159
  ```
144
160
 
145
- If you only want the seven callable MCP tools, use the native MCP install button:
161
+ If you only want the callable MCP tools, use the native MCP install button:
146
162
 
147
163
  [![Install in VS Code](https://img.shields.io/badge/VS_Code-Install_GodPrompt_MCP-0098FF?style=flat-square&logo=visualstudiocode&logoColor=white)](https://vscode.dev/redirect?url=vscode:mcp/install?%7B%22name%22%3A%22god-prompt-mcp%22%2C%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22god-prompt-mcp%22%5D%7D)
148
164
 
@@ -260,7 +276,7 @@ Amp can load GodPrompt as an Agent Skill and expose the MCP tools only when that
260
276
  npx -y skills@latest add AKzar1el/god-prompt-mcp --skill god-prompt --agent amp --copy -y
261
277
  ```
262
278
 
263
- The skill includes Amp's sibling `mcp.json` configuration, pinned to the current GodPrompt MCP package. Amp keeps those seven MCP tool definitions hidden until the skill loads, avoiding a permanently expanded tool context while preserving the full progressive-disclosure surface. Node.js 22+ is required for the MCP server.
279
+ The skill includes Amp's sibling `mcp.json` configuration, pinned to the current GodPrompt MCP package. Amp keeps those MCP tool definitions hidden until the skill loads, avoiding a permanently expanded tool context while preserving the full progressive-disclosure surface. Node.js 22+ is required for the MCP server.
264
280
 
265
281
  ### Factory Droid
266
282
 
@@ -273,10 +289,10 @@ npx -y skills@latest add AKzar1el/god-prompt-mcp --skill god-prompt --agent droi
273
289
  Droid discovers compatible project skills under `.agents/skills/`. To add the callable GodPrompt tools as a local stdio MCP server, use Droid's native MCP command with the published version pinned:
274
290
 
275
291
  ```bash
276
- droid mcp add god-prompt "npx -y god-prompt-mcp@1.0.45"
292
+ droid mcp add god-prompt "npx -y god-prompt-mcp@1.1.0"
277
293
  ```
278
294
 
279
- Open `/mcp` in Droid to verify the server and available tools. The Agent Skill supplies the reusable workflow while MCP exposes GodPrompt's seven progressive-disclosure tools. Node.js 22+ is required for the MCP server.
295
+ Open `/mcp` in Droid to verify the server and available tools. The Agent Skill supplies the reusable workflow while MCP exposes GodPrompt's read-only task and protocol tools. Node.js 22+ is required for the MCP server.
280
296
 
281
297
  ### Warp
282
298
 
@@ -299,7 +315,7 @@ npx -y skills@latest add AKzar1el/god-prompt-mcp --skill god-prompt --agent goos
299
315
  Goose discovers the copied skill under `.goose/skills/god-prompt/`. To expose GodPrompt's callable tools for a session, start Goose with the published MCP package as an external stdio extension:
300
316
 
301
317
  ```bash
302
- goose session --with-extension "npx -y god-prompt-mcp@1.0.45"
318
+ goose session --with-extension "npx -y god-prompt-mcp@1.1.0"
303
319
  ```
304
320
 
305
321
  Goose currently treats Agent Skills and MCP extensions as separate native surfaces, so this path does not depend on Agent Plugins support. The skill supplies the reusable workflow while MCP exposes GodPrompt's seven progressive-disclosure tools. Node.js 22+ is required for the MCP server.
@@ -364,7 +380,7 @@ The Trae target installs the skill under `.trae/skills/god-prompt/`, where TraeC
364
380
  "mcpServers": {
365
381
  "god-prompt": {
366
382
  "command": "npx",
367
- "args": ["-y", "god-prompt-mcp@1.0.45"]
383
+ "args": ["-y", "god-prompt-mcp@1.1.0"]
368
384
  }
369
385
  }
370
386
  }
@@ -383,7 +399,7 @@ npx -y skills@latest add AKzar1el/god-prompt-mcp --skill god-prompt --agent open
383
399
  The copied skill lands under `.agents/skills/god-prompt/`, one of OpenClaw's documented project skill roots. To expose GodPrompt's callable tools to OpenClaw-managed agent runtimes as well, register the published stdio server:
384
400
 
385
401
  ```bash
386
- openclaw mcp add god-prompt --command npx --arg -y --arg god-prompt-mcp@1.0.45
402
+ openclaw mcp add god-prompt --command npx --arg -y --arg god-prompt-mcp@1.1.0
387
403
  openclaw mcp probe god-prompt
388
404
  ```
389
405
 
@@ -404,7 +420,7 @@ The Qoder target installs the skill under `.qoder/skills/god-prompt/`, where Qod
404
420
  "mcpServers": {
405
421
  "god-prompt": {
406
422
  "command": "npx",
407
- "args": ["-y", "god-prompt-mcp@1.0.45"]
423
+ "args": ["-y", "god-prompt-mcp@1.1.0"]
408
424
  }
409
425
  }
410
426
  }
@@ -444,7 +460,7 @@ Kimi Code CLI can install GodPrompt as one native custom plugin containing the e
444
460
  /reload
445
461
  ```
446
462
 
447
- The Kimi manifest points at `skills/`, so the `god-prompt` skill remains available through Kimi's normal relevance-based skill loading instead of being forced into every session. The same manifest exposes `god-prompt-mcp@1.0.45` as a local stdio MCP server, preserving the seven progressive-disclosure tools. The explicit `tree/main` URL matters because Kimi's bare GitHub-repository install form prefers the latest GitHub release; using `main` makes the current plugin manifest available without forcing a documentation-only npm/MCP Registry release. Node.js 22+ is required for the MCP server.
463
+ The Kimi manifest points at `skills/`, so the `god-prompt` skill remains available through Kimi's normal relevance-based skill loading instead of being forced into every session. The same manifest exposes `god-prompt-mcp@1.1.0` as a local stdio MCP server, including the nine tools available in v1.1.0. The explicit `tree/main` URL matters because Kimi's bare GitHub-repository install form prefers the latest GitHub release; using `main` makes the current plugin manifest available without forcing a documentation-only npm/MCP Registry release. Node.js 22+ is required for the MCP server.
448
464
 
449
465
  ### JetBrains AI Assistant
450
466
 
@@ -0,0 +1,633 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Optional, local-only GodPrompt evidence bridge. Node 22+, zero dependencies.
4
+ * The public Cloudflare MCP never imports or executes this file.
5
+ */
6
+ import { createHash } from "node:crypto";
7
+ import { constants } from "node:fs";
8
+ import { mkdir, open, readFile, lstat } from "node:fs/promises";
9
+ import { homedir } from "node:os";
10
+ import { dirname, isAbsolute, join, resolve } from "node:path";
11
+ import { fileURLToPath } from "node:url";
12
+
13
+ export const BUNDLE_SCHEMA = "godprompt.evidence_bundle.v1";
14
+ const MAX_JSON_BYTES = 256 * 1024;
15
+ const MAX_FEEDBACK_BYTES = 256 * 1024;
16
+ const MAX_PAGES = 3;
17
+
18
+ function sha256(text) {
19
+ return createHash("sha256").update(text).digest("hex");
20
+ }
21
+ function fail(message) {
22
+ throw new Error(message);
23
+ }
24
+ function checkContract(contract) {
25
+ if (!contract || contract.schema !== "godprompt.work_contract.v1" ||
26
+ !/^sha256:[a-f0-9]{64}$/.test(contract.contract_id || "") ||
27
+ !Array.isArray(contract.verification_commands) ||
28
+ !Array.isArray(contract.allowed_paths) ||
29
+ !Array.isArray(contract.success_criteria)) fail("Expected a complete v1 GodPrompt contract");
30
+ return contract;
31
+ }
32
+ export async function readSmallJson(filename) {
33
+ const bytes = await readFile(filename);
34
+ if (bytes.length > MAX_JSON_BYTES) fail("Input JSON exceeds the 256 KiB limit");
35
+ return JSON.parse(bytes.toString("utf8"));
36
+ }
37
+ function makeBundle(adapter, contract, changedFiles, checks, gaps, provenance) {
38
+ return {
39
+ schema: BUNDLE_SCHEMA,
40
+ adapter,
41
+ provenance,
42
+ review_input: {
43
+ contract,
44
+ changed_files: changedFiles,
45
+ operations_performed: [],
46
+ checks,
47
+ acceptance: [],
48
+ observations: [],
49
+ human_review_reported: false,
50
+ },
51
+ gaps: [...new Set(gaps)],
52
+ independently_verified: false,
53
+ completion_authorized: false,
54
+ warning: "Caller-supplied exports and GitHub check names are not proof that contracted commands ran. Acceptance, complete diff, approvals and original outputs require independent review. Never send private evidence to the public MCP.",
55
+ };
56
+ }
57
+ function validateRepo(repo, sha) {
58
+ const segments = typeof repo === "string" ? repo.split("/") : [];
59
+ if (segments.length !== 2 || segments.some((s) => !/^[A-Za-z0-9_.-]{1,100}$/.test(s) || s === "." || s === "..")) {
60
+ fail("Repository must be owner/name");
61
+ }
62
+ if (typeof sha !== "string" || !/^[a-f0-9]{40}$/.test(sha)) fail("Use an exact 40-character lowercase commit SHA");
63
+ }
64
+ async function githubJson(url, fetchImpl) {
65
+ if (new URL(url).origin !== "https://api.github.com") fail("GitHub API origin mismatch");
66
+ // Only the actual network adapter needs credentials. Never pass a token to
67
+ // caller-injected fetch handlers (including the offline connector snapshot).
68
+ const token = fetchImpl === fetch ? process.env.GITHUB_TOKEN : null;
69
+ const response = await fetchImpl(url, {
70
+ headers: {
71
+ "Accept": "application/vnd.github+json",
72
+ "User-Agent": "godprompt-proof-bridge",
73
+ "X-GitHub-Api-Version": "2022-11-28",
74
+ ...(token ? { Authorization: "Bearer " + token } : {}),
75
+ },
76
+ signal: AbortSignal.timeout(15000),
77
+ });
78
+ if (!response.ok) fail("GitHub API HTTP " + response.status + " (credentials and response body withheld)");
79
+ const body = await response.text();
80
+ if (Buffer.byteLength(body) > 8 * 1024 * 1024) fail("GitHub response exceeds the safety limit");
81
+ return {
82
+ data: JSON.parse(body),
83
+ hasNext: /rel="next"/.test(response.headers.get("link") || ""),
84
+ };
85
+ }
86
+ export async function githubEvidence({ repo, sha, contract, mapping = {}, pr = null, fetchImpl = fetch }) {
87
+ validateRepo(repo, sha);
88
+ checkContract(contract);
89
+ if (!mapping || typeof mapping !== "object" || Array.isArray(mapping)) fail("Expected a VC-ID-to-check-name JSON map");
90
+ const base = "https://api.github.com/repos/" + repo;
91
+ const gaps = [];
92
+ if (pr !== null && (!Number.isInteger(pr) || pr < 1 || pr > 1000000)) fail("PR must be a positive integer");
93
+ const files = [];
94
+ let completeFiles = true;
95
+ const recordFile = (entry) => {
96
+ if (!entry || typeof entry.filename !== "string") fail("GitHub file list contains an invalid path");
97
+ files.push(entry.filename);
98
+ if (entry.status === "renamed" && typeof entry.previous_filename === "string") files.push(entry.previous_filename);
99
+ };
100
+ if (pr === null) {
101
+ gaps.push("SINGLE_COMMIT_DIFF_ONLY_NOT_FULL_PR");
102
+ for (let page = 1; page <= MAX_PAGES; page++) {
103
+ const item = await githubJson(base + "/commits/" + sha + "?per_page=100&page=" + page, fetchImpl);
104
+ if (item.data.sha !== sha || !Array.isArray(item.data.files)) fail("GitHub commit SHA or file list mismatch");
105
+ for (const entry of item.data.files) recordFile(entry);
106
+ if (!item.hasNext) break;
107
+ if (page === MAX_PAGES) {
108
+ completeFiles = false;
109
+ gaps.push("COMMIT_FILE_LIST_TRUNCATED");
110
+ }
111
+ }
112
+ } else {
113
+ const pullUrl = base + "/pulls/" + pr;
114
+ const before = await githubJson(pullUrl, fetchImpl);
115
+ if (before.data.number !== pr || before.data.head?.sha !== sha) fail("GitHub PR head SHA mismatch");
116
+ for (let page = 1; page <= MAX_PAGES; page++) {
117
+ const item = await githubJson(pullUrl + "/files?per_page=100&page=" + page, fetchImpl);
118
+ if (!Array.isArray(item.data)) fail("GitHub PR files response malformed");
119
+ for (const entry of item.data) recordFile(entry);
120
+ if (!item.hasNext) break;
121
+ if (page === MAX_PAGES) {
122
+ completeFiles = false;
123
+ gaps.push("PR_FILE_LIST_TRUNCATED");
124
+ }
125
+ }
126
+ const after = await githubJson(pullUrl, fetchImpl);
127
+ if (after.data.number !== pr || after.data.head?.sha !== sha) fail("GitHub PR head moved while collecting evidence");
128
+ }
129
+ const runs = [];
130
+ let completeRuns = true;
131
+ for (let page = 1; page <= MAX_PAGES; page++) {
132
+ const item = await githubJson(base + "/commits/" + sha + "/check-runs?per_page=100&page=" + page, fetchImpl);
133
+ if (!Array.isArray(item.data.check_runs)) fail("GitHub check-runs response malformed");
134
+ for (const run of item.data.check_runs) {
135
+ if (run.head_sha !== sha) fail("GitHub check-run head SHA mismatch");
136
+ runs.push(run);
137
+ }
138
+ if (!item.hasNext) {
139
+ if (Number.isInteger(item.data.total_count) && item.data.total_count > runs.length) {
140
+ completeRuns = false;
141
+ gaps.push("CHECK_RUNS_INCOMPLETE");
142
+ }
143
+ break;
144
+ }
145
+ if (page === MAX_PAGES) {
146
+ completeRuns = false;
147
+ gaps.push("CHECK_RUNS_TRUNCATED");
148
+ }
149
+ }
150
+ const checks = [];
151
+ const ids = {};
152
+ for (const expected of contract.verification_commands) {
153
+ const name = mapping[expected.id];
154
+ if (typeof name !== "string" || !name.trim()) {
155
+ gaps.push("CHECK_NOT_MAPPED:" + expected.id);
156
+ continue;
157
+ }
158
+ const matches = runs.filter((run) => run.name === name);
159
+ if (matches.length !== 1) {
160
+ gaps.push((matches.length ? "AMBIGUOUS_CHECK:" : "CHECK_NOT_FOUND:") + expected.id);
161
+ continue;
162
+ }
163
+ const run = matches[0];
164
+ const passed = completeFiles && completeRuns && run.status === "completed" && run.conclusion === "success";
165
+ const receipt = {
166
+ id: expected.id,
167
+ command: expected.command,
168
+ exit_code: passed ? 0 : (!completeFiles || !completeRuns || run.status !== "completed" ? null : 1),
169
+ source: "tool_output",
170
+ evidence_excerpt: "GitHub check '" + name.slice(0, 100) + "' status=" + run.status + ", conclusion=" + run.conclusion + ", commit=" + sha.slice(0, 12) + ". Exact command execution NOT established.",
171
+ };
172
+ if (!passed) gaps.push("CHECK_NOT_SUCCESSFUL:" + expected.id);
173
+ checks.push(receipt);
174
+ ids[expected.id] = Number.isInteger(run.id) ? run.id : null;
175
+ }
176
+ gaps.push("ACCEPTANCE_REQUIRES_INDEPENDENT_EVIDENCE");
177
+ if (!completeFiles) files.length = 0;
178
+ return makeBundle("github_checks", contract, [...new Set(files)], checks, gaps, {
179
+ provider: "github_rest_readonly",
180
+ commit_sha: sha,
181
+ diff_scope: pr === null ? "single_commit" : "pull_request",
182
+ pull_request_number: pr,
183
+ check_run_ids: ids,
184
+ file_list_complete: completeFiles,
185
+ check_run_list_complete: completeRuns,
186
+ });
187
+ }
188
+ /**
189
+ * Use a previously authorized GitHub connector export when no local GitHub
190
+ * credential is available. Entirely offline; never claims authenticated proof.
191
+ */
192
+ export async function githubSnapshotEvidence({ repo, sha, contract, mapping = {}, pr = null, snapshot }) {
193
+ const sourceFiles = pr === null ? snapshot?.commit?.files : snapshot?.pr_files;
194
+ if (!snapshot || typeof snapshot !== "object" || snapshot.complete !== true ||
195
+ !snapshot.check_runs || !Array.isArray(snapshot.check_runs.check_runs) ||
196
+ !Array.isArray(sourceFiles) ||
197
+ (pr === null && !snapshot.commit) ||
198
+ (pr !== null && (!snapshot.pull_request || snapshot.pull_request.number !== pr ||
199
+ snapshot.pull_request.head?.sha !== sha))) {
200
+ fail("Snapshot must contain complete:true, matching commit or pull_request, files and check_runs");
201
+ }
202
+ if (sourceFiles.length > 100 ||
203
+ (Number.isInteger(snapshot.check_runs.total_count) &&
204
+ snapshot.check_runs.total_count !== snapshot.check_runs.check_runs.length) ||
205
+ snapshot.check_runs.check_runs.length > 100) {
206
+ fail("Snapshot might be paginated; collect complete results or use direct GitHub reads");
207
+ }
208
+ const fetchImpl = async (url) => {
209
+ const data = url.includes("/check-runs?") ? snapshot.check_runs :
210
+ pr !== null && url.includes("/pulls/" + pr + "/files?") ? snapshot.pr_files :
211
+ pr !== null && url.endsWith("/pulls/" + pr) ? snapshot.pull_request :
212
+ snapshot.commit;
213
+ return new Response(JSON.stringify(data), { status: 200 });
214
+ };
215
+ const bundle = await githubEvidence({ repo, sha, contract, mapping, pr, fetchImpl });
216
+ bundle.adapter = "github_connector_snapshot";
217
+ bundle.provenance.provider = "caller_supplied_github_connector_snapshot";
218
+ bundle.gaps.push("CONNECTOR_SNAPSHOT_PROVENANCE_NOT_AUTHENTICATED");
219
+ return bundle;
220
+ }
221
+ export function codexifyEvidence({ contract, exportData }) {
222
+ checkContract(contract);
223
+ if (!exportData || typeof exportData !== "object" || Array.isArray(exportData)) fail("Codexify export must be an object");
224
+ const rawFiles = exportData.changed_files;
225
+ if (!Array.isArray(rawFiles) || rawFiles.length > 150 || rawFiles.some((v) => typeof v !== "string")) {
226
+ fail("Codexify export needs a bounded changed_files array");
227
+ }
228
+ const rawChecks = exportData.checks;
229
+ if (!Array.isArray(rawChecks) || rawChecks.length > 100) fail("Codexify export needs a bounded checks array");
230
+ const gaps = [];
231
+ const checks = rawChecks.map((receipt) => {
232
+ if (!receipt || typeof receipt !== "object" || typeof receipt.id !== "string" || typeof receipt.command !== "string") {
233
+ fail("Malformed Codexify receipt");
234
+ }
235
+ // Only a pasted structured exec_command envelope is attributed to tool output.
236
+ // An ordinary claimed numeric exit_code is never promoted to tool provenance.
237
+ const result = receipt.tool === "mcp__God_v5__exec_command" &&
238
+ receipt.response && typeof receipt.response === "object" ? receipt.response.upstream_result : null;
239
+ const code = Number.isInteger(result?.exit_code) && result.exit_code >= 0 ? result.exit_code : null;
240
+ const attributed = code !== null;
241
+ if (!attributed) gaps.push("NO_STRUCTURED_CODEXIFY_RECEIPT:" + receipt.id);
242
+ return {
243
+ id: receipt.id,
244
+ command: receipt.command,
245
+ exit_code: code,
246
+ source: attributed ? "tool_output" : "self_report",
247
+ evidence_excerpt: attributed
248
+ ? "Codexify exec_command exported envelope: exit_code=" + code + "; result_sha256=" + sha256(JSON.stringify(result)).slice(0, 16) + "; raw output withheld."
249
+ : "No structured Codexify exec_command tool result; self-report only.",
250
+ };
251
+ });
252
+ for (const required of contract.verification_commands) {
253
+ if (!checks.some((c) => c.id === required.id)) gaps.push("VERIFICATION_MISSING:" + required.id);
254
+ }
255
+ gaps.push("CHANGED_FILE_LIST_IS_CALLER_SUPPLIED");
256
+ gaps.push("ACCEPTANCE_REQUIRES_INDEPENDENT_EVIDENCE");
257
+ const bundle = makeBundle("codexify_receipts", contract, rawFiles, checks, gaps, {
258
+ provider: "codexify_export",
259
+ claimed_receipts: checks.length,
260
+ });
261
+ if (Array.isArray(exportData.operations_performed) &&
262
+ exportData.operations_performed.length <= 100 &&
263
+ exportData.operations_performed.every((v) => typeof v === "string" && v.length <= 500)) {
264
+ bundle.review_input.operations_performed = exportData.operations_performed;
265
+ }
266
+ return bundle;
267
+ }
268
+ function filePath(env = process.env) {
269
+ if (env.GODPROMPT_FEEDBACK_FILE) {
270
+ if (!isAbsolute(env.GODPROMPT_FEEDBACK_FILE)) fail("GODPROMPT_FEEDBACK_FILE must be an absolute path");
271
+ return env.GODPROMPT_FEEDBACK_FILE;
272
+ }
273
+ const base = env.LOCALAPPDATA || env.XDG_STATE_HOME || join(homedir(), ".local", "state");
274
+ return join(base, "godprompt", "feedback.jsonl");
275
+ }
276
+ function projectDigest(project) {
277
+ if (typeof project !== "string" || project.trim().length < 2 || project.length > 160) fail("Project identifier must be 2-160 characters");
278
+ return "sha256:" + sha256(project.trim());
279
+ }
280
+ async function readEvents(filename) {
281
+ let info;
282
+ try { info = await lstat(filename); }
283
+ catch (error) {
284
+ if (error.code === "ENOENT") return [];
285
+ throw error;
286
+ }
287
+ if (!info.isFile() || info.isSymbolicLink()) fail("Feedback path must be a regular file, not a symlink");
288
+ if (info.size > MAX_FEEDBACK_BYTES) fail("Local feedback file exceeds 256 KiB; archive it before adding more");
289
+ const text = await readFile(filename, "utf8");
290
+ const lines = text.split("\n").filter(Boolean);
291
+ return lines.map((line) => {
292
+ const event = JSON.parse(line);
293
+ if (!event || event.v !== 1 ||
294
+ typeof event.project !== "string" || !/^sha256:[a-f0-9]{64}$/.test(event.project) ||
295
+ typeof event.pattern !== "string" || typeof event.lesson !== "string" ||
296
+ (event.review_ref !== undefined && !/^[a-f0-9]{24}$/.test(event.review_ref))) {
297
+ fail("Malformed feedback file; no automatic repair or overwrite");
298
+ }
299
+ return event;
300
+ });
301
+ }
302
+ export async function saveFeedback({ project, outcome, pattern, lesson, verified = false, reviewRef = null }, env = process.env) {
303
+ const hash = projectDigest(project);
304
+ if (!["success", "failure", "blocked"].includes(outcome)) fail("Outcome must be success, failure or blocked");
305
+ if (typeof pattern !== "string" || !/^[a-z][a-z0-9_-]{2,47}$/.test(pattern)) {
306
+ fail("Pattern must be a 3-48 character lowercase issue code");
307
+ }
308
+ if (typeof lesson !== "string" || lesson.length < 5 || lesson.length > 160 ||
309
+ /[\r\n\t<>@]/.test(lesson) || /(?:https?:\/\/|[a-z]:\\|\/users\/|\/home\/|bearer |password|secret|api[_ -]?key|ghp_|github_pat_|sk-)/i.test(lesson)) {
310
+ fail("Lesson must be a short generic correction with no URLs, paths, credentials, or personal data");
311
+ }
312
+ if (typeof verified !== "boolean") fail("verified must be a boolean");
313
+ if (reviewRef !== null && (typeof reviewRef !== "string" || !/^[a-f0-9]{24}$/.test(reviewRef))) {
314
+ fail("Invalid bounded review fingerprint");
315
+ }
316
+ const filename = filePath(env);
317
+ const current = await readEvents(filename);
318
+ if (reviewRef && current.some((event) => event.project === hash && event.review_ref === reviewRef)) {
319
+ return { stored: false, reason: "duplicate_review_issue", scope: "local_only", project_hash: hash };
320
+ }
321
+ const event = {
322
+ v: 1, project: hash, at: new Date().toISOString(),
323
+ outcome, pattern, lesson: lesson.trim(), verified_reported: verified,
324
+ ...(reviewRef ? { review_ref: reviewRef } : {}),
325
+ };
326
+ const row = JSON.stringify(event) + "\n";
327
+ let used = 0;
328
+ try { used = (await lstat(filename)).size; }
329
+ catch (error) { if (error.code !== "ENOENT") throw error; }
330
+ if (used + Buffer.byteLength(row) > MAX_FEEDBACK_BYTES) fail("Feedback file is full (256 KiB); archive or rotate it manually");
331
+ await mkdir(dirname(filename), { recursive: true, mode: 0o700 });
332
+ const fd = await open(filename, constants.O_CREAT | constants.O_APPEND | constants.O_WRONLY | (constants.O_NOFOLLOW || 0), 0o600);
333
+ try { await fd.writeFile(row, "utf8"); }
334
+ finally { await fd.close(); }
335
+ return { stored: true, scope: "local_only", project_hash: hash, records_for_project: current.filter((e) => e.project === hash).length + 1, verified_reported: verified };
336
+ }
337
+ export async function localLessons(project, env = process.env) {
338
+ const hash = projectDigest(project);
339
+ const records = (await readEvents(filePath(env))).filter((e) => e.project === hash);
340
+ const byPattern = new Map();
341
+ for (const item of records) {
342
+ const value = byPattern.get(item.pattern) || { pattern: item.pattern, total: 0, failures: 0, verified_reports: 0 };
343
+ value.total++;
344
+ if (item.outcome !== "success") value.failures++;
345
+ if (item.verified_reported) value.verified_reports++;
346
+ byPattern.set(item.pattern, value);
347
+ }
348
+ return {
349
+ scope: "local_only",
350
+ project_hash: hash,
351
+ records: records.length,
352
+ recurring_patterns: [...byPattern.values()].sort((a, b) => b.failures - a.failures || b.total - a.total).slice(0, 10),
353
+ recent_lessons: records.slice(-5).reverse().map((x) => ({
354
+ pattern: x.pattern, outcome: x.outcome, lesson: x.lesson, verified_reported: x.verified_reported,
355
+ })),
356
+ warning: "These are local user-reported observations, not trained weights, global rules or independently verified facts.",
357
+ };
358
+ }
359
+ /**
360
+ * On-demand, read-only local observability. No telemetry or additional files.
361
+ * Outcomes are reported observations, never a measured agent success rate.
362
+ */
363
+ export async function localMetrics(project, { days = 30, now = Date.now() } = {}, env = process.env) {
364
+ const hash = projectDigest(project);
365
+ if (!Number.isInteger(days) || days < 1 || days > 365) fail("Metric window must be 1-365 days");
366
+ const timestamp = typeof now === "number" ? now : Date.parse(now);
367
+ if (!Number.isFinite(timestamp)) fail("Invalid metrics reference time");
368
+ const filename = filePath(env);
369
+ const records = (await readEvents(filename)).filter((row) => row.project === hash);
370
+ const cutoff = timestamp - days * 86400000;
371
+ const inWindow = records.filter((row) => {
372
+ const time = Date.parse(row.at);
373
+ return Number.isFinite(time) && time <= timestamp && time >= cutoff;
374
+ });
375
+ const counts = (items) => {
376
+ const result = { success: 0, failure: 0, blocked: 0 };
377
+ for (const item of items) if (Object.hasOwn(result, item.outcome)) result[item.outcome]++;
378
+ return result;
379
+ };
380
+ const patterns = new Map();
381
+ for (const item of inWindow) {
382
+ if (item.outcome === "success") continue;
383
+ const count = patterns.get(item.pattern) || 0;
384
+ patterns.set(item.pattern, count + 1);
385
+ }
386
+ const topHolds = [...patterns].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
387
+ .slice(0, 10).map(([pattern, reported_count]) => ({ pattern, reported_count }));
388
+ let fileBytes = 0;
389
+ try { fileBytes = (await lstat(filename)).size; }
390
+ catch (error) { if (error.code !== "ENOENT") throw error; }
391
+ return {
392
+ scope: "local_only",
393
+ project_hash: hash,
394
+ file_bytes: fileBytes,
395
+ file_cap_bytes: MAX_FEEDBACK_BYTES,
396
+ window_days: days,
397
+ reported_events_all_time: records.length,
398
+ reported_events_window: inWindow.length,
399
+ reported_outcomes_all_time: counts(records),
400
+ reported_outcomes_window: counts(inWindow),
401
+ reported_verifications_window: inWindow.filter((row) => row.verified_reported === true).length,
402
+ recurring_hold_patterns_window: topHolds,
403
+ latest_event_at: records.length ? records[records.length - 1].at : null,
404
+ warning: "Only user-reported events are counted. Sampling is incomplete and biased; do not interpret these counts as task success rates, measured quality uplift or independently verified telemetry.",
405
+ };
406
+ }
407
+ // Only fixed, public generic corrections are stored from a review. The
408
+ // submitted task, issue details, command output and paths are never persisted.
409
+ const REVIEW_LESSONS = Object.freeze({
410
+ MISSING_VERIFICATION: "Run each required verification command before completion",
411
+ VERIFICATION_FAILED: "Fix failed checks and rerun them before completion",
412
+ COMMAND_MISMATCH: "Preserve exact contracted commands in verification receipts",
413
+ SELF_REPORTED_CHECK: "Use real structured tool receipts rather than claimed success",
414
+ OUT_OF_SCOPE_CHANGE: "Review and revert changes outside the approved paths",
415
+ INVALID_CHANGED_PATH: "Use safe repository relative paths for changed files",
416
+ PROHIBITED_ACTION_REPORTED: "Stop prohibited actions and request explicit authorization",
417
+ ACCEPTANCE_NOT_MET: "Validate each acceptance criterion with observable evidence",
418
+ ACCEPTANCE_EVIDENCE_MISSING: "Reference successful checks or observations for acceptance",
419
+ CONTRACT_DRIFT: "Recreate the contract after any approved scope change",
420
+ REVIEW_REQUIRED: "Obtain separately authorized human review for high risk",
421
+ DUPLICATE_CHECK_RECEIPT: "Deduplicate verification receipt identifiers before review",
422
+ });
423
+ export async function learnFromReview({ project, review }, env = process.env) {
424
+ if (!review || typeof review !== "object" ||
425
+ review.status !== "HOLD" || !Array.isArray(review.issues)) {
426
+ return { stored: 0, reason: "Only HOLD issue codes are stored; a ready report is not verified success" };
427
+ }
428
+ if (typeof review.contract_id !== "string" || !/^sha256:[a-f0-9]{64}$/.test(review.contract_id)) {
429
+ fail("A HOLD review must contain its original v1 contract_id to avoid double-counting");
430
+ }
431
+ const codes = [...new Set(review.issues.map((item) => item?.code))].filter(
432
+ (code) => typeof code === "string" && Object.hasOwn(REVIEW_LESSONS, code)
433
+ ).slice(0, 8);
434
+ const storedCodes = [];
435
+ for (const code of codes) {
436
+ const result = await saveFeedback({
437
+ project,
438
+ outcome: "blocked",
439
+ pattern: "review_" + code.toLowerCase(),
440
+ lesson: REVIEW_LESSONS[code],
441
+ verified: false,
442
+ reviewRef: sha256(review.contract_id + ":" + code).slice(0, 24),
443
+ }, env);
444
+ if (result.stored) storedCodes.push(code);
445
+ }
446
+ return {
447
+ stored: storedCodes.length,
448
+ skipped_duplicate_issues: codes.length - storedCodes.length,
449
+ patterns: storedCodes,
450
+ source_is_caller_supplied: true,
451
+ note: "Stored only previously unseen contract-and-HOLD-code pairs as generic local lessons; no raw details or global policy changes.",
452
+ };
453
+ }
454
+ // Versioned, bounded workflow previews. This stays entirely local and is
455
+ // read-only. Repeated HOLDs suggest human-reviewed changes, never trust grants.
456
+ export const WORKFLOW_SCHEMA = "godprompt.local_workflow.v1";
457
+ const WORKFLOW_FOCUS = Object.freeze({
458
+ BUILD: "Define observable acceptance; add focused regression tests before implementation.",
459
+ DEBUG: "Reproduce the failure; isolate its root cause; test the fix and neighboring paths.",
460
+ REFACTOR: "Characterize existing behavior; change structure; verify behavior preservation.",
461
+ CONTENT: "Verify sources and factual claims; make focused edits; review accuracy and clarity.",
462
+ DESIGN: "Define design constraints; inspect responsive and accessible states; verify screenshots.",
463
+ SHIP: "Inspect release impact and rollback path; require explicit publish or deployment approval.",
464
+ ANALYZE: "Inspect authoritative evidence; separate observations from interpretation and unknowns.",
465
+ AUTOMATE: "Test idempotence, retries, failure handling and dry-run behavior before activation.",
466
+ PLAN: "Record constraints, assumptions, alternatives, uncertainties and explicit next actions.",
467
+ });
468
+ const BASE_WORKFLOW_GATES = Object.freeze([
469
+ "Use only paths and actions that the user and host authorize.",
470
+ "Create or review a task contract with explicit success criteria and verification commands.",
471
+ "Run checks in the actual environment and retain redacted tool or CI receipts.",
472
+ "Treat reported-ready evidence as unverified until independent source review.",
473
+ "Do not merge, publish, deploy, spend or widen risk limits without separate authorization.",
474
+ ]);
475
+ const REVIEW_PATTERN_PREFIX = "review_";
476
+ export async function localWorkflow(project, {
477
+ taskType = "BUILD", riskLevel = "medium", minReports = 3,
478
+ } = {}, env = process.env) {
479
+ const hash = projectDigest(project);
480
+ if (!Object.hasOwn(WORKFLOW_FOCUS, taskType)) fail("Workflow task type must be a classified GodPrompt task type");
481
+ if (!["low", "medium", "high", "critical"].includes(riskLevel)) fail("Invalid workflow risk level");
482
+ if (!Number.isInteger(minReports) || minReports < 2 || minReports > 20) fail("minReports must be an integer from 2 through 20");
483
+ const events = (await readEvents(filePath(env))).filter((row) => row.project === hash);
484
+ const issueCodes = new Map();
485
+ for (const row of events) {
486
+ if (row.outcome !== "blocked" || typeof row.pattern !== "string" ||
487
+ typeof row.review_ref !== "string" ||
488
+ !row.pattern.startsWith(REVIEW_PATTERN_PREFIX)) continue;
489
+ const issue = row.pattern.slice(REVIEW_PATTERN_PREFIX.length).toUpperCase();
490
+ if (!Object.hasOwn(REVIEW_LESSONS, issue)) continue;
491
+ issueCodes.set(issue, (issueCodes.get(issue) || 0) + 1);
492
+ }
493
+ const candidates = [...issueCodes].filter(([, count]) => count >= minReports)
494
+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
495
+ .slice(0, 8).map(([code, count]) => ({
496
+ issue_code: code,
497
+ reported_holds: count,
498
+ proposed_safeguard: REVIEW_LESSONS[code],
499
+ status: "NEEDS_HUMAN_REVIEW",
500
+ }));
501
+ const payload = {
502
+ schema: WORKFLOW_SCHEMA,
503
+ project_hash: hash,
504
+ task_type: taskType,
505
+ risk_level: riskLevel,
506
+ focus: WORKFLOW_FOCUS[taskType],
507
+ standard_gates: [...BASE_WORKFLOW_GATES],
508
+ human_review_required: riskLevel === "high" || riskLevel === "critical",
509
+ suggestion_threshold: minReports,
510
+ review_candidates: candidates,
511
+ auto_promoted: false,
512
+ independently_verified: false,
513
+ };
514
+ const version = "sha256:" + sha256(JSON.stringify(payload));
515
+ const markdown = [
516
+ "# GodPrompt local workflow — " + taskType,
517
+ "",
518
+ "Version: " + version,
519
+ "Scope: per-project local preview; no policy changes applied",
520
+ "",
521
+ "## Task focus",
522
+ payload.focus,
523
+ "",
524
+ "## Standard verification gates",
525
+ ...payload.standard_gates.map((gate) => "- " + gate),
526
+ ...(payload.human_review_required
527
+ ? ["", "## High-risk requirement", "- Obtain separately authorized human review before completion."] : []),
528
+ "",
529
+ "## Repeated local HOLD patterns — review candidates, NOT trusted rules",
530
+ ...(candidates.length ? candidates.map((entry) =>
531
+ "- " + entry.issue_code + " (" + entry.reported_holds + " reported HOLDs): " + entry.proposed_safeguard
532
+ ) : ["- None met the review threshold."]),
533
+ "",
534
+ "These are caller-supplied observations, not authenticated results. Do not copy candidates into project policy or global GodPrompt rules without an authorized human review and independent evidence.",
535
+ "The CLI never edits AGENTS.md, source files, the public MCP or local feedback during preview.",
536
+ ].join("\n");
537
+ return {
538
+ ...payload,
539
+ version,
540
+ markdown,
541
+ read_only: true,
542
+ source_reports_examined: events.length,
543
+ warning: "Version tracks a deterministic preview, not an approved rule set. Repeated self-reports are not independent evidence, and no policy is automatically applied.",
544
+ };
545
+ }
546
+ function parseOptions(argv) {
547
+ const command = argv[0];
548
+ const opts = {};
549
+ for (let i = 1; i < argv.length; i += 2) {
550
+ if (!argv[i]?.startsWith("--") || i + 1 >= argv.length) fail("Expected --name value option pairs");
551
+ const key = argv[i].slice(2);
552
+ if (!/^[a-z-]+$/.test(key) || Object.hasOwn(opts, key)) fail("Invalid or duplicate flag");
553
+ opts[key] = argv[i + 1];
554
+ }
555
+ const allowed = {
556
+ github: ["repo", "sha", "contract", "map", "pr"],
557
+ "github-snapshot": ["repo", "sha", "contract", "map", "snapshot", "pr"],
558
+ codexify: ["contract", "export"],
559
+ learn: ["project", "outcome", "pattern", "lesson", "verified"],
560
+ lessons: ["project"],
561
+ "learn-review": ["project", "review"],
562
+ metrics: ["project", "days"],
563
+ workflow: ["project", "type", "risk", "min-reports", "format"],
564
+ };
565
+ if (!allowed[command]) fail("Usage: godprompt-proof github|github-snapshot|codexify|learn|learn-review|lessons|metrics|workflow [--name value ...]");
566
+ for (const key of Object.keys(opts)) if (!allowed[command].includes(key)) fail("Unknown option --" + key);
567
+ return { command, opts };
568
+ }
569
+ export async function cli(argv = process.argv.slice(2)) {
570
+ const { command, opts } = parseOptions(argv);
571
+ if (command === "github") {
572
+ if (!opts.repo || !opts.sha || !opts.contract) fail("github requires --repo --sha --contract");
573
+ return githubEvidence({
574
+ repo: opts.repo,
575
+ sha: opts.sha,
576
+ contract: checkContract(await readSmallJson(opts.contract)),
577
+ mapping: opts.map ? await readSmallJson(opts.map) : {},
578
+ pr: opts.pr ? Number(opts.pr) : null,
579
+ });
580
+ }
581
+ if (command === "github-snapshot") {
582
+ if (!opts.repo || !opts.sha || !opts.contract || !opts.snapshot) fail("github-snapshot requires --repo --sha --contract --snapshot");
583
+ return githubSnapshotEvidence({
584
+ repo: opts.repo,
585
+ sha: opts.sha,
586
+ contract: checkContract(await readSmallJson(opts.contract)),
587
+ mapping: opts.map ? await readSmallJson(opts.map) : {},
588
+ pr: opts.pr ? Number(opts.pr) : null,
589
+ snapshot: await readSmallJson(opts.snapshot),
590
+ });
591
+ }
592
+ if (command === "codexify") {
593
+ if (!opts.contract || !opts.export) fail("codexify requires --contract --export");
594
+ return codexifyEvidence({
595
+ contract: checkContract(await readSmallJson(opts.contract)),
596
+ exportData: await readSmallJson(opts.export),
597
+ });
598
+ }
599
+ if (command === "learn-review") {
600
+ if (!opts.project || !opts.review) fail("learn-review requires --project --review");
601
+ return learnFromReview({ project: opts.project, review: await readSmallJson(opts.review) });
602
+ }
603
+ if (command === "learn") {
604
+ for (const key of ["project", "outcome", "pattern", "lesson"]) if (!opts[key]) fail("learn requires --" + key);
605
+ if (opts.verified && !["true", "false"].includes(opts.verified)) fail("--verified accepts true or false");
606
+ return saveFeedback({ ...opts, verified: opts.verified === "true" });
607
+ }
608
+ if (command === "metrics") {
609
+ if (!opts.project) fail("metrics requires --project");
610
+ return localMetrics(opts.project, { days: opts.days ? Number(opts.days) : 30 });
611
+ }
612
+ if (command === "workflow") {
613
+ if (!opts.project || !opts.type) fail("workflow requires --project and --type");
614
+ if (opts.format && !["json", "markdown"].includes(opts.format)) fail("workflow --format must be json or markdown");
615
+ const result = await localWorkflow(opts.project, {
616
+ taskType: opts.type,
617
+ riskLevel: opts.risk || "medium",
618
+ minReports: opts["min-reports"] ? Number(opts["min-reports"]) : 3,
619
+ });
620
+ return opts.format === "markdown" ? result.markdown : result;
621
+ }
622
+ if (!opts.project) fail("lessons requires --project");
623
+ return localLessons(opts.project);
624
+ }
625
+ const invokedAsScript = process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url);
626
+ if (invokedAsScript) {
627
+ cli().then((result) => {
628
+ process.stdout.write((typeof result === "string" ? result : JSON.stringify(result, null, 2)) + "\n");
629
+ }).catch((error) => {
630
+ process.stderr.write("GodPrompt proof bridge: " + error.message + "\n");
631
+ process.exitCode = 1;
632
+ });
633
+ }
package/dist/server.js CHANGED
@@ -3,7 +3,7 @@ import { CONTENT, VERSION } from "./content.js";
3
3
  import { CORE_SKILL } from "./skill-content.js";
4
4
  export const SERVER_INFO = {
5
5
  name: "god-prompt-mcp",
6
- version: "1.0.45",
6
+ version: "1.1.0",
7
7
  };
8
8
  export const SERVER_INSTRUCTIONS = "Start with get_core_skill for the lean GodPrompt protocol. Use classify_task to route a concrete task, then load get_protocols, get_gates, or get_anti_patterns only when that focused reference is needed. Use get_god_prompt only when the full single-file payload is preferable. All GodPrompt tools are read-only.";
9
9
  const READ_ONLY_ANNOTATIONS = {
package/dist/stdio.js CHANGED
@@ -3,9 +3,11 @@ import { McpServer } from "@modelcontextprotocol/server";
3
3
  import { serveStdio } from "@modelcontextprotocol/server/stdio";
4
4
  import { registerGodPromptTools, SERVER_INFO, SERVER_INSTRUCTIONS, } from "./server.js";
5
5
  import { registerGodPromptSkillExtension } from "./skills.js";
6
+ import { registerWorkContractTools, WORK_CONTRACT_INSTRUCTIONS } from "./work-contract.js";
6
7
  function createServer() {
7
- const server = new McpServer(SERVER_INFO, { instructions: SERVER_INSTRUCTIONS });
8
+ const server = new McpServer(SERVER_INFO, { instructions: `${SERVER_INSTRUCTIONS} ${WORK_CONTRACT_INSTRUCTIONS}` });
8
9
  registerGodPromptTools(server);
10
+ registerWorkContractTools(server);
9
11
  registerGodPromptSkillExtension(server);
10
12
  return server;
11
13
  }
@@ -0,0 +1,380 @@
1
+ import * as z from "zod/v4";
2
+ // A stateless, deterministic contract. This server never reads repositories,
3
+ // runs commands, contacts providers, stores user work, or grants permissions.
4
+ export const CONTRACT_SCHEMA = "godprompt.work_contract.v1";
5
+ export const WORK_CONTRACT_INSTRUCTIONS = "For coding tasks with scoped changes or required proof of completion, use classify_task then create_work_contract to define explicit acceptance, scope and actual verification commands before implementation. After authorized work, provide redacted command receipts and changed paths to review_work_evidence. All evidence is caller-supplied; a review is not independent verification, approval, or completion authorization.";
6
+ const TASK_TYPES = [
7
+ "BUILD", "DEBUG", "REFACTOR", "CONTENT", "DESIGN",
8
+ "SHIP", "ANALYZE", "AUTOMATE", "PLAN", "UNCLASSIFIED",
9
+ ];
10
+ const taskType = z.enum(TASK_TYPES);
11
+ const riskLevel = z.enum(["low", "medium", "high", "critical"]);
12
+ export function isScopedPath(value) {
13
+ if (!value || value.startsWith("/") || value.includes("\\") ||
14
+ value.includes("\0") || /^[a-zA-Z]:/.test(value) ||
15
+ value.includes("?") || value.includes("*"))
16
+ return false;
17
+ const path = value.endsWith("/") ? value.slice(0, -1) : value;
18
+ return path.length > 0 && path.split("/").every((segment) => segment.length > 0 && segment !== "." && segment !== "..");
19
+ }
20
+ const path = z.string().trim().min(1).max(240)
21
+ .refine(isScopedPath, "Use a relative POSIX path, or a directory ending with /. No globs, traversal or drive paths.");
22
+ const phrase = z.string().trim().min(3).max(500);
23
+ const command = z.string().trim().min(1).max(400);
24
+ const CreateInput = z.object({
25
+ task: z.string().trim().min(5).max(3000),
26
+ task_type: taskType.default("UNCLASSIFIED"),
27
+ risk_level: riskLevel.default("medium"),
28
+ allowed_paths: z.array(path).max(50).default([]),
29
+ forbidden_actions: z.array(phrase).max(30).default([]),
30
+ success_criteria: z.array(phrase).max(30).default([]),
31
+ verification_commands: z.array(command).max(30).default([]),
32
+ });
33
+ const ContractPayload = z.object({
34
+ schema: z.literal(CONTRACT_SCHEMA),
35
+ task: z.string().min(5).max(3000),
36
+ task_type: taskType,
37
+ risk_level: riskLevel,
38
+ allowed_paths: z.array(path).max(50),
39
+ forbidden_actions: z.array(phrase).max(30),
40
+ success_criteria: z.array(z.object({
41
+ id: z.string().regex(/^AC-[0-9]{2}$/),
42
+ text: phrase,
43
+ })).max(30),
44
+ verification_commands: z.array(z.object({
45
+ id: z.string().regex(/^VC-[0-9]{2}$/),
46
+ command,
47
+ })).max(30),
48
+ });
49
+ const Contract = ContractPayload.extend({
50
+ contract_id: z.string().regex(/^sha256:[a-f0-9]{64}$/),
51
+ });
52
+ function canonicalPayload(contract) {
53
+ return {
54
+ schema: contract.schema,
55
+ task: contract.task,
56
+ task_type: contract.task_type,
57
+ risk_level: contract.risk_level,
58
+ allowed_paths: contract.allowed_paths,
59
+ forbidden_actions: contract.forbidden_actions,
60
+ success_criteria: contract.success_criteria,
61
+ verification_commands: contract.verification_commands,
62
+ };
63
+ }
64
+ async function fingerprint(value) {
65
+ const bytes = new TextEncoder().encode(JSON.stringify(value));
66
+ const digest = await crypto.subtle.digest("SHA-256", bytes);
67
+ return "sha256:" + Array.from(new Uint8Array(digest))
68
+ .map((n) => n.toString(16).padStart(2, "0")).join("");
69
+ }
70
+ function missingDefinitions(contract) {
71
+ const issues = [];
72
+ if (contract.task_type === "UNCLASSIFIED")
73
+ issues.push({
74
+ code: "TASK_TYPE_UNCLASSIFIED",
75
+ detail: "Choose a task type. Use classify_task first, then resolve ambiguity explicitly.",
76
+ });
77
+ if (contract.allowed_paths.length === 0)
78
+ issues.push({
79
+ code: "SCOPE_UNDEFINED",
80
+ detail: "Supply exact allowable files or relative directory prefixes ending in /.",
81
+ });
82
+ if (contract.success_criteria.length === 0)
83
+ issues.push({
84
+ code: "ACCEPTANCE_UNDEFINED",
85
+ detail: "Supply user-approved, observable outcome-level success criteria.",
86
+ });
87
+ if (contract.verification_commands.length === 0)
88
+ issues.push({
89
+ code: "VERIFICATION_UNDEFINED",
90
+ detail: "Supply actual repository-appropriate verification commands. None are invented.",
91
+ });
92
+ return issues;
93
+ }
94
+ function duplicateValues(values) {
95
+ return new Set(values).size !== values.length;
96
+ }
97
+ export async function createWorkContract(raw) {
98
+ const input = CreateInput.parse(raw);
99
+ const payload = {
100
+ schema: CONTRACT_SCHEMA,
101
+ task: input.task,
102
+ task_type: input.task_type,
103
+ risk_level: input.risk_level,
104
+ allowed_paths: input.allowed_paths,
105
+ forbidden_actions: input.forbidden_actions,
106
+ success_criteria: input.success_criteria.map((text, i) => ({
107
+ id: "AC-" + String(i + 1).padStart(2, "0"),
108
+ text,
109
+ })),
110
+ verification_commands: input.verification_commands.map((commandText, i) => ({
111
+ id: "VC-" + String(i + 1).padStart(2, "0"),
112
+ command: commandText,
113
+ })),
114
+ };
115
+ const issues = missingDefinitions(payload);
116
+ if (duplicateValues(payload.allowed_paths))
117
+ issues.push({
118
+ code: "DUPLICATE_SCOPE_PATH",
119
+ detail: "Remove duplicate allowed paths before work begins.",
120
+ });
121
+ if (duplicateValues(payload.verification_commands.map((v) => v.command)))
122
+ issues.push({
123
+ code: "DUPLICATE_VERIFICATION",
124
+ detail: "Each required verification command should be unique.",
125
+ });
126
+ return {
127
+ contract: { ...payload, contract_id: await fingerprint(payload) },
128
+ definition_status: issues.length ? "NEEDS_DEFINITION" : "DEFINED",
129
+ issues,
130
+ workflow: [
131
+ "Understand authoritative requirements and current repository state.",
132
+ "Plan within the specified paths, forbidden actions and success criteria.",
133
+ "Execute only actions separately authorized by the user and the host.",
134
+ "Run required checks in the actual target environment and retain redacted receipts.",
135
+ "Submit evidence to review_work_evidence, then independently verify before completion claims.",
136
+ "Report complete, partial, blocked, or stopped truthfully; hand off this contract unchanged.",
137
+ ],
138
+ instructions: "Contract creation neither executes commands nor authorizes changes, deployment, merges, spending or completion claims. The SHA-256 ID detects accidental drift, not malicious forgery.",
139
+ };
140
+ }
141
+ const VerificationReceipt = z.object({
142
+ id: z.string().regex(/^VC-[0-9]{2}$/),
143
+ command,
144
+ exit_code: z.number().int().nullable(),
145
+ evidence_excerpt: z.string().max(1000).default(""),
146
+ source: z.enum(["tool_output", "self_report"]).default("self_report"),
147
+ });
148
+ const AcceptanceReceipt = z.object({
149
+ id: z.string().regex(/^AC-[0-9]{2}$/),
150
+ status: z.enum(["met", "unmet", "unknown"]),
151
+ evidence_refs: z.array(z.string().min(1).max(80)).max(20).default([]),
152
+ });
153
+ const Observation = z.object({
154
+ id: z.string().regex(/^OBS-[0-9]{2}$/),
155
+ note: z.string().trim().min(3).max(1000),
156
+ source: z.enum(["tool_output", "manual_report"]),
157
+ });
158
+ const ReviewInput = z.object({
159
+ contract: Contract,
160
+ changed_files: z.array(z.string().trim().min(1).max(240)).max(150).default([]),
161
+ operations_performed: z.array(phrase).max(100).default([]),
162
+ checks: z.array(VerificationReceipt).max(100).default([]),
163
+ acceptance: z.array(AcceptanceReceipt).max(100).default([]),
164
+ observations: z.array(Observation).max(100).default([]),
165
+ human_review_reported: z.boolean().default(false),
166
+ });
167
+ function isAllowed(file, allowed) {
168
+ if (!isScopedPath(file) || file.endsWith("/"))
169
+ return false;
170
+ return allowed.some((entry) => entry.endsWith("/") ? file.startsWith(entry) : file === entry);
171
+ }
172
+ function normalizeAction(text) {
173
+ return text.normalize("NFKC").toLowerCase().trim().replace(/\s+/g, " ");
174
+ }
175
+ function mentionsForbiddenAction(reported, forbidden) {
176
+ const operation = normalizeAction(reported);
177
+ const restriction = normalizeAction(forbidden);
178
+ if (operation === restriction)
179
+ return true;
180
+ // Conservative token/phrase matching, not an NLP authorization decision:
181
+ // "deployed to staging" must not silently bypass "deploy". A negated
182
+ // mention is also flagged for explicit review rather than treated as proof.
183
+ const variants = {
184
+ deploy: ["deploy", "deploys", "deployed", "deploying"],
185
+ merge: ["merge", "merges", "merged", "merging"],
186
+ publish: ["publish", "publishes", "published", "publishing"],
187
+ release: ["release", "releases", "released", "releasing"],
188
+ delete: ["delete", "deletes", "deleted", "deleting", "deletion"],
189
+ push: ["push", "pushes", "pushed", "pushing"],
190
+ spend: ["spend", "spends", "spent", "spending"],
191
+ trade: ["trade", "trades", "traded", "trading"],
192
+ };
193
+ const phrases = variants[restriction] ?? [restriction];
194
+ return phrases.some((phrase) => {
195
+ // Delimit tokens, so "deploy" does not match "undeployed".
196
+ let index = operation.indexOf(phrase);
197
+ while (index !== -1) {
198
+ const end = index + phrase.length;
199
+ const before = index === 0 || !/[a-z0-9]/.test(operation[index - 1]);
200
+ const after = end === operation.length || !/[a-z0-9]/.test(operation[end]);
201
+ if (before && after)
202
+ return true;
203
+ index = operation.indexOf(phrase, index + 1);
204
+ }
205
+ return false;
206
+ });
207
+ }
208
+ export async function reviewWorkEvidence(raw) {
209
+ const input = ReviewInput.parse(raw);
210
+ const contract = input.contract;
211
+ const issues = missingDefinitions(contract);
212
+ if (await fingerprint(canonicalPayload(contract)) !== contract.contract_id)
213
+ issues.push({
214
+ code: "CONTRACT_DRIFT",
215
+ detail: "Contract fields no longer match its SHA-256 fingerprint. Recreate and review the contract.",
216
+ });
217
+ if (duplicateValues(contract.allowed_paths))
218
+ issues.push({
219
+ code: "DUPLICATE_SCOPE_PATH",
220
+ detail: "Contract contains duplicate scope paths.",
221
+ });
222
+ if (duplicateValues(contract.verification_commands.map((v) => v.command)))
223
+ issues.push({
224
+ code: "DUPLICATE_VERIFICATION",
225
+ detail: "Contract contains duplicate verification commands.",
226
+ });
227
+ if (duplicateValues(input.checks.map((c) => c.id)))
228
+ issues.push({
229
+ code: "DUPLICATE_CHECK_RECEIPT",
230
+ detail: "More than one check receipt uses the same verification ID.",
231
+ });
232
+ if (duplicateValues(input.acceptance.map((c) => c.id)))
233
+ issues.push({
234
+ code: "DUPLICATE_ACCEPTANCE_RECEIPT",
235
+ detail: "More than one acceptance receipt uses the same criterion ID.",
236
+ });
237
+ if (duplicateValues(input.observations.map((o) => o.id)))
238
+ issues.push({
239
+ code: "DUPLICATE_OBSERVATION",
240
+ detail: "More than one observation uses the same ID.",
241
+ });
242
+ for (const file of input.changed_files) {
243
+ if (!isScopedPath(file) || file.endsWith("/"))
244
+ issues.push({
245
+ code: "INVALID_CHANGED_PATH",
246
+ detail: "Changed file path is not a safe relative file path: " + file,
247
+ });
248
+ else if (!isAllowed(file, contract.allowed_paths))
249
+ issues.push({
250
+ code: "OUT_OF_SCOPE_CHANGE",
251
+ detail: "Changed file is outside the defined paths: " + file,
252
+ });
253
+ }
254
+ for (const action of input.operations_performed) {
255
+ if (contract.forbidden_actions.some((restriction) => mentionsForbiddenAction(action, restriction)))
256
+ issues.push({
257
+ code: "PROHIBITED_ACTION_REPORTED",
258
+ detail: "A reported operation may include a forbidden action; inspect the original execution record: " + action,
259
+ });
260
+ }
261
+ const allowedCheckIds = new Set(contract.verification_commands.map((check) => check.id));
262
+ const allowedAcceptanceIds = new Set(contract.success_criteria.map((criterion) => criterion.id));
263
+ for (const receipt of input.checks) {
264
+ if (!allowedCheckIds.has(receipt.id))
265
+ issues.push({
266
+ code: "UNEXPECTED_CHECK_RECEIPT",
267
+ detail: "Check receipt ID is not specified by the contract: " + receipt.id,
268
+ });
269
+ }
270
+ for (const receipt of input.acceptance) {
271
+ if (!allowedAcceptanceIds.has(receipt.id))
272
+ issues.push({
273
+ code: "UNEXPECTED_ACCEPTANCE_RECEIPT",
274
+ detail: "Acceptance receipt ID is not specified by the contract: " + receipt.id,
275
+ });
276
+ }
277
+ const checks = new Map(input.checks.map((receipt) => [receipt.id, receipt]));
278
+ const evidenceIDs = new Set();
279
+ for (const expected of contract.verification_commands) {
280
+ const receipt = checks.get(expected.id);
281
+ if (!receipt) {
282
+ issues.push({
283
+ code: "MISSING_VERIFICATION",
284
+ detail: "No execution receipt for " + expected.id + " (" + expected.command + ").",
285
+ });
286
+ continue;
287
+ }
288
+ if (receipt.command !== expected.command)
289
+ issues.push({
290
+ code: "COMMAND_MISMATCH",
291
+ detail: "Command recorded for " + expected.id + " does not match the contract.",
292
+ });
293
+ else if (receipt.exit_code !== 0)
294
+ issues.push({
295
+ code: "VERIFICATION_FAILED",
296
+ detail: "Command " + expected.id + " has nonzero or missing exit code.",
297
+ });
298
+ else if (receipt.source !== "tool_output")
299
+ issues.push({
300
+ code: "SELF_REPORTED_CHECK",
301
+ detail: "Command " + expected.id + " has no attributed tool-output receipt.",
302
+ });
303
+ else if (!receipt.evidence_excerpt.trim())
304
+ issues.push({
305
+ code: "EVIDENCE_EXCERPT_MISSING",
306
+ detail: "Command " + expected.id + " has no bounded tool-output summary or original evidence reference.",
307
+ });
308
+ else
309
+ evidenceIDs.add(receipt.id);
310
+ }
311
+ for (const observation of input.observations)
312
+ evidenceIDs.add(observation.id);
313
+ const acceptance = new Map(input.acceptance.map((receipt) => [receipt.id, receipt]));
314
+ for (const criterion of contract.success_criteria) {
315
+ const receipt = acceptance.get(criterion.id);
316
+ if (!receipt || receipt.status !== "met") {
317
+ issues.push({
318
+ code: "ACCEPTANCE_NOT_MET",
319
+ detail: "Criterion " + criterion.id + " lacks a reported met result.",
320
+ });
321
+ continue;
322
+ }
323
+ if (receipt.evidence_refs.length === 0 ||
324
+ receipt.evidence_refs.some((ref) => !evidenceIDs.has(ref))) {
325
+ issues.push({
326
+ code: "ACCEPTANCE_EVIDENCE_MISSING",
327
+ detail: "Criterion " + criterion.id + " needs references to supplied successful checks or observations.",
328
+ });
329
+ }
330
+ }
331
+ if ((contract.risk_level === "high" || contract.risk_level === "critical") &&
332
+ !input.human_review_reported) {
333
+ issues.push({
334
+ code: "REVIEW_REQUIRED",
335
+ detail: "High/critical-risk work requires a separately authorized human review.",
336
+ });
337
+ }
338
+ return {
339
+ contract_id: contract.contract_id,
340
+ status: issues.length ? "HOLD" : "REPORTED_READY_FOR_INDEPENDENT_REVIEW",
341
+ issues,
342
+ reported_files: input.changed_files.length,
343
+ required_checks: contract.verification_commands.length,
344
+ supplied_check_receipts: input.checks.length,
345
+ required_acceptance_criteria: contract.success_criteria.length,
346
+ supplied_acceptance_receipts: input.acceptance.length,
347
+ independently_verified: false,
348
+ completion_authorized: false,
349
+ warning: "Every receipt and approval is caller-supplied and untrusted. This server did not execute or independently authenticate any command, diff, manual check or approval. A clean report is not proof of successful work or authorization to ship.",
350
+ next_step: issues.length
351
+ ? "Resolve the reported gaps and rerun evidence review. Do not claim task completion."
352
+ : "Independently inspect authoritative source tool outputs, actual diff, CI status and necessary approvals before a completion claim.",
353
+ };
354
+ }
355
+ const ANNOTATIONS = {
356
+ readOnlyHint: true,
357
+ destructiveHint: false,
358
+ idempotentHint: true,
359
+ openWorldHint: false,
360
+ };
361
+ function toolResult(value) {
362
+ return {
363
+ structuredContent: value,
364
+ content: [{ type: "text", text: JSON.stringify(value, null, 2) }],
365
+ };
366
+ }
367
+ export function registerWorkContractTools(server) {
368
+ server.registerTool("create_work_contract", {
369
+ title: "Create a bounded GodPrompt task contract",
370
+ description: "Create a portable, SHA-256-fingerprinted task contract with explicitly provided scope, acceptance criteria, verification commands and prohibitions. Deterministic, read-only and stateless. Use classify_task first; missing details produce NEEDS_DEFINITION, never inferred commands or permission to execute.",
371
+ inputSchema: CreateInput.shape,
372
+ annotations: ANNOTATIONS,
373
+ }, async (input) => toolResult(await createWorkContract(input)));
374
+ server.registerTool("review_work_evidence", {
375
+ title: "Review task completion evidence",
376
+ description: "Fail-closed audit of a create_work_contract result against supplied changed paths, command receipts, criteria, prohibited actions and risk review. Returns HOLD or REPORTED_READY_FOR_INDEPENDENT_REVIEW; never independently verifies caller-supplied evidence or authorizes completion, merge or deployment.",
377
+ inputSchema: ReviewInput.shape,
378
+ annotations: ANNOTATIONS,
379
+ }, async (input) => toolResult(await reviewWorkEvidence(input)));
380
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "god-prompt-mcp",
3
- "version": "1.0.45",
3
+ "version": "1.1.0",
4
4
  "mcpName": "io.github.AKzar1el/god-prompt-mcp",
5
5
  "description": "GodPrompt MCP server + portable Agent Skill for coding agents — TDD, debugging, verification gates, task routing, and progressive disclosure.",
6
6
  "private": false,
@@ -9,14 +9,17 @@
9
9
  "files": [
10
10
  "dist/stdio.js",
11
11
  "dist/server.js",
12
+ "dist/work-contract.js",
12
13
  "dist/skill-content.js",
13
14
  "dist/skills.js",
14
15
  "dist/content.js",
16
+ "bin/godprompt-proof.mjs",
15
17
  "README.md",
16
18
  "LICENSE"
17
19
  ],
18
20
  "bin": {
19
- "god-prompt-mcp": "dist/stdio.js"
21
+ "god-prompt-mcp": "dist/stdio.js",
22
+ "godprompt-proof": "bin/godprompt-proof.mjs"
20
23
  },
21
24
  "repository": {
22
25
  "type": "git",