Skip to content

⛰️ LifeOS — The AI-powered Life Operating System that helps you hill climb to wherever you're going.

PAI v4.0.2 — 11 bug fixes, 0 new features

Daniel Miessler80599c75f3b8
diff --git a/Releases/v4.0.1/.claude/PAI-Install/engine/actions.ts b/Releases/v4.0.1/.claude/PAI-Install/engine/actions.ts
index c142d326..d7d9cde5 100644
--- a/Releases/v4.0.1/.claude/PAI-Install/engine/actions.ts
+++ b/Releases/v4.0.1/.claude/PAI-Install/engine/actions.ts
@@ -584,23 +584,25 @@ export async function runConfiguration(
}
}
- // Set up zsh alias
+ // Set up shell alias (detect bash/zsh/fish)
await emit({ event: "progress", step: "configuration", percent: 80, detail: "Setting up shell alias..." });
- const zshrcPath = join(homedir(), ".zshrc");
- const aliasLine = `alias pai='bun ${join(paiDir, "skills", "PAI", "Tools", "pai.ts")}'`;
+ const userShell = process.env.SHELL || "/bin/zsh";
+ const rcFile = userShell.includes("bash") ? ".bashrc" : userShell.includes("fish") ? ".config/fish/config.fish" : ".zshrc";
+ const rcPath = join(homedir(), rcFile);
+ const aliasLine = `alias pai='bun ${join(paiDir, "PAI", "Tools", "pai.ts")}'`;
const marker = "# PAI alias";
- if (existsSync(zshrcPath)) {
- let content = readFileSync(zshrcPath, "utf-8");
+ if (existsSync(rcPath)) {
+ let content = readFileSync(rcPath, "utf-8");
// Remove any existing pai alias (old CORE or PAI paths, any marker variant)
content = content.replace(/^#\s*(?:PAI|CORE)\s*alias.*\n.*alias pai=.*\n?/gm, "");
content = content.replace(/^alias pai=.*\n?/gm, "");
// Add fresh alias
content = content.trimEnd() + `\n\n${marker}\n${aliasLine}\n`;
- writeFileSync(zshrcPath, content);
+ writeFileSync(rcPath, content);
} else {
- writeFileSync(zshrcPath, `${marker}\n${aliasLine}\n`);
+ writeFileSync(rcPath, `${marker}\n${aliasLine}\n`);
}
// Fix permissions
diff --git a/Releases/v4.0.1/.claude/PAI-Install/install.sh b/Releases/v4.0.1/.claude/PAI-Install/install.sh
index 0b08b8d8..de1dd34f 100755
--- a/Releases/v4.0.1/.claude/PAI-Install/install.sh
+++ b/Releases/v4.0.1/.claude/PAI-Install/install.sh
@@ -153,4 +153,13 @@ fi
info "Launching installer..."
echo ""
-exec bun run "$INSTALLER_DIR/main.ts" --mode gui
+
+# Auto-detect headless/SSH environments and fall back to CLI mode
+if [ -z "$DISPLAY" ] && [ -z "$WAYLAND_DISPLAY" ] && [ "$(uname)" != "Darwin" ]; then
+ INSTALL_MODE="cli"
+ info "Headless environment detected — using CLI installer."
+else
+ INSTALL_MODE="gui"
+fi
+
+exec bun run "$INSTALLER_DIR/main.ts" --mode "$INSTALL_MODE"
diff --git a/Releases/v4.0.1/.claude/hooks/LoadContext.hook.ts b/Releases/v4.0.1/.claude/hooks/LoadContext.hook.ts
index 3e4ab3c8..b6a07a65 100755
--- a/Releases/v4.0.1/.claude/hooks/LoadContext.hook.ts
+++ b/Releases/v4.0.1/.claude/hooks/LoadContext.hook.ts
@@ -529,7 +529,7 @@ Dynamic context loaded. Core identity, rules, and format are in CLAUDE.md.
process.exit(0);
} catch (error) {
console.error('❌ Error in LoadContext hook:', error);
- process.exit(1);
+ process.exit(0); // Non-fatal — don't block session startup
}
}
diff --git a/Releases/v4.0.1/.claude/hooks/RatingCapture.hook.ts b/Releases/v4.0.1/.claude/hooks/RatingCapture.hook.ts
index fbfc92c6..38c7a60b 100755
--- a/Releases/v4.0.1/.claude/hooks/RatingCapture.hook.ts
+++ b/Releases/v4.0.1/.claude/hooks/RatingCapture.hook.ts
@@ -21,7 +21,6 @@
* SIDE EFFECTS:
* - Writes to: MEMORY/LEARNING/SIGNALS/ratings.jsonl
* - Writes to: MEMORY/LEARNING/<category>/<YYYY-MM>/*.md (for low ratings)
- * - Triggers: TrendingAnalysis.ts update (fire-and-forget)
* - API call: Haiku inference for implicit sentiment (fast/cheap)
*
* PERFORMANCE:
@@ -53,7 +52,7 @@ interface RatingEntry {
rating: number;
session_id: string;
comment?: string;
- source?: 'implicit';
+ source?: 'implicit' | 'explicit';
sentiment_summary?: string;
confidence?: number;
response_preview?: string; // Truncated last response that was rated (from cache)
@@ -64,7 +63,6 @@ interface RatingEntry {
const BASE_DIR = process.env.PAI_DIR || join(process.env.HOME!, '.claude');
const SIGNALS_DIR = join(BASE_DIR, 'MEMORY', 'LEARNING', 'SIGNALS');
const RATINGS_FILE = join(SIGNALS_DIR, 'ratings.jsonl');
-const TRENDING_SCRIPT = join(BASE_DIR, 'tools', 'TrendingAnalysis.ts');
const LAST_RESPONSE_CACHE = join(BASE_DIR, 'MEMORY', 'STATE', 'last-response.txt');
const MIN_PROMPT_LENGTH = 3;
const MIN_CONFIDENCE = 0.5;
@@ -306,15 +304,6 @@ function writeRating(entry: RatingEntry): void {
console.error(`[RatingCapture] Wrote ${source} rating ${entry.rating} to ${RATINGS_FILE}`);
}
-// ── Shared: Trigger Trending Analysis ──
-
-function triggerTrending(): void {
- if (existsSync(TRENDING_SCRIPT)) {
- Bun.spawn(['bun', TRENDING_SCRIPT, '--force'], { stdout: 'ignore', stderr: 'ignore' });
- console.error('[RatingCapture] Triggered TrendingAnalysis update');
- }
-}
-
// ── Shared: Capture Low Rating Learning ──
function captureLowRatingLearning(
@@ -395,12 +384,13 @@ async function main() {
timestamp: getISOTimestamp(),
rating: explicitResult.rating,
session_id: data.session_id,
+ source: 'explicit' as const,
};
if (explicitResult.comment) entry.comment = explicitResult.comment;
if (cachedResponse) entry.response_preview = cachedResponse.slice(0, 500);
writeRating(entry);
- triggerTrending();
+
if (explicitResult.rating < 5) {
// Read cached last response (written by LastResponseCache.hook.ts on previous Stop event)
@@ -475,7 +465,7 @@ async function main() {
confidence: 0.95,
...(cachedResponse ? { response_preview: cachedResponse.slice(0, 500) } : {}),
});
- triggerTrending();
+
process.exit(0);
}
}
@@ -516,7 +506,7 @@ async function main() {
if (implicitCachedResponse) entry.response_preview = implicitCachedResponse.slice(0, 500);
writeRating(entry);
- triggerTrending();
+
if (sentiment.rating < 5) {
captureLowRatingLearning(
@@ -550,7 +540,7 @@ async function main() {
sentiment_summary: `INFERENCE_FAILED: "${failedPromptPreview}"`,
confidence: 0,
});
- triggerTrending();
+
}
process.exit(0);
diff --git a/Releases/v4.0.1/.claude/hooks/WorkCompletionLearning.hook.ts b/Releases/v4.0.1/.claude/hooks/WorkCompletionLearning.hook.ts
index 3f199eaa..f15038fb 100755
--- a/Releases/v4.0.1/.claude/hooks/WorkCompletionLearning.hook.ts
+++ b/Releases/v4.0.1/.claude/hooks/WorkCompletionLearning.hook.ts
@@ -104,6 +104,7 @@ function parseYaml(content: string): WorkMeta {
let currentKey = '';
let inArray = false;
let arrayKey = '';
+ let lineageSubKey = '';
for (const line of lines) {
const trimmed = line.trim();
@@ -113,9 +114,8 @@ function parseYaml(content: string): WorkMeta {
if (trimmed.startsWith('- ') && inArray) {
const value = trimmed.slice(2).replace(/^["']|["']$/g, '');
if (arrayKey === 'lineage') {
- // Nested array in lineage
- const lastKey = Object.keys(meta.lineage).pop();
- if (lastKey) meta.lineage[lastKey].push(value);
+ // Nested array in lineage — use tracked sub-key
+ if (lineageSubKey) meta.lineage[lineageSubKey].push(value);
} else {
meta[arrayKey].push(value);
}
@@ -145,6 +145,7 @@ function parseYaml(content: string): WorkMeta {
if (meta.lineage && ['tools_used', 'files_changed', 'agents_spawned'].includes(key)) {
meta.lineage[key] = [];
arrayKey = 'lineage';
+ lineageSubKey = key;
inArray = true;
} else {
meta[key] = [];
diff --git a/Releases/v4.0.1/.claude/hooks/handlers/DocCrossRefIntegrity.ts b/Releases/v4.0.1/.claude/hooks/handlers/DocCrossRefIntegrity.ts
index a0de54b6..5ece1bd4 100644
--- a/Releases/v4.0.1/.claude/hooks/handlers/DocCrossRefIntegrity.ts
+++ b/Releases/v4.0.1/.claude/hooks/handlers/DocCrossRefIntegrity.ts
@@ -35,6 +35,7 @@
import { readFileSync, writeFileSync, existsSync, readdirSync, mkdirSync } from 'fs';
import { join, basename, dirname } from 'path';
import { paiPath, getPaiDir } from '../lib/paths';
+import { getIdentity } from '../lib/identity';
import { inference } from '../../PAI/Tools/Inference';
import type { ParsedTranscript } from '../../PAI/Tools/TranscriptParser';
@@ -363,7 +364,7 @@ async function notifyVoice(message: string): Promise<void> {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
signal: AbortSignal.timeout(3000),
- body: JSON.stringify({ message, voice_id: 'fTtv3eikoepIosk8dTZ5' }),
+ body: JSON.stringify({ message, voice_id: getIdentity().mainDAVoiceID }),
});
} catch {
// Voice server may not be running — silent fail
@@ -832,13 +833,18 @@ export async function handleDocCrossRefIntegrity(
// Step 6: Inference-powered semantic analysis
// Run inference to catch what grep can't: semantic drift in descriptions
- console.error(`${TAG} === Running inference analysis ===`);
- const inferenceEdits = await runInferenceAnalysis(modifiedFiles, docsToCheck);
- if (inferenceEdits.length > 0) {
- const inferenceApplied = applyInferenceEdits(inferenceEdits);
- updatesApplied.push(...inferenceApplied);
+ // Skip if no drift found — saves ~15s of inference per response
+ if (allDrift.length > 0) {
+ console.error(`${TAG} === Running inference analysis ===`);
+ const inferenceEdits = await runInferenceAnalysis(modifiedFiles, docsToCheck);
+ if (inferenceEdits.length > 0) {
+ const inferenceApplied = applyInferenceEdits(inferenceEdits);
+ updatesApplied.push(...inferenceApplied);
+ } else {
+ console.error(`${TAG} [INFERENCE] No semantic corrections needed`);
+ }
} else {
- console.error(`${TAG} [INFERENCE] No semantic corrections needed`);
+ console.error(`${TAG} [INFERENCE] Skipped — no drift detected`);
}
// Step 7: Save drift report (renumbered for inference step)
diff --git a/Releases/v4.0.1/.claude/hooks/handlers/UpdateCounts.ts b/Releases/v4.0.1/.claude/hooks/handlers/UpdateCounts.ts
index 8bf3154e..cf1718a3 100755
--- a/Releases/v4.0.1/.claude/hooks/handlers/UpdateCounts.ts
+++ b/Releases/v4.0.1/.claude/hooks/handlers/UpdateCounts.ts
@@ -262,6 +262,16 @@ export async function handleUpdateCounts(): Promise<void> {
// Update counts section
settings.counts = counts;
+ // Extract and write Algorithm version from CLAUDE.md
+ try {
+ const claudeMd = readFileSync(join(paiDir, 'CLAUDE.md'), 'utf-8');
+ const algoMatch = claudeMd.match(/Algorithm\/v([\d.]+)\.md/);
+ if (algoMatch) {
+ settings.pai = settings.pai || {};
+ settings.pai.algorithmVersion = algoMatch[1];
+ }
+ } catch {}
+
// Write back
writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\n');
console.error(`[UpdateCounts] Updated: SK:${counts.skills} WF:${counts.workflows} HK:${counts.hooks} SIG:${counts.signals} F:${counts.files} W:${counts.work} SESS:${counts.sessions} RES:${counts.research} RAT:${counts.ratings}`);
diff --git a/Releases/v4.0.1/.claude/statusline-command.sh b/Releases/v4.0.1/.claude/statusline-command.sh
index f4dd37df..fac6b481 100755
--- a/Releases/v4.0.1/.claude/statusline-command.sh
+++ b/Releases/v4.0.1/.claude/statusline-command.sh
@@ -410,6 +410,8 @@ learning_count="$learnings_count"
# ─────────────────────────────────────────────────────────────────────────────
# Hooks don't inherit terminal context. Try multiple methods.
+_width_cache="/tmp/pai-term-width-${KITTY_WINDOW_ID:-default}"
+
detect_terminal_width() {
local width=""
@@ -426,10 +428,25 @@ detect_terminal_width() {
# Tier 3: tput fallback
[ -z "$width" ] || [ "$width" = "0" ] && width=$(tput cols 2>/dev/null)
- # Tier 4: Environment variable
- [ -z "$width" ] || [ "$width" = "0" ] && width=${COLUMNS:-80}
+ # If we got a real width, cache it for subprocess re-renders
+ if [ -n "$width" ] && [ "$width" != "0" ] && [ "$width" -gt 0 ] 2>/dev/null; then
+ echo "$width" > "$_width_cache" 2>/dev/null
+ echo "$width"
+ return
+ fi
+
+ # Tier 4: Read cached width from previous successful detection
+ if [ -f "$_width_cache" ]; then
+ local cached
+ cached=$(cat "$_width_cache" 2>/dev/null)
+ if [ "$cached" -gt 0 ] 2>/dev/null; then
+ echo "$cached"
+ return
+ fi
+ fi
- echo "$width"
+ # Tier 5: Environment variable / default
+ echo "${COLUMNS:-80}"
}
term_width=$(detect_terminal_width)