@letterblack/lbe-core 1.3.5 → 1.3.7

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.
@@ -1,306 +1,306 @@
1
- // src/cli/commands/init.js
2
- // Initialize LBE in a workspace:
3
- // 1. Scan project → generate workspace contract (semantics + enforcement)
4
- // 2. Show compact summary → ask once
5
- // 3. Write lbe.workspace.json
6
- // 4. Set up crypto infrastructure silently
7
-
8
- import fs from 'fs';
9
- import path from 'path';
10
- import readline from 'readline';
11
- import { generateKeyPair } from '../../core/signature.js';
12
- import { createPolicySignatureEnvelope } from '../../core/policySignature.js';
13
- import { scanWorkspace, formatSummary } from '../../core/workspaceScanner.js';
14
-
15
- // ─── Interactive prompt ───────────────────────────────────────────────────────
16
-
17
- function ask(question) {
18
- // Non-interactive (CI / pipe) — default accept
19
- if (!process.stdin.isTTY) return Promise.resolve('y');
20
- return new Promise(resolve => {
21
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
22
- rl.question(question, ans => { rl.close(); resolve(ans.trim().toLowerCase()); });
23
- });
24
- }
25
-
26
- // ─── Strict / relaxed adjustments ────────────────────────────────────────────
27
-
28
- function applyStrict(enforcement) {
29
- // Strict: move approval items to deny, add common risky patterns
30
- return {
31
- ...enforcement,
32
- deny: [...new Set([...enforcement.deny, ...enforcement.approval, '*.json', 'config/**'])],
33
- approval: [],
34
- };
35
- }
36
-
37
- function applyRelaxed(enforcement) {
38
- // Relaxed: drop approval requirement, everything not denied is allowed
39
- return { ...enforcement, approval: [] };
40
- }
41
-
42
- // ─── Crypto setup (silent — infrastructure only) ──────────────────────────────
43
-
44
- function setupCrypto(cwd) {
45
- const nowIso = new Date().toISOString();
46
- const expiresAt = new Date(Date.now() + 180 * 24 * 60 * 60 * 1000).toISOString();
47
- const defaultKeyId = 'agent:gpt-v1-2026Q1';
48
- const signerKeyId = 'policy-signer-v1-2026Q1';
49
-
50
- // All LBE infrastructure lives under .lbe/ — nothing pollutes the project root
51
- const lbeDir = path.join(cwd, '.lbe');
52
- for (const d of ['config', 'keys', 'data']) {
53
- fs.mkdirSync(path.join(lbeDir, d), { recursive: true });
54
- }
55
-
56
- // Data stores
57
- const dataFiles = {
58
- '.lbe/data/nonce.db.json': JSON.stringify({ entries: [] }, null, 2),
59
- '.lbe/data/rate-limit.db.json': JSON.stringify({ entries: [] }, null, 2),
60
- '.lbe/data/policy.state.json': JSON.stringify({ schemaVersion: '1', lastAccepted: null, updatedAt: null }, null, 2),
61
- '.lbe/data/audit.log.jsonl': '',
62
- };
63
- for (const [rel, content] of Object.entries(dataFiles)) {
64
- const p = path.join(cwd, rel);
65
- if (!fs.existsSync(p)) fs.writeFileSync(p, content);
66
- }
67
-
68
- // Keypair
69
- const keyDir = path.join(lbeDir, 'keys');
70
- const pubPath = path.join(keyDir, 'public.key');
71
- const secPath = path.join(keyDir, 'secret.key');
72
- let publicKeyB64, secretKeyB64;
73
- if (fs.existsSync(pubPath) && fs.existsSync(secPath)) {
74
- publicKeyB64 = fs.readFileSync(pubPath, 'utf8').trim();
75
- secretKeyB64 = fs.readFileSync(secPath, 'utf8').trim();
76
- } else {
77
- const kp = generateKeyPair();
78
- publicKeyB64 = kp.publicKey;
79
- secretKeyB64 = kp.secretKey;
80
- fs.writeFileSync(pubPath, publicKeyB64);
81
- fs.writeFileSync(secPath, secretKeyB64, { mode: 0o600 });
82
- }
83
-
84
- // Keys store
85
- const keysPath = path.join(lbeDir, 'config/keys.json');
86
- const keysStore = fs.existsSync(keysPath)
87
- ? JSON.parse(fs.readFileSync(keysPath, 'utf8'))
88
- : { schemaVersion: '1', defaultKeyId, trustedKeys: {} };
89
-
90
- for (const keyId of [defaultKeyId, signerKeyId]) {
91
- if (!keysStore.trustedKeys[keyId]) {
92
- keysStore.trustedKeys[keyId] = {
93
- publicKey: publicKeyB64,
94
- notBefore: nowIso,
95
- expiresAt,
96
- validFrom: nowIso,
97
- validUntil: expiresAt,
98
- deprecated: false,
99
- };
100
- }
101
- }
102
- keysStore.defaultKeyId = defaultKeyId;
103
- fs.writeFileSync(keysPath, JSON.stringify(keysStore, null, 2));
104
-
105
- // Policy
106
- const policyPath = path.join(lbeDir, 'config/policy.default.json');
107
- let policyObj;
108
- if (fs.existsSync(policyPath)) {
109
- policyObj = JSON.parse(fs.readFileSync(policyPath, 'utf8'));
110
- } else {
111
- policyObj = {
112
- default: 'DENY',
113
- version: '1.0.0',
114
- createdAt: nowIso,
115
- security: {
116
- maxClockSkewSec: 600,
117
- maxPolicyCreatedAtSkewSec: 31536000,
118
- defaultRateLimit: { windowSec: 60, maxRequests: 30 }
119
- },
120
- requesters: {
121
- 'agent:gpt': {
122
- allowAdapters: ['noop', 'shell'],
123
- allowCommands: ['RUN_SHELL'],
124
- rateLimit: { windowSec: 60, maxRequests: 30 },
125
- filesystem: { roots: [cwd], denyPatterns: ['**/.git/**', '**/secrets/**', '**/*.key'] },
126
- exec: { allowCmds: ['ls', 'node', 'python', 'echo'], denyCmds: ['rm', 'chmod', 'chown', 'curl', 'wget', 'su', 'sudo'] }
127
- }
128
- }
129
- };
130
- fs.writeFileSync(policyPath, JSON.stringify(policyObj, null, 2));
131
- }
132
-
133
- // Policy signature
134
- const sigResult = createPolicySignatureEnvelope({ policyObj, secretKeyB64, keyId: signerKeyId });
135
- if (sigResult.ok) {
136
- fs.writeFileSync(path.join(lbeDir, 'config/policy.sig.json'), JSON.stringify(sigResult.envelope, null, 2));
137
- }
138
-
139
- return { defaultKeyId, secretKeyB64, publicKeyB64 };
140
- }
141
-
142
- // ─── Agent governance files ───────────────────────────────────────────────────
143
- // Generated once by init so every AI agent auto-discovers LBE without the user
144
- // needing to explain it. Logic and internals are never mentioned — only the API.
145
-
146
- function agentContractContent() {
147
- return `# LBE Governance Contract
148
-
149
- This project has LetterBlack LBE (Local-first execution Governance) active.
150
-
151
- ## Your role as an agent
152
-
153
- Every file write, delete, and shell command must go through the LBE executor.
154
- The executor validates each action against the project policy and audits it.
155
-
156
- ## How to perform actions
157
-
158
- \`\`\`js
159
- import { createLocalExecutor } from '@letterblack/lbe-exec';
160
- const lbe = createLocalExecutor({ rootDir: process.cwd() });
161
-
162
- await lbe.writeFile('output/report.md', content);
163
- await lbe.readFile('src/config.json');
164
- await lbe.patchFile('src/index.js', patch);
165
- await lbe.deleteFile('tmp/scratch.txt');
166
- await lbe.runShell('node', ['scripts/build.js']);
167
- \`\`\`
168
-
169
- ## What you must never do
170
-
171
- - Call fs.* or child_process.* directly
172
- - Modify \`.lbe/policy.json\` directly — propose a rule via \`lbe.policy.proposeRule()\`
173
- - Attempt to bypass or disable the executor
174
-
175
- ## Proposing a policy rule
176
-
177
- \`\`\`js
178
- const proposal = lbe.policy.proposeRule({
179
- effect: 'deny', type: 'path', pattern: 'secrets/**',
180
- from: 'agent: these files should never be modified'
181
- });
182
- // Return proposal to the user — never call lbe.policy.addRule() yourself.
183
- \`\`\`
184
-
185
- ## Result shape
186
-
187
- \`{ ok: boolean, decision: 'allow' | 'deny' | 'observe', executed: boolean }\`
188
-
189
- ## Files
190
-
191
- - Policy: \`.lbe/policy.json\`
192
- - Audit: \`.lbe/audit.jsonl\`
193
- - Status: \`npx lbe-exec status\`
194
- `;
195
- }
196
-
197
- function writeAgentContract(cwd) {
198
- const lbeDir = path.join(cwd, '.lbe');
199
- fs.mkdirSync(lbeDir, { recursive: true });
200
- fs.writeFileSync(path.join(lbeDir, 'AGENT_CONTRACT.md'), agentContractContent());
201
- }
202
-
203
- // Migrate legacy root-level LBE files into .lbe/ so the workspace stays clean.
204
- function migrateLegacyRootFiles(cwd) {
205
- const lbeDir = path.join(cwd, '.lbe');
206
- fs.mkdirSync(lbeDir, { recursive: true });
207
- const migrations = [
208
- ['lbe.policy.json', '.lbe/policy.json'],
209
- ['lbe.workspace.json', '.lbe/workspace.json'],
210
- ];
211
- const removed = [];
212
- for (const [src, dest] of migrations) {
213
- const srcPath = path.join(cwd, src);
214
- const destPath = path.join(cwd, dest);
215
- if (fs.existsSync(srcPath) && !fs.existsSync(destPath)) {
216
- fs.renameSync(srcPath, destPath);
217
- removed.push(src + ' → ' + dest);
218
- } else if (fs.existsSync(srcPath)) {
219
- fs.unlinkSync(srcPath); // dest already exists — just drop the old file
220
- removed.push(src + ' (removed — .lbe/ version exists)');
221
- }
222
- }
223
- // Remove files that should never have been created in the project root
224
- const toDelete = ['CLAUDE.md', path.join('.github', 'copilot-instructions.md')];
225
- for (const rel of toDelete) {
226
- const p = path.join(cwd, rel);
227
- // Only remove if it contains the lbe-governance marker — don't touch user files
228
- if (fs.existsSync(p)) {
229
- const content = fs.readFileSync(p, 'utf8');
230
- if (content.includes('lbe-governance') || content.includes('LetterBlack LBE')) {
231
- fs.unlinkSync(p);
232
- removed.push(rel + ' (removed — LBE-generated file)');
233
- }
234
- }
235
- }
236
- return removed;
237
- }
238
-
239
- // ─── Main ─────────────────────────────────────────────────────────────────────
240
-
241
- export async function initCommand(opts = {}) {
242
- const cwd = process.cwd();
243
- const yes = opts.yes || opts.y || !process.stdin.isTTY;
244
- const lbeDir = path.join(cwd, '.lbe');
245
- fs.mkdirSync(lbeDir, { recursive: true });
246
- const outPath = path.join(lbeDir, 'workspace.json');
247
-
248
- // 1. Scan
249
- console.log('\nScanning workspace...\n');
250
- const { projectTypes, primaryType, semantics, enforcement } = scanWorkspace(cwd);
251
-
252
- // 2. Show summary
253
- console.log(formatSummary(projectTypes, semantics, enforcement));
254
- console.log('');
255
-
256
- // 3. Ask once (unless --yes or non-interactive)
257
- let finalEnforcement = enforcement;
258
- if (!yes) {
259
- const answer = await ask('Accept? [Y = accept / s = strict / r = relaxed / n = cancel] ');
260
- if (answer === 'n') {
261
- console.log('Cancelled.');
262
- return { success: false };
263
- }
264
- if (answer === 's') finalEnforcement = applyStrict(enforcement);
265
- if (answer === 'r') finalEnforcement = applyRelaxed(enforcement);
266
- }
267
-
268
- // 4. Write lbe.workspace.json
269
- const contract = {
270
- lbe: true,
271
- version: '0.4.0',
272
- state: 'local',
273
- projectTypes,
274
- primaryType,
275
- semantics,
276
- enforcement: finalEnforcement,
277
- };
278
- fs.writeFileSync(outPath, JSON.stringify(contract, null, 2));
279
- console.log('✓ Wrote .lbe/workspace.json');
280
-
281
- // 5. Crypto setup (silent)
282
- setupCrypto(cwd);
283
- const localPolicyPath = path.join(lbeDir, 'policy.json');
284
- if (!fs.existsSync(localPolicyPath)) {
285
- fs.writeFileSync(localPolicyPath, JSON.stringify({ version: 1, mode: 'observe', workspace: cwd, rules: [] }, null, 2) + '\n');
286
- }
287
- const localAuditPath = path.join(lbeDir, 'audit.jsonl');
288
- if (!fs.existsSync(localAuditPath)) fs.writeFileSync(localAuditPath, '');
289
- console.log('✓ Keys and policy ready (.lbe/)');
290
-
291
- // 6. Agent contract inside .lbe/ only — no CLAUDE.md, no .github/ changes
292
- writeAgentContract(cwd);
293
- console.log('✓ Agent contract written → .lbe/AGENT_CONTRACT.md');
294
-
295
- // 7. Migrate any legacy root files from previous LBE versions
296
- const migrated = migrateLegacyRootFiles(cwd);
297
- if (migrated.length) {
298
- console.log('\n✓ Migrated legacy files:');
299
- for (const m of migrated) console.log(' ' + m);
300
- }
301
-
302
- console.log('\nDone. All LBE state is in .lbe/');
303
- console.log('Run npx lbe-exec status to verify.\n');
304
-
305
- return { success: true, contract };
306
- }
1
+ // src/cli/commands/init.js
2
+ // Initialize LBE in a workspace:
3
+ // 1. Scan project → generate workspace contract (semantics + enforcement)
4
+ // 2. Show compact summary → ask once
5
+ // 3. Write lbe.workspace.json
6
+ // 4. Set up crypto infrastructure silently
7
+
8
+ import fs from 'fs';
9
+ import path from 'path';
10
+ import readline from 'readline';
11
+ import { generateKeyPair } from '../../core/signature.js';
12
+ import { createPolicySignatureEnvelope } from '../../core/policySignature.js';
13
+ import { scanWorkspace, formatSummary } from '../../core/workspaceScanner.js';
14
+
15
+ // ─── Interactive prompt ───────────────────────────────────────────────────────
16
+
17
+ function ask(question) {
18
+ // Non-interactive (CI / pipe) — default accept
19
+ if (!process.stdin.isTTY) return Promise.resolve('y');
20
+ return new Promise(resolve => {
21
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
22
+ rl.question(question, ans => { rl.close(); resolve(ans.trim().toLowerCase()); });
23
+ });
24
+ }
25
+
26
+ // ─── Strict / relaxed adjustments ────────────────────────────────────────────
27
+
28
+ function applyStrict(enforcement) {
29
+ // Strict: move approval items to deny, add common risky patterns
30
+ return {
31
+ ...enforcement,
32
+ deny: [...new Set([...enforcement.deny, ...enforcement.approval, '*.json', 'config/**'])],
33
+ approval: [],
34
+ };
35
+ }
36
+
37
+ function applyRelaxed(enforcement) {
38
+ // Relaxed: drop approval requirement, everything not denied is allowed
39
+ return { ...enforcement, approval: [] };
40
+ }
41
+
42
+ // ─── Crypto setup (silent — infrastructure only) ──────────────────────────────
43
+
44
+ function setupCrypto(cwd) {
45
+ const nowIso = new Date().toISOString();
46
+ const expiresAt = new Date(Date.now() + 180 * 24 * 60 * 60 * 1000).toISOString();
47
+ const defaultKeyId = 'agent:gpt-v1-2026Q1';
48
+ const signerKeyId = 'policy-signer-v1-2026Q1';
49
+
50
+ // All LBE infrastructure lives under .lbe/ — nothing pollutes the project root
51
+ const lbeDir = path.join(cwd, '.lbe');
52
+ for (const d of ['config', 'keys', 'data']) {
53
+ fs.mkdirSync(path.join(lbeDir, d), { recursive: true });
54
+ }
55
+
56
+ // Data stores
57
+ const dataFiles = {
58
+ '.lbe/data/nonce.db.json': JSON.stringify({ entries: [] }, null, 2),
59
+ '.lbe/data/rate-limit.db.json': JSON.stringify({ entries: [] }, null, 2),
60
+ '.lbe/data/policy.state.json': JSON.stringify({ schemaVersion: '1', lastAccepted: null, updatedAt: null }, null, 2),
61
+ '.lbe/data/audit.log.jsonl': '',
62
+ };
63
+ for (const [rel, content] of Object.entries(dataFiles)) {
64
+ const p = path.join(cwd, rel);
65
+ if (!fs.existsSync(p)) fs.writeFileSync(p, content);
66
+ }
67
+
68
+ // Keypair
69
+ const keyDir = path.join(lbeDir, 'keys');
70
+ const pubPath = path.join(keyDir, 'public.key');
71
+ const secPath = path.join(keyDir, 'secret.key');
72
+ let publicKeyB64, secretKeyB64;
73
+ if (fs.existsSync(pubPath) && fs.existsSync(secPath)) {
74
+ publicKeyB64 = fs.readFileSync(pubPath, 'utf8').trim();
75
+ secretKeyB64 = fs.readFileSync(secPath, 'utf8').trim();
76
+ } else {
77
+ const kp = generateKeyPair();
78
+ publicKeyB64 = kp.publicKey;
79
+ secretKeyB64 = kp.secretKey;
80
+ fs.writeFileSync(pubPath, publicKeyB64);
81
+ fs.writeFileSync(secPath, secretKeyB64, { mode: 0o600 });
82
+ }
83
+
84
+ // Keys store
85
+ const keysPath = path.join(lbeDir, 'config/keys.json');
86
+ const keysStore = fs.existsSync(keysPath)
87
+ ? JSON.parse(fs.readFileSync(keysPath, 'utf8'))
88
+ : { schemaVersion: '1', defaultKeyId, trustedKeys: {} };
89
+
90
+ for (const keyId of [defaultKeyId, signerKeyId]) {
91
+ if (!keysStore.trustedKeys[keyId]) {
92
+ keysStore.trustedKeys[keyId] = {
93
+ publicKey: publicKeyB64,
94
+ notBefore: nowIso,
95
+ expiresAt,
96
+ validFrom: nowIso,
97
+ validUntil: expiresAt,
98
+ deprecated: false,
99
+ };
100
+ }
101
+ }
102
+ keysStore.defaultKeyId = defaultKeyId;
103
+ fs.writeFileSync(keysPath, JSON.stringify(keysStore, null, 2));
104
+
105
+ // Policy
106
+ const policyPath = path.join(lbeDir, 'config/policy.default.json');
107
+ let policyObj;
108
+ if (fs.existsSync(policyPath)) {
109
+ policyObj = JSON.parse(fs.readFileSync(policyPath, 'utf8'));
110
+ } else {
111
+ policyObj = {
112
+ default: 'DENY',
113
+ version: '1.0.0',
114
+ createdAt: nowIso,
115
+ security: {
116
+ maxClockSkewSec: 600,
117
+ maxPolicyCreatedAtSkewSec: 31536000,
118
+ defaultRateLimit: { windowSec: 60, maxRequests: 30 }
119
+ },
120
+ requesters: {
121
+ 'agent:gpt': {
122
+ allowAdapters: ['noop', 'shell'],
123
+ allowCommands: ['RUN_SHELL'],
124
+ rateLimit: { windowSec: 60, maxRequests: 30 },
125
+ filesystem: { roots: [cwd], denyPatterns: ['**/.git/**', '**/secrets/**', '**/*.key'] },
126
+ exec: { allowCmds: ['ls', 'node', 'python', 'echo'], denyCmds: ['rm', 'chmod', 'chown', 'curl', 'wget', 'su', 'sudo'] }
127
+ }
128
+ }
129
+ };
130
+ fs.writeFileSync(policyPath, JSON.stringify(policyObj, null, 2));
131
+ }
132
+
133
+ // Policy signature
134
+ const sigResult = createPolicySignatureEnvelope({ policyObj, secretKeyB64, keyId: signerKeyId });
135
+ if (sigResult.ok) {
136
+ fs.writeFileSync(path.join(lbeDir, 'config/policy.sig.json'), JSON.stringify(sigResult.envelope, null, 2));
137
+ }
138
+
139
+ return { defaultKeyId, secretKeyB64, publicKeyB64 };
140
+ }
141
+
142
+ // ─── Agent governance files ───────────────────────────────────────────────────
143
+ // Generated once by init so every AI agent auto-discovers LBE without the user
144
+ // needing to explain it. Logic and internals are never mentioned — only the API.
145
+
146
+ function agentContractContent() {
147
+ return `# LBE Governance Contract
148
+
149
+ This project has LetterBlack LBE (Local-first execution Governance) active.
150
+
151
+ ## Your role as an agent
152
+
153
+ Every file write, delete, and shell command must go through the LBE executor.
154
+ The executor validates each action against the project policy and audits it.
155
+
156
+ ## How to perform actions
157
+
158
+ \`\`\`js
159
+ import { createLocalExecutor } from '@letterblack/lbe-exec';
160
+ const lbe = createLocalExecutor({ rootDir: process.cwd() });
161
+
162
+ await lbe.writeFile('output/report.md', content);
163
+ await lbe.readFile('src/config.json');
164
+ await lbe.patchFile('src/index.js', patch);
165
+ await lbe.deleteFile('tmp/scratch.txt');
166
+ await lbe.runShell('node', ['scripts/build.js']);
167
+ \`\`\`
168
+
169
+ ## What you must never do
170
+
171
+ - Call fs.* or child_process.* directly
172
+ - Modify \`.lbe/policy.json\` directly — propose a rule via \`lbe.policy.proposeRule()\`
173
+ - Attempt to bypass or disable the executor
174
+
175
+ ## Proposing a policy rule
176
+
177
+ \`\`\`js
178
+ const proposal = lbe.policy.proposeRule({
179
+ effect: 'deny', type: 'path', pattern: 'secrets/**',
180
+ from: 'agent: these files should never be modified'
181
+ });
182
+ // Return proposal to the user — never call lbe.policy.addRule() yourself.
183
+ \`\`\`
184
+
185
+ ## Result shape
186
+
187
+ \`{ ok: boolean, decision: 'allow' | 'deny' | 'observe', executed: boolean }\`
188
+
189
+ ## Files
190
+
191
+ - Policy: \`.lbe/policy.json\`
192
+ - Audit: \`.lbe/audit.jsonl\`
193
+ - Status: \`npx lbe-exec status\`
194
+ `;
195
+ }
196
+
197
+ function writeAgentContract(cwd) {
198
+ const lbeDir = path.join(cwd, '.lbe');
199
+ fs.mkdirSync(lbeDir, { recursive: true });
200
+ fs.writeFileSync(path.join(lbeDir, 'AGENT_CONTRACT.md'), agentContractContent());
201
+ }
202
+
203
+ // Migrate legacy root-level LBE files into .lbe/ so the workspace stays clean.
204
+ function migrateLegacyRootFiles(cwd) {
205
+ const lbeDir = path.join(cwd, '.lbe');
206
+ fs.mkdirSync(lbeDir, { recursive: true });
207
+ const migrations = [
208
+ ['lbe.policy.json', '.lbe/policy.json'],
209
+ ['lbe.workspace.json', '.lbe/workspace.json'],
210
+ ];
211
+ const removed = [];
212
+ for (const [src, dest] of migrations) {
213
+ const srcPath = path.join(cwd, src);
214
+ const destPath = path.join(cwd, dest);
215
+ if (fs.existsSync(srcPath) && !fs.existsSync(destPath)) {
216
+ fs.renameSync(srcPath, destPath);
217
+ removed.push(src + ' → ' + dest);
218
+ } else if (fs.existsSync(srcPath)) {
219
+ fs.unlinkSync(srcPath); // dest already exists — just drop the old file
220
+ removed.push(src + ' (removed — .lbe/ version exists)');
221
+ }
222
+ }
223
+ // Remove files that should never have been created in the project root
224
+ const toDelete = ['CLAUDE.md', path.join('.github', 'copilot-instructions.md')];
225
+ for (const rel of toDelete) {
226
+ const p = path.join(cwd, rel);
227
+ // Only remove if it contains the lbe-governance marker — don't touch user files
228
+ if (fs.existsSync(p)) {
229
+ const content = fs.readFileSync(p, 'utf8');
230
+ if (content.includes('lbe-governance') || content.includes('LetterBlack LBE')) {
231
+ fs.unlinkSync(p);
232
+ removed.push(rel + ' (removed — LBE-generated file)');
233
+ }
234
+ }
235
+ }
236
+ return removed;
237
+ }
238
+
239
+ // ─── Main ─────────────────────────────────────────────────────────────────────
240
+
241
+ export async function initCommand(opts = {}) {
242
+ const cwd = process.cwd();
243
+ const yes = opts.yes || opts.y || !process.stdin.isTTY;
244
+ const lbeDir = path.join(cwd, '.lbe');
245
+ fs.mkdirSync(lbeDir, { recursive: true });
246
+ const outPath = path.join(lbeDir, 'workspace.json');
247
+
248
+ // 1. Scan
249
+ console.log('\nScanning workspace...\n');
250
+ const { projectTypes, primaryType, semantics, enforcement } = scanWorkspace(cwd);
251
+
252
+ // 2. Show summary
253
+ console.log(formatSummary(projectTypes, semantics, enforcement));
254
+ console.log('');
255
+
256
+ // 3. Ask once (unless --yes or non-interactive)
257
+ let finalEnforcement = enforcement;
258
+ if (!yes) {
259
+ const answer = await ask('Accept? [Y = accept / s = strict / r = relaxed / n = cancel] ');
260
+ if (answer === 'n') {
261
+ console.log('Cancelled.');
262
+ return { success: false };
263
+ }
264
+ if (answer === 's') finalEnforcement = applyStrict(enforcement);
265
+ if (answer === 'r') finalEnforcement = applyRelaxed(enforcement);
266
+ }
267
+
268
+ // 4. Write lbe.workspace.json
269
+ const contract = {
270
+ lbe: true,
271
+ version: '0.4.0',
272
+ state: 'local',
273
+ projectTypes,
274
+ primaryType,
275
+ semantics,
276
+ enforcement: finalEnforcement,
277
+ };
278
+ fs.writeFileSync(outPath, JSON.stringify(contract, null, 2));
279
+ console.log('✓ Wrote .lbe/workspace.json');
280
+
281
+ // 5. Crypto setup (silent)
282
+ setupCrypto(cwd);
283
+ const localPolicyPath = path.join(lbeDir, 'policy.json');
284
+ if (!fs.existsSync(localPolicyPath)) {
285
+ fs.writeFileSync(localPolicyPath, JSON.stringify({ version: 1, mode: 'observe', workspace: cwd, rules: [] }, null, 2) + '\n');
286
+ }
287
+ const localAuditPath = path.join(lbeDir, 'audit.jsonl');
288
+ if (!fs.existsSync(localAuditPath)) fs.writeFileSync(localAuditPath, '');
289
+ console.log('✓ Keys and policy ready (.lbe/)');
290
+
291
+ // 6. Agent contract inside .lbe/ only — no CLAUDE.md, no .github/ changes
292
+ writeAgentContract(cwd);
293
+ console.log('✓ Agent contract written → .lbe/AGENT_CONTRACT.md');
294
+
295
+ // 7. Migrate any legacy root files from previous LBE versions
296
+ const migrated = migrateLegacyRootFiles(cwd);
297
+ if (migrated.length) {
298
+ console.log('\n✓ Migrated legacy files:');
299
+ for (const m of migrated) console.log(' ' + m);
300
+ }
301
+
302
+ console.log('\nDone. All LBE state is in .lbe/');
303
+ console.log('Run npx lbe-exec status to verify.\n');
304
+
305
+ return { success: true, contract };
306
+ }
@@ -1,28 +1,8 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
- import os from 'node:os';
4
3
  import { resolveWorkspaceState } from '../../state/index.js';
5
4
  import { loadLatestProof } from '../../state/proofRunner.js';
6
5
 
7
- // Fields that must NEVER appear in public proof output
8
- const REDACT_FIELDS = new Set([
9
- 'files_changed', 'failures', 'workspace', 'stateDir',
10
- 'target_id', 'intent_id',
11
- ]);
12
-
13
- function redactPath(p) {
14
- if (!p || typeof p !== 'string') return p;
15
- // Replace home dir with ~, then remove machine-specific prefix
16
- const home = os.homedir().replace(/\\/g, '/');
17
- const pNorm = p.replace(/\\/g, '/');
18
- const relative = pNorm.startsWith(home + '/')
19
- ? '~/' + pNorm.slice(home.length + 1)
20
- : pNorm;
21
- // Only keep the last two path segments
22
- const parts = relative.replace(/\\/g, '/').split('/');
23
- return parts.length > 2 ? '…/' + parts.slice(-2).join('/') : relative;
24
- }
25
-
26
6
  function buildPublicProof(proof, targets) {
27
7
  const lastTarget = Array.isArray(targets) && targets.length > 0
28
8
  ? targets[targets.length - 1]
@@ -61,7 +41,7 @@ function buildPublicProof(proof, targets) {
61
41
  */
62
42
  export async function proofCommand(opts) {
63
43
  const workspaceRoot = path.resolve(opts.root || process.cwd());
64
- const { stateDir, workspaceId, paths } = resolveWorkspaceState(workspaceRoot);
44
+ const { stateDir } = resolveWorkspaceState(workspaceRoot);
65
45
 
66
46
  const proof = loadLatestProof(stateDir);
67
47
  const isPublic = opts.public === true || opts.public === 'true';
@@ -84,7 +64,7 @@ export async function proofCommand(opts) {
84
64
  if (fs.existsSync(targetPath)) {
85
65
  const raw = fs.readFileSync(targetPath, 'utf8').trim();
86
66
  targets = raw ? raw.split('\n').reduce((acc, l) => {
87
- try { acc.push(JSON.parse(l)); } catch (_) {}
67
+ try { acc.push(JSON.parse(l)); } catch (_) { /* ignore */ }
88
68
  return acc;
89
69
  }, []) : [];
90
70
  }