@sbains2/lifeos 0.1.3 → 0.2.1

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/src/remedy.js ADDED
@@ -0,0 +1,288 @@
1
+ /**
2
+ * `lifeos doctor --fix` — deterministic remediation for an unhealthy scaffold.
3
+ *
4
+ * Trust posture:
5
+ * - NEVER touches user secrets (tokens, OAuth credentials)
6
+ * - NEVER edits the user's shell rc (~/.zshrc, ~/.bashrc)
7
+ * - NEVER overwrites existing files without backup
8
+ * - ONLY applies fixes for checks where the right action is unambiguous and
9
+ * doesn't require user input
10
+ *
11
+ * What it can fix automatically:
12
+ * - Missing quadrant folders → mkdir -p (with placeholder README)
13
+ * - Missing council files → copy from bundled templates
14
+ * - Missing writing_style.md (when path is set in config) → create stub
15
+ * - Missing .env.example for required auth env vars → generate with help-URL
16
+ * comments per env var. User sources it as .env.local after filling in
17
+ * values.
18
+ *
19
+ * What it CANNOT fix automatically (must be user-driven):
20
+ * - Missing env var values (we'd need the secret)
21
+ * - Schema version mismatch (needs `lifeos migrate` — not yet implemented)
22
+ * - Empty brain index (needs `lifeos brain` — not yet implemented)
23
+ * - Missing MCP runtimes (npx / docker / uvx — user must install)
24
+ *
25
+ * Each fix returns { id, applied: boolean, action: string, message: string }.
26
+ * Caller decides how to render.
27
+ */
28
+
29
+ import { existsSync, mkdirSync, writeFileSync, copyFileSync, readFileSync } from 'node:fs';
30
+ import { join, dirname, isAbsolute } from 'node:path';
31
+ import { fileURLToPath } from 'node:url';
32
+ import { loadRegistry } from './templates-loader.js';
33
+
34
+ const __dirname = dirname(fileURLToPath(import.meta.url));
35
+ const TEMPLATES_COUNCIL = join(__dirname, '..', 'templates', 'council');
36
+
37
+ /**
38
+ * Apply all deterministic fixes to a scaffold. Reads the same lifeos.config.json
39
+ * doctor reads. Returns { applied: [], skipped: [], summary }.
40
+ */
41
+ export function applyDoctorFixes(targetDir, options = {}) {
42
+ const { allowWritingStyleStub = true, allowEnvExample = true } = options;
43
+
44
+ const configPath = join(targetDir, 'lifeos.config.json');
45
+ if (!existsSync(configPath)) {
46
+ return {
47
+ applied: [],
48
+ skipped: [{ id: 'config', reason: 'lifeos.config.json not found — nothing to remediate' }],
49
+ summary: { applied: 0, skipped: 1 },
50
+ };
51
+ }
52
+ let config;
53
+ try {
54
+ config = JSON.parse(readFileSync(configPath, 'utf8'));
55
+ } catch (err) {
56
+ return {
57
+ applied: [],
58
+ skipped: [{ id: 'config', reason: `JSON parse failed: ${err.message} — fix manually first` }],
59
+ summary: { applied: 0, skipped: 1 },
60
+ };
61
+ }
62
+
63
+ const applied = [];
64
+ const skipped = [];
65
+
66
+ // Fix 1: missing quadrant folders
67
+ for (const q of config.quadrants ?? []) {
68
+ if (!q.active) continue;
69
+ const fullPath = isAbsolute(q.path) ? q.path : join(targetDir, q.path);
70
+ if (existsSync(fullPath)) continue;
71
+ try {
72
+ mkdirSync(fullPath, { recursive: true });
73
+ const readme = join(fullPath, 'README.md');
74
+ if (!existsSync(readme)) {
75
+ writeFileSync(readme, quadrantReadme(q), 'utf8');
76
+ }
77
+ applied.push({
78
+ id: `quadrant_folder:${q.id}`,
79
+ action: `mkdir`,
80
+ message: `Created ${q.path}/ + placeholder README`,
81
+ });
82
+ } catch (err) {
83
+ skipped.push({ id: `quadrant_folder:${q.id}`, reason: `mkdir failed: ${err.message}` });
84
+ }
85
+ }
86
+
87
+ // Fix 2: missing council files
88
+ const councilDir = join(targetDir, '.claude', 'agents', 'council');
89
+ for (const member of config.council ?? []) {
90
+ if (!member.system_prompt_path) continue;
91
+ const filename = member.system_prompt_path.split('/').pop();
92
+ const installedPath = join(councilDir, filename);
93
+ if (existsSync(installedPath)) continue;
94
+ const templatePath = join(TEMPLATES_COUNCIL, filename);
95
+ if (!existsSync(templatePath)) {
96
+ skipped.push({
97
+ id: `council_file:${member.id}`,
98
+ reason: `bundled template missing for ${filename} — file may be custom; not auto-fixable`,
99
+ });
100
+ continue;
101
+ }
102
+ try {
103
+ mkdirSync(councilDir, { recursive: true });
104
+ copyFileSync(templatePath, installedPath);
105
+ applied.push({
106
+ id: `council_file:${member.id}`,
107
+ action: 'copy',
108
+ message: `Copied ${filename} from bundled templates`,
109
+ });
110
+ } catch (err) {
111
+ skipped.push({ id: `council_file:${member.id}`, reason: `copy failed: ${err.message}` });
112
+ }
113
+ }
114
+
115
+ // Fix 3: writing_style.md stub if path is set + file missing
116
+ if (allowWritingStyleStub && config.writing_style_path) {
117
+ const stylePath = isAbsolute(config.writing_style_path)
118
+ ? config.writing_style_path
119
+ : join(targetDir, config.writing_style_path);
120
+ if (!existsSync(stylePath)) {
121
+ try {
122
+ mkdirSync(dirname(stylePath), { recursive: true });
123
+ writeFileSync(stylePath, writingStyleStub(), 'utf8');
124
+ applied.push({
125
+ id: 'writing_style',
126
+ action: 'stub',
127
+ message: `Wrote stub at ${config.writing_style_path} — replace with a real sample of your writing`,
128
+ });
129
+ } catch (err) {
130
+ skipped.push({ id: 'writing_style', reason: `write failed: ${err.message}` });
131
+ }
132
+ }
133
+ }
134
+
135
+ // Fix 4: .env.example for required env vars
136
+ if (allowEnvExample) {
137
+ let registry = null;
138
+ try {
139
+ registry = loadRegistry();
140
+ } catch {
141
+ /* skip env example if registry unavailable */
142
+ }
143
+ if (registry) {
144
+ const envEntries = collectEnvEntries(config, registry);
145
+ if (envEntries.length > 0) {
146
+ const envExamplePath = join(targetDir, '.env.example');
147
+ const wasExisting = existsSync(envExamplePath);
148
+ try {
149
+ // Don't overwrite if user already customized — just notify
150
+ if (wasExisting) {
151
+ skipped.push({
152
+ id: 'env_example',
153
+ reason: `.env.example already exists — not overwriting (review and merge manually if needed)`,
154
+ });
155
+ } else {
156
+ writeFileSync(envExamplePath, envExampleContent(envEntries), 'utf8');
157
+ applied.push({
158
+ id: 'env_example',
159
+ action: 'generate',
160
+ message: `Wrote .env.example with ${envEntries.length} env var stub(s) + help URLs. Copy to .env.local, fill in values, then \`source .env.local\` before launching Claude.`,
161
+ });
162
+ }
163
+ } catch (err) {
164
+ skipped.push({ id: 'env_example', reason: `write failed: ${err.message}` });
165
+ }
166
+ }
167
+ }
168
+ }
169
+
170
+ return {
171
+ applied,
172
+ skipped,
173
+ summary: { applied: applied.length, skipped: skipped.length },
174
+ };
175
+ }
176
+
177
+ /**
178
+ * Collect env var entries needed by wired MCPs.
179
+ * Returns [{ env_var, mcp_id, mcp_name, help_url, scope_hint }].
180
+ */
181
+ function collectEnvEntries(config, registry) {
182
+ const byId = new Map(registry.servers.map((s) => [s.id, s]));
183
+ const entries = [];
184
+ const seen = new Set();
185
+ for (const m of config.mcp_servers ?? []) {
186
+ const entry = byId.get(m.id);
187
+ if (!entry?.auth?.env_var) continue;
188
+ if (seen.has(entry.auth.env_var)) continue;
189
+ seen.add(entry.auth.env_var);
190
+ entries.push({
191
+ env_var: entry.auth.env_var,
192
+ mcp_id: entry.id,
193
+ mcp_name: entry.name,
194
+ help_url: entry.auth.help_url,
195
+ scope_hint: entry.auth.scope_hint,
196
+ });
197
+ }
198
+ return entries;
199
+ }
200
+
201
+ function envExampleContent(entries) {
202
+ const lines = [
203
+ '# LifeOS — wired MCP environment variables',
204
+ '#',
205
+ '# Generated by `lifeos doctor --fix`. To use:',
206
+ '# 1. Copy this file to .env.local in the same directory',
207
+ '# 2. Fill in each value from the help URLs below',
208
+ '# 3. Source it before launching Claude Code:',
209
+ '# source .env.local',
210
+ '# or add a permanent `set -a; source .env.local; set +a` to your shell rc.',
211
+ '#',
212
+ '# Trust note: .env.local should be gitignored (LifeOS scaffold .gitignore covers this).',
213
+ '# LifeOS itself never reads any value in this file — it\'s yours, in your shell.',
214
+ '',
215
+ ];
216
+
217
+ for (const e of entries) {
218
+ lines.push(`# ${e.mcp_name}`);
219
+ if (e.help_url) lines.push(`# Get one: ${e.help_url}`);
220
+ if (e.scope_hint) {
221
+ const wrapped = wrapText(`# Scope: ${e.scope_hint}`, 100);
222
+ lines.push(...wrapped);
223
+ }
224
+ lines.push(`export ${e.env_var}=`);
225
+ lines.push('');
226
+ }
227
+
228
+ return lines.join('\n');
229
+ }
230
+
231
+ function wrapText(text, maxWidth) {
232
+ const lines = [];
233
+ const prefix = text.startsWith('#') ? '# ' : '';
234
+ const content = text.startsWith('#') ? text.slice(2) : text;
235
+ const words = content.split(/\s+/);
236
+ let current = '';
237
+ for (const word of words) {
238
+ if (current.length + word.length + 1 > maxWidth - prefix.length) {
239
+ if (current) lines.push(prefix + current);
240
+ current = word;
241
+ } else {
242
+ current = current ? `${current} ${word}` : word;
243
+ }
244
+ }
245
+ if (current) lines.push(prefix + current);
246
+ return lines;
247
+ }
248
+
249
+ function quadrantReadme(q) {
250
+ return `# ${q.name}
251
+
252
+ ${q.description ?? ''}
253
+
254
+ This folder is the home of your **${q.id}** quadrant. The LifeOS council members assigned to it will read files here as context when convened.
255
+
256
+ ## Council members assigned
257
+
258
+ ${(q.council_member_ids ?? []).map((id) => `- \`${id}\``).join('\n') || '_none_'}
259
+
260
+ ## MCP servers wired
261
+
262
+ ${(q.mcp_server_ids ?? []).map((id) => `- \`${id}\``).join('\n') || '_none_'}
263
+
264
+ ## Priority
265
+
266
+ \`${q.priority}\` — change in \`lifeos.config.json\` to adjust how much airtime this quadrant gets in cross-quadrant convenings.
267
+ `;
268
+ }
269
+
270
+ function writingStyleStub() {
271
+ return `# Writing style
272
+
273
+ > This file anchors your voice for council members that produce written output (Writing Critic, Editor, etc.).
274
+ > Replace this placeholder with a real sample of your writing — an email, an essay paragraph, a Slack message you're proud of.
275
+ > The council reads this verbatim and tries to match the register. Be specific.
276
+
277
+ ## Style notes
278
+
279
+ - _Tone:_ [e.g., formal-analytical, conversational, direct, hedged]
280
+ - _Sentence length preference:_ [e.g., short and punchy / long and layered]
281
+ - _Vocabulary preferences:_ [e.g., academic, plain-spoken, jargon-heavy]
282
+ - _Avoid:_ [e.g., overly casual contractions, filler phrases, marketing-speak]
283
+
284
+ ## Sample (replace this entire section with your own)
285
+
286
+ [Paste 200-500 words of your own writing here. Anything you wrote and stand behind.]
287
+ `;
288
+ }
@@ -91,13 +91,44 @@ Roster of council voices. Each member is defined once globally and referenced by
91
91
 
92
92
  ### `mcp_servers`
93
93
 
94
- Wired MCP servers — id-only references, with optional per-server overrides. The CLI's onboarding wizard suggests these from `templates/mcps/registry.json` based on the user's app stack.
94
+ Wired MCP servers — id-only references in the user's `lifeos.config.json`, with optional per-server overrides. The CLI's onboarding wizard suggests these from `templates/mcps/registry.json` based on the user's app stack.
95
+
96
+ In the user's config:
95
97
 
96
98
  | Field | Type | Required | Notes |
97
99
  |---|---|---|---|
98
100
  | `id` | string | yes | Slug; must match a registry entry |
99
101
  | `config_overrides` | object | no | Per-server config (e.g., scopes, allowed folders, send_permission) |
100
102
 
103
+ In the registry (`templates/mcps/registry.json`), each entry carries the metadata needed to install + auth:
104
+
105
+ | Field | Type | Required | Notes |
106
+ |---|---|---|---|
107
+ | `id` | string | yes | Slug |
108
+ | `name` | string | yes | Display name |
109
+ | `category` | string | yes | Grouping (productivity, communication, engineering, etc.) |
110
+ | `description` | string | yes | One-sentence description |
111
+ | `status` | enum | yes | `reference` / `vendor-published` / `community` / `beta-unverified` / `use-at-your-own-risk` |
112
+ | `repo_url` | string | no | Verified GitHub URL (null if beta-unverified) |
113
+ | `runtime` | enum | yes | `npx` / `uvx` / `pip-install` / `git+pip` / `docker` / `remote` / `manual` |
114
+ | `install_command` | string[] | no | Argv-style command to install/run the MCP. `null` if `manual` runtime |
115
+ | `auth.method` | enum | yes | `oauth` / `api_key` / `none` |
116
+ | `auth.env_var` | string | no | Name of the env var holding the credential |
117
+ | `auth.help_url` | string | no | Where the user obtains credentials (e.g., `https://github.com/settings/tokens`) |
118
+ | `auth.scope_hint` | string | no | Recommended scopes/permissions |
119
+ | `risk_advisory` | string | no | Free-text warning surfaced for `use-at-your-own-risk` entries |
120
+ | `useful_for_personas` | string[] | yes | Which persona templates suggest this MCP |
121
+ | `last_verified` | string | yes | YYYY-MM-DD when registry entry was last verified against upstream |
122
+ | `install_hint` | string | yes | Free-text fallback / additional context for the install path |
123
+
124
+ #### Status enum reference
125
+
126
+ - `reference` — Maintained by the MCP steering group. Most stable.
127
+ - `vendor-published` — Published by the vendor whose product it integrates with (e.g. Stripe, Notion, Microsoft for Playwright). Generally vendor-supported.
128
+ - `community` — Community-built, actively maintained as of `last_verified`. Multiple options often exist.
129
+ - `beta-unverified` — We have not researched a current canonical implementation. Install path needs your own due diligence.
130
+ - `use-at-your-own-risk` — Functions but carries significant risk. Currently only used for MCPs that violate the upstream service's ToS or carry account-ban risk (e.g., LinkedIn unofficial-API MCPs). Always read `risk_advisory` before installing.
131
+
101
132
  Server install details (package, runtime, auth method) live in the registry, not the config file. This keeps configs small and lets registry updates propagate without users regenerating their files.
102
133
 
103
134
  ### `agent_runtime`