scrumrun 2.0.0 → 2.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.
@@ -0,0 +1,240 @@
1
+ "use strict";
2
+
3
+ const fs = require("node:fs");
4
+ const path = require("node:path");
5
+ const {
6
+ ArtifactRepository,
7
+ METHOD_VERSION,
8
+ assertNoSymlinkPath,
9
+ atomicWrite,
10
+ parseArtifact,
11
+ serializeArtifact,
12
+ sha256,
13
+ validateArtifact,
14
+ withArtifactLock
15
+ } = require("./artifacts");
16
+ const { RUN_LEDGER_VERSION } = require("./schema");
17
+ const { migrateLegacyRun, validateRunLedger } = require("../runtime/run-ledger");
18
+
19
+ const MIGRATION_NAME = "run-ledger-v1";
20
+ const MIGRATION_DIR = path.join(".migration", MIGRATION_NAME);
21
+ const MANIFEST_PATH = path.join(MIGRATION_DIR, "manifest.json");
22
+
23
+ function posix(value) {
24
+ return value.split(path.sep).join("/");
25
+ }
26
+
27
+ function backupPath(relative) {
28
+ return posix(path.join(MIGRATION_DIR, "backup", relative));
29
+ }
30
+
31
+ function readMarker(scrumDir) {
32
+ const file = assertNoSymlinkPath(scrumDir, path.join(scrumDir, "method.json"));
33
+ if (!fs.existsSync(file) || !fs.lstatSync(file).isFile()) throw new Error("Canonical method.json is missing or unsafe.");
34
+ try {
35
+ const value = JSON.parse(fs.readFileSync(file, "utf8"));
36
+ if (value.method !== METHOD_VERSION) throw new Error(`method must be ${METHOD_VERSION}`);
37
+ return { file, value, content: fs.readFileSync(file, "utf8") };
38
+ } catch (error) {
39
+ throw new Error(`Canonical method.json is malformed: ${error.message}`);
40
+ }
41
+ }
42
+
43
+ function planRunLedgerMigration(projectRoot) {
44
+ const scrumDir = path.join(projectRoot, ".scrumrun");
45
+ if (!fs.existsSync(scrumDir) || !fs.lstatSync(scrumDir).isDirectory()) throw new Error("Not a ScrumRun project: .scrumrun/ is missing.");
46
+ const marker = readMarker(scrumDir);
47
+ const repository = new ArtifactRepository(scrumDir);
48
+ const changes = [];
49
+ const warnings = [];
50
+ const errors = [];
51
+
52
+ for (const artifact of repository.list("run")) {
53
+ if (!artifact.record || artifact.errors.length) {
54
+ errors.push(`${path.relative(scrumDir, artifact.file)}: ${artifact.errors.join("; ")}`);
55
+ continue;
56
+ }
57
+ if (artifact.record.ledger === RUN_LEDGER_VERSION) {
58
+ const ledger = validateRunLedger(artifact.record, artifact.body);
59
+ for (const error of ledger.errors) errors.push(`${artifact.record.id}: ${error}`);
60
+ continue;
61
+ }
62
+ const relative = posix(path.relative(scrumDir, artifact.file));
63
+ const before = fs.readFileSync(artifact.file, "utf8");
64
+ try {
65
+ const migrated = migrateLegacyRun(artifact.record, artifact.body, {
66
+ legacyHash: sha256(before),
67
+ backupRef: `.scrumrun/${backupPath(relative)}`
68
+ });
69
+ const after = serializeArtifact(migrated.record, migrated.body);
70
+ const parsed = parseArtifact(after);
71
+ const validation = [...parsed.errors, ...validateArtifact(parsed.record, "run"), ...validateRunLedger(parsed.record, parsed.body).errors];
72
+ if (validation.length) throw new Error(validation.join("; "));
73
+ changes.push({ relative, before, after, beforeSha256: sha256(before), afterSha256: sha256(after), mode: migrated.mode });
74
+ if (migrated.mode === "snapshot") warnings.push(`${artifact.record.id}: missing transition history is preserved as an evidenced snapshot, not reconstructed.`);
75
+ } catch (error) {
76
+ errors.push(`${artifact.record.id}: ${error.message}`);
77
+ }
78
+ }
79
+
80
+ const markerValue = {
81
+ ...marker.value,
82
+ schemas: { ...(marker.value.schemas || {}), run_ledger: RUN_LEDGER_VERSION }
83
+ };
84
+ const markerAfter = `${JSON.stringify(markerValue, null, 2)}\n`;
85
+ if (marker.content !== markerAfter) {
86
+ changes.push({
87
+ relative: "method.json",
88
+ before: marker.content,
89
+ after: markerAfter,
90
+ beforeSha256: sha256(marker.content),
91
+ afterSha256: sha256(markerAfter),
92
+ mode: "schema-marker"
93
+ });
94
+ }
95
+ const fingerprint = sha256(changes.map((change) => `${change.relative}\0${change.beforeSha256}`).sort().join("\n"));
96
+ return {
97
+ projectRoot,
98
+ scrumDir,
99
+ status: errors.length ? "blocked" : changes.length ? "ready" : "current",
100
+ migration: MIGRATION_NAME,
101
+ ledger: RUN_LEDGER_VERSION,
102
+ fingerprint,
103
+ changes,
104
+ warnings,
105
+ errors
106
+ };
107
+ }
108
+
109
+ function reportRunLedgerMigration(plan, status = plan.status) {
110
+ const mappings = plan.changes.length
111
+ ? plan.changes.map((change) => `- \`${change.relative}\` · ${change.mode} · \`${change.beforeSha256.slice(0, 12)}\` → \`${change.afterSha256.slice(0, 12)}\``).join("\n")
112
+ : "- No changes required.";
113
+ const warnings = plan.warnings.length ? plan.warnings.map((warning) => `- ${warning}`).join("\n") : "- None.";
114
+ const errors = plan.errors.length ? plan.errors.map((error) => `- ${error}`).join("\n") : "- None.";
115
+ return `# ScrumRun Run Ledger Migration\n\nStatus: ${status}\nSchema: ${RUN_LEDGER_VERSION}\nSource fingerprint: \`${plan.fingerprint}\`\nChanged files: ${plan.changes.length}\n\n## Mappings\n\n${mappings}\n\n## Warnings\n\n${warnings}\n\n## Blockers\n\n${errors}\n`;
116
+ }
117
+
118
+ function manifestFile(scrumDir) {
119
+ return assertNoSymlinkPath(scrumDir, path.join(scrumDir, MANIFEST_PATH));
120
+ }
121
+
122
+ function loadManifest(scrumDir) {
123
+ const file = manifestFile(scrumDir);
124
+ if (!fs.existsSync(file)) return null;
125
+ if (!fs.lstatSync(file).isFile() || fs.lstatSync(file).isSymbolicLink()) throw new Error("Run ledger migration manifest is unsafe.");
126
+ return JSON.parse(fs.readFileSync(file, "utf8"));
127
+ }
128
+
129
+ function backupChanges(plan) {
130
+ for (const change of plan.changes) {
131
+ const target = assertNoSymlinkPath(plan.scrumDir, path.join(plan.scrumDir, backupPath(change.relative)));
132
+ if (fs.existsSync(target)) {
133
+ if (sha256(fs.readFileSync(target)) !== change.beforeSha256) throw new Error(`Migration backup conflicts for ${change.relative}.`);
134
+ continue;
135
+ }
136
+ atomicWrite(target, change.before);
137
+ }
138
+ }
139
+
140
+ function verifyChanges(scrumDir, changes, field) {
141
+ const problems = [];
142
+ for (const change of changes) {
143
+ const file = assertNoSymlinkPath(scrumDir, path.join(scrumDir, change.relative));
144
+ const actual = fs.existsSync(file) && fs.lstatSync(file).isFile() ? sha256(fs.readFileSync(file)) : "missing";
145
+ if (actual !== change[field]) problems.push(`${change.relative}: expected ${change[field]}, found ${actual}`);
146
+ }
147
+ return problems;
148
+ }
149
+
150
+ function restoreChanges(scrumDir, changes) {
151
+ for (const change of [...changes].reverse()) {
152
+ const backup = assertNoSymlinkPath(scrumDir, path.join(scrumDir, backupPath(change.relative)));
153
+ if (!fs.existsSync(backup) || sha256(fs.readFileSync(backup)) !== change.beforeSha256) {
154
+ throw new Error(`Run ledger backup is missing or corrupt for ${change.relative}.`);
155
+ }
156
+ const target = assertNoSymlinkPath(scrumDir, path.join(scrumDir, change.relative));
157
+ atomicWrite(target, fs.readFileSync(backup));
158
+ }
159
+ }
160
+
161
+ function recoverPrepared(scrumDir, manifest) {
162
+ if (!manifest || manifest.status !== "prepared") return false;
163
+ const allowed = [];
164
+ for (const change of manifest.changes) {
165
+ const file = path.join(scrumDir, change.relative);
166
+ const actual = fs.existsSync(file) ? sha256(fs.readFileSync(file)) : "missing";
167
+ if (![change.beforeSha256, change.afterSha256].includes(actual)) allowed.push(`${change.relative}: unexpected ${actual}`);
168
+ }
169
+ if (allowed.length) throw new Error(`Interrupted Run ledger migration cannot recover safely:\n${allowed.join("\n")}`);
170
+ restoreChanges(scrumDir, manifest.changes);
171
+ atomicWrite(manifestFile(scrumDir), `${JSON.stringify({ ...manifest, status: "recovered", recovered_at: new Date().toISOString() }, null, 2)}\n`);
172
+ return true;
173
+ }
174
+
175
+ function applyRunLedgerMigration(projectRoot, { failurePoint = null } = {}) {
176
+ const scrumDir = path.join(projectRoot, ".scrumrun");
177
+ const preview = planRunLedgerMigration(projectRoot);
178
+ if (preview.errors.length) throw new Error(`Run ledger migration is blocked:\n${preview.errors.join("\n")}`);
179
+ if (!preview.changes.length) return { status: "current", plan: preview, output: reportRunLedgerMigration(preview, "current") };
180
+ return withArtifactLock(scrumDir, "run-ledger-migration", () => {
181
+ const existing = loadManifest(scrumDir);
182
+ if (existing && existing.status === "prepared") recoverPrepared(scrumDir, existing);
183
+ const plan = planRunLedgerMigration(projectRoot);
184
+ if (plan.errors.length) throw new Error(`Run ledger migration is blocked:\n${plan.errors.join("\n")}`);
185
+ if (!plan.changes.length) return { status: "current", plan, output: reportRunLedgerMigration(plan, "current") };
186
+ const changed = verifyChanges(scrumDir, plan.changes, "beforeSha256");
187
+ if (changed.length) throw new Error(`Run ledger source changed after preflight:\n${changed.join("\n")}`);
188
+ backupChanges(plan);
189
+ const manifest = {
190
+ migration: MIGRATION_NAME,
191
+ schema: RUN_LEDGER_VERSION,
192
+ status: "prepared",
193
+ prepared_at: new Date().toISOString(),
194
+ source_fingerprint: plan.fingerprint,
195
+ changes: plan.changes.map(({ relative, beforeSha256, afterSha256, mode }) => ({ relative, beforeSha256, afterSha256, mode }))
196
+ };
197
+ atomicWrite(manifestFile(scrumDir), `${JSON.stringify(manifest, null, 2)}\n`);
198
+ try {
199
+ for (let index = 0; index < plan.changes.length; index++) {
200
+ const change = plan.changes[index];
201
+ const target = assertNoSymlinkPath(scrumDir, path.join(scrumDir, change.relative));
202
+ atomicWrite(target, change.after);
203
+ if (failurePoint === `after-${index + 1}`) throw new Error(`Injected Run ledger migration failure after write ${index + 1}.`);
204
+ }
205
+ const afterProblems = verifyChanges(scrumDir, plan.changes, "afterSha256");
206
+ if (afterProblems.length) throw new Error(`Run ledger migration verification failed:\n${afterProblems.join("\n")}`);
207
+ const applied = { ...manifest, status: "applied", applied_at: new Date().toISOString() };
208
+ atomicWrite(manifestFile(scrumDir), `${JSON.stringify(applied, null, 2)}\n`);
209
+ return { status: "applied", plan, manifest: applied, output: reportRunLedgerMigration(plan, "applied") };
210
+ } catch (error) {
211
+ restoreChanges(scrumDir, manifest.changes);
212
+ atomicWrite(manifestFile(scrumDir), `${JSON.stringify({ ...manifest, status: "recovered", recovered_at: new Date().toISOString() }, null, 2)}\n`);
213
+ throw error;
214
+ }
215
+ });
216
+ }
217
+
218
+ function rollbackRunLedgerMigration(projectRoot) {
219
+ const scrumDir = path.join(projectRoot, ".scrumrun");
220
+ return withArtifactLock(scrumDir, "run-ledger-migration", () => {
221
+ const manifest = loadManifest(scrumDir);
222
+ if (!manifest || !["applied", "prepared"].includes(manifest.status)) throw new Error("No applied Run ledger migration is available for rollback.");
223
+ if (manifest.status === "applied") {
224
+ const changed = verifyChanges(scrumDir, manifest.changes, "afterSha256");
225
+ if (changed.length) throw new Error(`Rollback would erase post-migration changes:\n${changed.join("\n")}`);
226
+ }
227
+ restoreChanges(scrumDir, manifest.changes);
228
+ const rolledBack = { ...manifest, status: "rolled-back", rolled_back_at: new Date().toISOString() };
229
+ atomicWrite(manifestFile(scrumDir), `${JSON.stringify(rolledBack, null, 2)}\n`);
230
+ return { status: "rolled-back", manifest: rolledBack };
231
+ });
232
+ }
233
+
234
+ module.exports = {
235
+ MIGRATION_NAME,
236
+ applyRunLedgerMigration,
237
+ planRunLedgerMigration,
238
+ reportRunLedgerMigration,
239
+ rollbackRunLedgerMigration
240
+ };
package/lib/v2/schema.js CHANGED
@@ -7,6 +7,22 @@ function deepFreeze(value) {
7
7
  }
8
8
 
9
9
  const METHOD_VERSION = "2.0.0";
10
+ const RUN_LEDGER_VERSION = 1;
11
+
12
+ const RUN_EVENT_TYPES = deepFreeze(["transition", "snapshot"]);
13
+ const RUN_EVIDENCE_KINDS = deepFreeze([
14
+ "approval",
15
+ "command",
16
+ "test",
17
+ "file",
18
+ "review",
19
+ "decision",
20
+ "insight",
21
+ "risk",
22
+ "note",
23
+ "migration",
24
+ "legacy"
25
+ ]);
10
26
 
11
27
  const ARTIFACT_TYPES = deepFreeze({
12
28
  feature: {
@@ -92,7 +108,8 @@ const STRUCTURAL_RELATIONS = deepFreeze({
92
108
  });
93
109
 
94
110
  const SCALAR_FIELDS = deepFreeze({
95
- attempt: { kinds: ["run"], required: true, type: "positive integer", meaning: "monotonic execution-attempt number within one Task" }
111
+ attempt: { kinds: ["run"], required: true, type: "positive integer", meaning: "monotonic execution-attempt number within one Task" },
112
+ ledger: { kinds: ["run"], required: false, type: `integer ${RUN_LEDGER_VERSION}`, meaning: "canonical Run event-ledger schema; required for newly authored Runs" }
96
113
  });
97
114
 
98
115
  const TRUTH_OWNERSHIP = deepFreeze({
@@ -121,6 +138,9 @@ module.exports = {
121
138
  ARTIFACT_TYPES,
122
139
  AUTHORITY,
123
140
  METHOD_VERSION,
141
+ RUN_EVENT_TYPES,
142
+ RUN_EVIDENCE_KINDS,
143
+ RUN_LEDGER_VERSION,
124
144
  SCALAR_FIELDS,
125
145
  STRUCTURAL_RELATIONS,
126
146
  TRUTH_OWNERSHIP,
@@ -0,0 +1,254 @@
1
+ "use strict";
2
+
3
+ const crypto = require("node:crypto");
4
+ const fs = require("node:fs");
5
+ const path = require("node:path");
6
+ const {
7
+ assertNoSymlinkPath,
8
+ atomicWrite,
9
+ sha256,
10
+ withArtifactLock
11
+ } = require("./artifacts");
12
+
13
+ const TRANSACTION_SCHEMA = 1;
14
+ const TRANSACTION_ROOT = path.join(".backup", "transactions");
15
+ const PENDING_DIR = path.join(TRANSACTION_ROOT, "pending");
16
+ const RECEIPT_DIR = path.join(TRANSACTION_ROOT, "receipts");
17
+ const FORBIDDEN = [".backup/", ".cache/", ".migration/", "vault.local.md"];
18
+
19
+ function posix(value) {
20
+ return value.split(path.sep).join("/");
21
+ }
22
+
23
+ function transactionId() {
24
+ return `TXN-${Date.now()}-${crypto.randomBytes(6).toString("hex")}`;
25
+ }
26
+
27
+ function safeTransactionPath(scrumDir, relative) {
28
+ return assertNoSymlinkPath(scrumDir, path.join(scrumDir, relative));
29
+ }
30
+
31
+ function relativeTarget(scrumDir, file) {
32
+ const target = assertNoSymlinkPath(scrumDir, path.resolve(file));
33
+ const relative = posix(path.relative(path.resolve(scrumDir), target));
34
+ if (!relative || relative.startsWith("../") || path.isAbsolute(relative)) throw new Error(`Transaction target escapes .scrumrun: ${file}`);
35
+ if (FORBIDDEN.some((entry) => relative === entry.replace(/\/$/, "") || relative.startsWith(entry))) {
36
+ throw new Error(`Transaction target is outside the canonical mutation boundary: ${relative}`);
37
+ }
38
+ return { relative, file: target };
39
+ }
40
+
41
+ function snapshot(content) {
42
+ if (content === null) return { exists: false, sha256: "missing", content_base64: null };
43
+ const value = Buffer.isBuffer(content) ? content : Buffer.from(String(content));
44
+ return { exists: true, sha256: sha256(value), content_base64: value.toString("base64") };
45
+ }
46
+
47
+ function fileSnapshot(scrumDir, relative) {
48
+ const file = safeTransactionPath(scrumDir, relative);
49
+ if (!fs.existsSync(file)) return snapshot(null);
50
+ if (!fs.lstatSync(file).isFile()) throw new Error(`Transaction target is not a regular file: ${relative}`);
51
+ return snapshot(fs.readFileSync(file));
52
+ }
53
+
54
+ function sameSnapshot(left, right) {
55
+ return Boolean(left && right && left.exists === right.exists && left.sha256 === right.sha256);
56
+ }
57
+
58
+ function applySnapshot(scrumDir, relative, value) {
59
+ const file = safeTransactionPath(scrumDir, relative);
60
+ if (!value.exists) {
61
+ if (fs.existsSync(file)) fs.rmSync(file, { force: true });
62
+ return;
63
+ }
64
+ atomicWrite(file, Buffer.from(value.content_base64, "base64"));
65
+ }
66
+
67
+ function pendingDirectory(scrumDir) {
68
+ return safeTransactionPath(scrumDir, PENDING_DIR);
69
+ }
70
+
71
+ function receipt(transaction, status, details = {}) {
72
+ return {
73
+ schema: TRANSACTION_SCHEMA,
74
+ id: transaction.id,
75
+ name: transaction.name,
76
+ status,
77
+ created_at: transaction.created_at,
78
+ finished_at: new Date().toISOString(),
79
+ changes: transaction.changes.map((change) => ({
80
+ relative: change.relative,
81
+ before_sha256: change.before.sha256,
82
+ after_sha256: change.after.sha256
83
+ })),
84
+ ...details
85
+ };
86
+ }
87
+
88
+ function finishJournal(scrumDir, journalFile, transaction, status, details = {}) {
89
+ const receiptFile = safeTransactionPath(scrumDir, path.join(RECEIPT_DIR, `${transaction.id}.json`));
90
+ atomicWrite(receiptFile, `${JSON.stringify(receipt(transaction, status, details), null, 2)}\n`);
91
+ fs.rmSync(journalFile, { force: true });
92
+ }
93
+
94
+ function pendingTransactions(scrumDir) {
95
+ const directory = pendingDirectory(scrumDir);
96
+ if (!fs.existsSync(directory)) return [];
97
+ if (!fs.lstatSync(directory).isDirectory()) throw new Error("Transaction pending path is not a directory.");
98
+ const entries = fs.readdirSync(directory, { withFileTypes: true }).sort((left, right) => left.name.localeCompare(right.name));
99
+ for (const entry of entries) {
100
+ if (entry.isSymbolicLink() || !entry.isFile() || !/^TXN-[a-zA-Z0-9-]+\.json$/.test(entry.name)) {
101
+ throw new Error(`Unexpected transaction journal entry: ${entry.name}`);
102
+ }
103
+ }
104
+ return entries.map((entry) => {
105
+ const file = safeTransactionPath(scrumDir, path.join(PENDING_DIR, entry.name));
106
+ try {
107
+ const transaction = JSON.parse(fs.readFileSync(file, "utf8"));
108
+ return { file, transaction };
109
+ } catch (error) {
110
+ throw new Error(`Transaction journal is malformed: ${entry.name}: ${error.message}`);
111
+ }
112
+ });
113
+ }
114
+
115
+ function validateJournal(transaction) {
116
+ const errors = [];
117
+ if (!transaction || transaction.schema !== TRANSACTION_SCHEMA) errors.push(`schema must be ${TRANSACTION_SCHEMA}`);
118
+ if (!/^TXN-[a-zA-Z0-9-]+$/.test(transaction && transaction.id || "")) errors.push("id is invalid");
119
+ if (!transaction || !["prepared", "committed"].includes(transaction.status)) errors.push("status must be prepared or committed");
120
+ if (!transaction || !Array.isArray(transaction.changes) || !transaction.changes.length) errors.push("changes must be a non-empty array");
121
+ for (const change of transaction && Array.isArray(transaction.changes) ? transaction.changes : []) {
122
+ if (typeof change.relative !== "string" || !change.relative) errors.push("change.relative is required");
123
+ for (const key of ["before", "after"]) {
124
+ const value = change[key];
125
+ if (!value || typeof value.exists !== "boolean" || typeof value.sha256 !== "string") errors.push(`${change.relative || "change"}.${key} is malformed`);
126
+ if (value && value.exists && typeof value.content_base64 !== "string") errors.push(`${change.relative || "change"}.${key} content is missing`);
127
+ if (value && value.exists && typeof value.content_base64 === "string") {
128
+ const decoded = Buffer.from(value.content_base64, "base64");
129
+ if (decoded.toString("base64") !== value.content_base64 || sha256(decoded) !== value.sha256) {
130
+ errors.push(`${change.relative || "change"}.${key} content hash is invalid`);
131
+ }
132
+ }
133
+ if (value && !value.exists && (value.sha256 !== "missing" || value.content_base64 !== null)) {
134
+ errors.push(`${change.relative || "change"}.${key} missing snapshot is invalid`);
135
+ }
136
+ }
137
+ }
138
+ return errors;
139
+ }
140
+
141
+ function recoverPendingTransactionsUnlocked(scrumDir) {
142
+ const recovered = [];
143
+ for (const { file, transaction } of pendingTransactions(scrumDir)) {
144
+ const errors = validateJournal(transaction);
145
+ if (errors.length) throw new Error(`Unsafe transaction journal ${path.basename(file)}: ${errors.join("; ")}`);
146
+ for (const change of transaction.changes) {
147
+ const target = relativeTarget(scrumDir, path.join(scrumDir, change.relative));
148
+ if (target.relative !== change.relative) throw new Error(`Unsafe transaction target in ${transaction.id}: ${change.relative}`);
149
+ }
150
+ const current = transaction.changes.map((change) => ({ change, value: fileSnapshot(scrumDir, change.relative) }));
151
+ const unexpected = current.filter(({ change, value }) => !sameSnapshot(value, change.before) && !sameSnapshot(value, change.after));
152
+ if (unexpected.length) {
153
+ throw new Error(`Pending transaction ${transaction.id} cannot recover without overwriting owner changes: ${unexpected.map(({ change }) => change.relative).join(", ")}`);
154
+ }
155
+ if (transaction.status === "prepared") {
156
+ for (const change of [...transaction.changes].reverse()) applySnapshot(scrumDir, change.relative, change.before);
157
+ const unrestored = transaction.changes.filter((change) => !sameSnapshot(fileSnapshot(scrumDir, change.relative), change.before));
158
+ if (unrestored.length) throw new Error(`Transaction ${transaction.id} recovery verification failed: ${unrestored.map((change) => change.relative).join(", ")}`);
159
+ finishJournal(scrumDir, file, transaction, "recovered", { action: "rolled-back-prepared" });
160
+ recovered.push({ id: transaction.id, action: "rolled-back" });
161
+ } else {
162
+ const incomplete = current.filter(({ change, value }) => !sameSnapshot(value, change.after));
163
+ if (incomplete.length) throw new Error(`Committed transaction ${transaction.id} is incomplete: ${incomplete.map(({ change }) => change.relative).join(", ")}`);
164
+ finishJournal(scrumDir, file, transaction, "committed", { action: "verified-commit" });
165
+ recovered.push({ id: transaction.id, action: "verified" });
166
+ }
167
+ }
168
+ return recovered;
169
+ }
170
+
171
+ function recoverPendingTransactions(scrumDir) {
172
+ return withArtifactLock(scrumDir, "kernel", () => recoverPendingTransactionsUnlocked(scrumDir));
173
+ }
174
+
175
+ function normalizeChanges(scrumDir, changes) {
176
+ if (!Array.isArray(changes) || !changes.length) throw new Error("Kernel transaction requires at least one change.");
177
+ const seen = new Set();
178
+ return changes.map((change) => {
179
+ const target = relativeTarget(scrumDir, change.file);
180
+ if (seen.has(target.relative)) throw new Error(`Duplicate transaction target: ${target.relative}`);
181
+ seen.add(target.relative);
182
+ if (!Object.prototype.hasOwnProperty.call(change, "previous") || !Object.prototype.hasOwnProperty.call(change, "next")) {
183
+ throw new Error(`Transaction change requires previous and next content: ${target.relative}`);
184
+ }
185
+ return { relative: target.relative, before: snapshot(change.previous), after: snapshot(change.next) };
186
+ });
187
+ }
188
+
189
+ function writeKernelTransactionUnlocked(scrumDir, name, changes, { failurePoint = null, interruptPoint = null } = {}) {
190
+ if (!/^[a-z0-9-]+$/i.test(name || "")) throw new Error(`Invalid transaction name: ${name || "missing"}`);
191
+ const normalized = normalizeChanges(scrumDir, changes);
192
+ const conflicts = normalized.filter((change) => !sameSnapshot(fileSnapshot(scrumDir, change.relative), change.before));
193
+ if (conflicts.length) throw new Error(`Transaction source changed before prepare: ${conflicts.map((change) => change.relative).join(", ")}`);
194
+ const transaction = {
195
+ schema: TRANSACTION_SCHEMA,
196
+ id: transactionId(),
197
+ name,
198
+ status: "prepared",
199
+ created_at: new Date().toISOString(),
200
+ changes: normalized
201
+ };
202
+ const journalFile = safeTransactionPath(scrumDir, path.join(PENDING_DIR, `${transaction.id}.json`));
203
+ atomicWrite(journalFile, `${JSON.stringify(transaction, null, 2)}\n`);
204
+ if (interruptPoint === "after-prepare") throw Object.assign(new Error("Simulated interruption after transaction prepare."), { code: "SCRUMRUN_INTERRUPTED" });
205
+ try {
206
+ for (let index = 0; index < transaction.changes.length; index++) {
207
+ const change = transaction.changes[index];
208
+ applySnapshot(scrumDir, change.relative, change.after);
209
+ if (interruptPoint === `after-${index + 1}`) {
210
+ throw Object.assign(new Error(`Simulated interruption after transaction write ${index + 1}.`), { code: "SCRUMRUN_INTERRUPTED" });
211
+ }
212
+ if (failurePoint === `after-${index + 1}`) throw new Error(`Injected transaction failure after write ${index + 1}.`);
213
+ }
214
+ const invalid = transaction.changes.filter((change) => !sameSnapshot(fileSnapshot(scrumDir, change.relative), change.after));
215
+ if (invalid.length) throw new Error(`Transaction verification failed: ${invalid.map((change) => change.relative).join(", ")}`);
216
+ const committed = { ...transaction, status: "committed", committed_at: new Date().toISOString() };
217
+ atomicWrite(journalFile, `${JSON.stringify(committed, null, 2)}\n`);
218
+ if (interruptPoint === "after-commit") {
219
+ throw Object.assign(new Error("Simulated interruption after transaction commit."), { code: "SCRUMRUN_INTERRUPTED" });
220
+ }
221
+ finishJournal(scrumDir, journalFile, committed, "committed", { action: "applied" });
222
+ return { id: transaction.id, status: "committed", changes: transaction.changes.length };
223
+ } catch (error) {
224
+ if (error.code === "SCRUMRUN_INTERRUPTED") throw error;
225
+ for (const change of [...transaction.changes].reverse()) applySnapshot(scrumDir, change.relative, change.before);
226
+ finishJournal(scrumDir, journalFile, transaction, "recovered", { action: "rolled-back-error", error: error.message });
227
+ throw error;
228
+ }
229
+ }
230
+
231
+ function runKernelTransaction(scrumDir, name, changes, options = {}) {
232
+ return withArtifactLock(scrumDir, "kernel", () => {
233
+ const recovered = recoverPendingTransactionsUnlocked(scrumDir);
234
+ const result = writeKernelTransactionUnlocked(scrumDir, name, changes, options);
235
+ return { ...result, recovered };
236
+ });
237
+ }
238
+
239
+ function pendingTransactionStatus(scrumDir) {
240
+ try {
241
+ return { pending: pendingTransactions(scrumDir).map(({ transaction }) => ({ id: transaction.id, name: transaction.name, status: transaction.status })) };
242
+ } catch (error) {
243
+ return { pending: [], error: error.message };
244
+ }
245
+ }
246
+
247
+ module.exports = {
248
+ TRANSACTION_SCHEMA,
249
+ pendingTransactionStatus,
250
+ recoverPendingTransactions,
251
+ recoverPendingTransactionsUnlocked,
252
+ runKernelTransaction,
253
+ writeKernelTransactionUnlocked
254
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "scrumrun",
3
- "version": "2.0.0",
3
+ "version": "2.1.0",
4
4
  "description": "Evidence-driven Agile runtime and semantic project memory for AI coding agents.",
5
5
  "bin": {
6
6
  "scrumrun": "bin/scrumrun.js",
@@ -8,6 +8,9 @@ const {
8
8
  ARTIFACT_TYPES,
9
9
  AUTHORITY,
10
10
  METHOD_VERSION,
11
+ RUN_EVENT_TYPES,
12
+ RUN_EVIDENCE_KINDS,
13
+ RUN_LEDGER_VERSION,
11
14
  SCALAR_FIELDS,
12
15
  STRUCTURAL_RELATIONS,
13
16
  TRUTH_OWNERSHIP
@@ -76,6 +79,14 @@ ${scalarRows.join("\n")}
76
79
 
77
80
  Native creation uses the declared initial statuses. Migration may restore a historical non-initial status only with provenance and validation.
78
81
 
82
+ ## Run event ledger
83
+
84
+ Newly authored Runs use \`ledger: ${RUN_LEDGER_VERSION}\`. Their \`## Events\` section contains append-only JSON event blocks with stable ids in the form \`RUN-NNN-EVT-NNN\`.
85
+
86
+ Every event requires \`schema\`, \`id\`, contiguous \`sequence\`, RFC3339 \`occurred_at\`, \`timestamp_precision\`, \`actor\`, \`from\`, \`to\`, \`reason\`, and structured \`evidence\`. Event types are ${RUN_EVENT_TYPES.map((value) => `\`${value}\``).join(", ")}. Evidence kinds are ${RUN_EVIDENCE_KINDS.map((value) => `\`${value}\``).join(", ")}.
87
+
88
+ A native ledger begins with \`created → executing\`; an evidenced migration \`snapshot\` may establish one historical baseline without inventing missing transitions. Event order, transition legality, final status, updated date, and completion evidence are machine-validated. Run owns the event history; Task stores its intended scope and synchronized current status without copying Run events.
89
+
79
90
  ## Truth questions
80
91
 
81
92
  ${Object.entries(TRUTH_OWNERSHIP).map(([kind, owner]) => `- **${kind}:** ${owner.question}`).join("\n")}
@@ -5,19 +5,27 @@ Canonical project policy. Universal method invariants live in `core.md`; this fi
5
5
  ## GR-001 - Protect secrets
6
6
 
7
7
  Status: active
8
+ Enforcement: builtin:secret-boundary
9
+ Scope: all
8
10
  Rule: Never commit or print real secrets. Keep local development values in `vault.local.md` and runtime values in environment/config.
9
11
 
10
12
  ## GR-002 - Preserve owner work
11
13
 
12
14
  Status: active
15
+ Enforcement: builtin:owner-work
16
+ Scope: all
13
17
  Rule: Never overwrite unrelated or pre-existing owner changes. Canonical mutations must be scoped, lossless, validated, and recoverable.
14
18
 
15
19
  ## GR-003 - Respect read-only paths
16
20
 
17
21
  Status: active
22
+ Enforcement: builtin:read-only-path
23
+ Scope: all
18
24
  Rule: Never modify a path marked read-only by the owner or project configuration.
19
25
 
20
26
  ## GR-004 - Approval gates execution
21
27
 
22
28
  Status: active
29
+ Enforcement: builtin:approval-gate
30
+ Scope: intake, execution
23
31
  Rule: Intake remains read-only. Create/update a Task and create a Run only after explicit valid approval.
@@ -1,8 +1,9 @@
1
- # ScrumRun Map - {{PROJECT_NAME}}
1
+ # ScrumRun Project Map
2
2
 
3
3
  Generated: {{DATE}}
4
+ Status: stale
4
5
  Authority: none; rebuild from canonical artifacts and source code.
5
6
 
6
- ## Active Graph
7
+ ## Summary
7
8
 
8
- - Pending: no Features, Tasks, Sprints, Runs, Memory, or Reviews yet.
9
+ - No source fingerprint exists until `/sc knowledge map --build` creates the disposable semantic index and this bounded view.
@@ -1,4 +1,7 @@
1
1
  {
2
2
  "method": "2.0.0",
3
- "layout": "v2"
3
+ "layout": "v2",
4
+ "schemas": {
5
+ "run_ledger": 1
6
+ }
4
7
  }
@@ -1,21 +1,14 @@
1
- # ScrumRun State - {{PROJECT_NAME}}
1
+ # ScrumRun State
2
2
 
3
- Generated: {{DATE}}
4
- Authority: none; this is a disposable view.
3
+ Projection schema: 1
4
+ Generated: {{DATE}}T00:00:00.000Z
5
+ Status: stale until `init` rebuilds this projection.
6
+ Authority: none; rebuild from canonical artifacts.
5
7
 
6
8
  ## Active Work
7
9
 
8
- - Feature: none.
9
- - Task: none.
10
- - Sprint: none.
11
- - Run: none.
10
+ - No active canonical work.
12
11
 
13
12
  ## Relevant Memory
14
13
 
15
- - Decisions: none.
16
- - Knowledge: none.
17
- - Insights: none.
18
-
19
- ## Next Action
20
-
21
- - Use `/sc plan intake <request>`.
14
+ - No active canonical memory.