Skip to content

Commit b5cb72b

Browse files
MrPickeringclaude
andcommitted
Story-so-far setup: host adapter, work packets, state bootstrap, facts ledger
Weaver's core stays deterministic: it builds work packets, a host (Claude Code interactively, or the `claude` CLI in batch) answers them, and Weaver validates and records the answers with the hashes of their inputs. - engine/host.mjs: runs the configured host with the prompt on stdin, WITHOUT ANTHROPIC_API_KEY in the child environment (so runs stay on the user's Claude subscription). Survives a host that exits early, times out a hung host, and retries once on a transient failure. Batch runs are concurrency-limited. Doctor warns when no host is available. - engine/packets.mjs: deterministic packet ids, JSON extraction, and one repair round for answers that fail validation; interactive `weaver packet` / `weaver submit`. - `weaver state bootstrap [--run]`: per-scene narrative-state records plus facts files for imported books, in reading order, resumable, and never auto-accepted (the author runs state:accept). Anti-invention rule: every fact must quote the scene verbatim, or the answer is repaired or skipped. After acceptance, imported books can release. - continuity/facts.json: a deterministic facts ledger (per character, in reading order, plus where each fact was first established), with a compact summary as packet context. Verified: npm run preflight (55/55) with a fake host covering the happy path through release, invented quotes, repair, retry, early exit, the API key never reaching the host, resume, and the interactive round trip. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Session-Id: 04db4d93-9884-44ee-b28f-627e92b33731 Agent: claude-code
1 parent a3add7b commit b5cb72b

14 files changed

Lines changed: 855 additions & 11 deletions

‎README.md‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,38 @@ npx weaver release --root ./my-book --id beta-01
181181
If an earlier scene changes, `state:status` marks it and all later scenes stale.
182182
Re-derive them in order before accepting state again.
183183

184+
## Story-so-far setup
185+
186+
Imported books have prose but no trusted scene-by-scene story-so-far records.
187+
Bootstrap derives those records and a facts ledger before release. Weaver only
188+
builds packets and checks answers; a configured command-line host does the AI
189+
work, and the author still accepts the resulting state:
190+
191+
```bash
192+
npx weaver state bootstrap --run --root ./my-book
193+
npx weaver state:accept --through 3-2 --root ./my-book
194+
npx weaver facts build --root ./my-book
195+
```
196+
197+
For an interactive Claude Code session, print one packet and submit its answer:
198+
199+
```bash
200+
npx weaver packet state --scene 1-1 --root ./my-book
201+
npx weaver submit <packet-id> --file ./answer.md --root ./my-book
202+
```
203+
204+
Answers contain a Markdown narrative-state record and a fenced JSON facts
205+
block. Every fact quote must be a verbatim 3–25 word excerpt from that scene;
206+
quotes from elsewhere are rejected, including after the single repair round.
207+
`continuity/facts.json` is deterministic derived state: it keeps facts in scene
208+
order and records the first scene that establishes each normalized value.
209+
210+
The host defaults to Claude Code (`claude -p --output-format text`) and can be
211+
set in `project.json` with `host.command`, `host.args`, `host.concurrency`, and
212+
`host.timeout_seconds`. Weaver removes `ANTHROPIC_API_KEY` from the child
213+
environment, so host runs use the user's Claude subscription rather than
214+
silently billing an API key. A missing host is a doctor warning, not a block.
215+
184216
## Commands
185217

186218
| Command | Purpose |
@@ -202,7 +234,11 @@ Re-derive them in order before accepting state again.
202234
| `history` | Show approvals and undos (`--json` supported) |
203235
| `hooks install` | Install or merge Claude Code scene-edit hooks |
204236
| `state:status` | Show current and stale derived-state records |
237+
| `state bootstrap` | Build story-so-far packets, optionally run them through the host |
205238
| `state:accept` | Stamp reviewed narrative state through a scene |
239+
| `packet state` | Print an interactive story-so-far packet |
240+
| `submit` | Validate and record a packet answer |
241+
| `facts build` | Rebuild the deterministic facts ledger |
206242
| `grounding <scene-id>` | Assemble the context packet for a writing pass |
207243
| `release --id <id>` | Build an immutable Markdown/HTML reader release |
208244

‎contracts/facts-ledger.schema.json‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
{
2+
"$schema": "https://json-schema.org/draft/2020-12/schema",
3+
"$id": "https://raw.githubusercontent.com/pickbitsai/weaver/main/contracts/facts-ledger.schema.json",
4+
"title": "Weaver facts ledger",
5+
"type": "object",
6+
"additionalProperties": false,
7+
"required": ["$schema", "generator", "manuscript_sha256", "subjects", "first_established"],
8+
"properties": {
9+
"$schema": { "const": "https://pickbits.ai/schemas/weaver/facts-ledger-1.json" },
10+
"generator": { "type": "string", "minLength": 1 },
11+
"manuscript_sha256": { "type": "string", "pattern": "^[a-f0-9]{64}$" },
12+
"subjects": {
13+
"type": "object",
14+
"additionalProperties": {
15+
"type": "array",
16+
"items": {
17+
"type": "object",
18+
"additionalProperties": false,
19+
"required": ["scene_id", "kind", "value", "quote"],
20+
"properties": {
21+
"scene_id": { "type": "string", "pattern": "^[0-9]+-[0-9]+$" },
22+
"kind": { "enum": ["location", "knowledge", "possession", "relationship", "event", "time"] },
23+
"value": { "type": "string", "minLength": 1 },
24+
"quote": { "type": "string", "minLength": 1 }
25+
}
26+
}
27+
}
28+
},
29+
"first_established": {
30+
"type": "array",
31+
"items": {
32+
"type": "object",
33+
"additionalProperties": false,
34+
"required": ["normalized_value", "subject", "kind", "scene_id"],
35+
"properties": {
36+
"normalized_value": { "type": "string", "minLength": 1 },
37+
"subject": { "type": "string", "minLength": 1 },
38+
"kind": { "enum": ["location", "knowledge", "possession", "relationship", "event", "time"] },
39+
"scene_id": { "type": "string", "pattern": "^[0-9]+-[0-9]+$" }
40+
}
41+
}
42+
}
43+
}
44+
}

‎contracts/facts.schema.json‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
{
2+
"$schema": "https://json-schema.org/draft/2020-12/schema",
3+
"$id": "https://raw.githubusercontent.com/pickbitsai/weaver/main/contracts/facts.schema.json",
4+
"title": "Weaver scene facts",
5+
"type": "object",
6+
"additionalProperties": false,
7+
"required": ["$schema", "scene_id", "prose_sha256", "packet_id", "generator", "facts"],
8+
"properties": {
9+
"$schema": { "const": "https://pickbits.ai/schemas/weaver/facts-1.json" },
10+
"scene_id": { "type": "string", "pattern": "^[0-9]+-[0-9]+$" },
11+
"prose_sha256": { "type": "string", "pattern": "^[a-f0-9]{64}$" },
12+
"packet_id": { "type": "string", "pattern": "^[a-f0-9]{12}$" },
13+
"generator": { "type": "string", "minLength": 1 },
14+
"facts": {
15+
"type": "array",
16+
"items": {
17+
"type": "object",
18+
"additionalProperties": false,
19+
"required": ["kind", "subject", "value", "quote"],
20+
"properties": {
21+
"kind": { "enum": ["location", "knowledge", "possession", "relationship", "event", "time"] },
22+
"subject": { "type": "string", "minLength": 1 },
23+
"value": { "type": "string", "minLength": 1 },
24+
"quote": { "type": "string", "minLength": 1 }
25+
}
26+
}
27+
}
28+
}
29+
}

‎contracts/project.schema.json‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,16 @@
3030
"reader_state_path": { "type": "string", "minLength": 1 },
3131
"outline_scene_root": { "type": "string", "minLength": 1 },
3232
"require_current_state_for_release": { "type": "boolean" },
33+
"host": {
34+
"type": "object",
35+
"additionalProperties": false,
36+
"properties": {
37+
"command": { "type": "string", "minLength": 1 },
38+
"args": { "type": "array", "items": { "type": "string" } },
39+
"concurrency": { "type": "integer", "minimum": 1, "maximum": 4 },
40+
"timeout_seconds": { "type": "integer", "minimum": 1 }
41+
}
42+
},
3343
"chapters": {
3444
"type": "object",
3545
"additionalProperties": { "type": "string" }

‎docs/WORKFLOW.md‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,22 @@ chapter and scene counts, POV decisions, and scene word counts. Imported books
3232
begin with missing or stale narrative state by design; `check` reports that
3333
state but does not fail on it until the project's state workflow is bootstrapped.
3434

35+
Before release, bootstrap the story-so-far records and facts ledger. The host
36+
answers deterministic packets, then the author reviews and accepts the records:
37+
38+
```bash
39+
weaver state bootstrap --run --root ./my-book
40+
weaver state:accept --through 3-2 --root ./my-book
41+
weaver facts build --root ./my-book
42+
```
43+
44+
The interactive route is `weaver packet state --scene 1-1`, followed by
45+
`weaver submit <packet-id> --file answer.md`. A malformed or deterministic
46+
validation failure gets one host repair attempt. Scene facts must use registry
47+
IDs (or `world`) and every quote must be a verbatim excerpt from that scene;
48+
invalid answers are skipped and never written. Editing an earlier scene makes
49+
its state and downstream state stale again, so bootstrap in reading order.
50+
3551
The repair path uses the same author approval boundary: imported or AI-edited
3652
scene changes appear in `weaver changes`, and the author approves or rejects
3753
one chapter at a time before continuing to state review and export.

‎engine/doctor.mjs‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { fileURLToPath } from "node:url";
77
import { compareIntegrity } from "./integrity.mjs";
88
import { GENERATOR } from "./identity.mjs";
99
import { WEAVER_HOOK_COMMANDS } from "./hooks.mjs";
10+
import { hostAvailable } from "./host.mjs";
1011

1112
const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
1213

@@ -60,6 +61,13 @@ const FINDINGS = {
6061
why: "PickBits Weaver runs with an AI that can run commands, such as Claude Code. Chat-only AIs (web chat windows) are not supported.",
6162
fix: "Use an AI that can run commands, such as Claude Code."
6263
},
64+
hostAvailable: {
65+
id: "host-available",
66+
problem: "The configured command-line AI host is not available",
67+
title: "Command-line AI host is available",
68+
why: "Bootstrap needs the configured command-line AI host to answer work packets.",
69+
fix: "install the command-line AI host (Claude Code) or set \"host\" in project.json."
70+
},
6371
hooksInstalled: {
6472
id: "hooks-installed",
6573
problem: "Weaver's Claude Code hooks are not installed",
@@ -213,6 +221,15 @@ export function runDoctor({ bookRoot, packageRoot = PACKAGE_ROOT, nodeVersion =
213221
warnings.push(...hostFinding);
214222
checks.push(checkResult(FINDINGS.host.id, FINDINGS.host.title, "warning", hostFinding));
215223

224+
let project = {};
225+
try { project = JSON.parse(readFileSync(join(root, "project.json"), "utf8")); } catch {
226+
// The project check is reported elsewhere; a missing project cannot make this warning blocking.
227+
}
228+
const available = hostAvailable(project);
229+
const availableFinding = available ? [] : [finding(FINDINGS.hostAvailable)];
230+
if (!available) warnings.push(...availableFinding);
231+
checks.push(checkResult(FINDINGS.hostAvailable.id, FINDINGS.hostAvailable.title, available ? "pass" : "warning", availableFinding));
232+
216233
return { generator: GENERATOR, ok: blocking.length === 0, blocking, warnings, checks };
217234
}
218235

‎engine/host.mjs‎

Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
// SPDX-License-Identifier: Apache-2.0
2+
// Copyright 2026 Mark Pickering and PICKBITS LLC. Part of PickBits Weaver.
3+
import { spawn, spawnSync } from "node:child_process";
4+
5+
export const DEFAULT_HOST = Object.freeze({
6+
command: "claude",
7+
args: ["-p", "--output-format", "text"],
8+
concurrency: 2,
9+
timeout_seconds: 600
10+
});
11+
12+
export function hostConfig(project = {}) {
13+
const configured = project.host || {};
14+
return {
15+
command: configured.command || DEFAULT_HOST.command,
16+
args: Array.isArray(configured.args) ? [...configured.args] : [...DEFAULT_HOST.args],
17+
concurrency: configured.concurrency || DEFAULT_HOST.concurrency,
18+
timeout_seconds: configured.timeout_seconds || DEFAULT_HOST.timeout_seconds
19+
};
20+
}
21+
22+
function safeEnvironment() {
23+
const environment = { ...process.env };
24+
delete environment.ANTHROPIC_API_KEY;
25+
return environment;
26+
}
27+
28+
function executableForShell(command) {
29+
if (process.platform !== "win32" || !/\s/u.test(command) || /^".*"$/u.test(command)) return command;
30+
return `"${command.replaceAll('"', '\\"')}"`;
31+
}
32+
33+
function runAttempt(config, promptText) {
34+
return new Promise((resolve) => {
35+
const started = Date.now();
36+
let child;
37+
try {
38+
child = spawn(executableForShell(config.command), config.args, {
39+
cwd: config.cwd,
40+
env: safeEnvironment(),
41+
shell: process.platform === "win32",
42+
stdio: ["pipe", "pipe", "pipe"]
43+
});
44+
} catch (error) {
45+
resolve({ ok: false, text: "", seconds: (Date.now() - started) / 1000, error: `could not start host: ${error.message}` });
46+
return;
47+
}
48+
49+
let stdout = "";
50+
let stderr = "";
51+
let settled = false;
52+
let timedOut = false;
53+
const finish = (result) => {
54+
if (settled) return;
55+
settled = true;
56+
clearTimeout(timer);
57+
resolve({ ...result, seconds: (Date.now() - started) / 1000 });
58+
};
59+
child.stdout.setEncoding("utf8");
60+
child.stderr.setEncoding("utf8");
61+
child.stdout.on("data", (chunk) => { stdout += chunk; });
62+
child.stderr.on("data", (chunk) => { stderr += chunk; });
63+
child.stdin.on("error", () => {
64+
// A host that exits before consuming its prompt may close stdin with EPIPE.
65+
});
66+
child.on("error", (error) => {
67+
finish({ ok: false, text: stdout, error: `could not start host: ${error.message}` });
68+
});
69+
child.on("close", (code, signal) => {
70+
if (timedOut) return;
71+
if (code !== 0) {
72+
const detail = stderr.trim() ? `: ${stderr.trim().replace(/\s+/gu, " ").slice(0, 240)}` : "";
73+
finish({ ok: false, text: stdout, error: `host exited with ${signal ? `signal ${signal}` : `code ${code}`}${detail}` });
74+
} else if (!stdout.trim()) {
75+
finish({ ok: false, text: stdout, error: "host returned empty output" });
76+
} else {
77+
finish({ ok: true, text: stdout });
78+
}
79+
});
80+
const timer = setTimeout(() => {
81+
timedOut = true;
82+
child.kill();
83+
finish({ ok: false, text: stdout, error: `host timed out after ${config.timeout_seconds} seconds` });
84+
}, config.timeout_seconds * 1000);
85+
try {
86+
child.stdin.end(promptText, () => {});
87+
} catch (error) {
88+
finish({ ok: false, text: stdout, error: `could not send prompt to host: ${error.message}` });
89+
}
90+
});
91+
}
92+
93+
export async function runHost(root, project, promptText) {
94+
const config = { ...hostConfig(project), cwd: root };
95+
const failures = [];
96+
const started = Date.now();
97+
for (let attempt = 1; attempt <= 2; attempt += 1) {
98+
const result = await runAttempt(config, promptText);
99+
if (result.ok) {
100+
return { ok: true, text: result.text, seconds: (Date.now() - started) / 1000, attempts: attempt };
101+
}
102+
failures.push(`attempt ${attempt}: ${result.error}`);
103+
}
104+
return {
105+
ok: false,
106+
text: "",
107+
seconds: (Date.now() - started) / 1000,
108+
attempts: 2,
109+
error: `host failed after 2 attempts: ${failures.join("; ")}`
110+
};
111+
}
112+
113+
export async function runHostBatch(root, project, prompts, { concurrency } = {}) {
114+
const limit = Math.min(4, Math.max(1, Number(concurrency || hostConfig(project).concurrency) || 1));
115+
const results = new Array(prompts.length);
116+
let next = 0;
117+
async function worker() {
118+
while (true) {
119+
const index = next;
120+
next += 1;
121+
if (index >= prompts.length) return;
122+
results[index] = await runHost(root, project, prompts[index]);
123+
}
124+
}
125+
await Promise.all(Array.from({ length: Math.min(limit, prompts.length) }, () => worker()));
126+
return results;
127+
}
128+
129+
export function hostAvailable(project, timeoutMs = 15_000) {
130+
const config = hostConfig(project);
131+
if (!/[\\/]/u.test(config.command)) {
132+
const locator = process.platform === "win32" ? "where.exe" : "which";
133+
const found = spawnSync(locator, [config.command], { encoding: "utf8", timeout: Math.min(timeoutMs, 2_000), stdio: ["ignore", "pipe", "ignore"] });
134+
if (found.status !== 0) return false;
135+
}
136+
const result = spawnSync(executableForShell(config.command), ["--version"], {
137+
env: safeEnvironment(),
138+
shell: process.platform === "win32",
139+
timeout: timeoutMs,
140+
encoding: "utf8",
141+
stdio: ["ignore", "pipe", "pipe"]
142+
});
143+
return result.status === 0 && !result.error;
144+
}

0 commit comments

Comments
 (0)