← back to Dw Launchd Canary

make-bootstrap-paste.mjs

93 lines

#!/usr/bin/env node
// gated-plist-install batcher (Officer Idea Council #5, 2026-06-17).
//
// The launchd canary DETECTS dropped jobs; this turns that list into ONE
// copy-paste block that bootstraps the backlog — user-level launchd only, NO
// sudo. It is a GENERATOR: it prints a script and changes nothing. Steve reviews
// and runs it (re-arming a scheduled job is a gated action).
//
// Safety: it does NOT blindly arm everything. Jobs the canary marks
// expected_unloaded (deliberate hazards like drain-all-queues), plus an explicit
// review denylist, are emitted COMMENTED OUT under a REVIEW header. Every line is
// annotated with what the job runs + its schedule so the paste is legible.
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { execSync } from 'node:child_process';

const HOME = os.homedir();
const LA = path.join(HOME, 'Library/LaunchAgents');
const SKILL = path.join(HOME, 'Projects/dw-launchd-canary');
const manifest = JSON.parse(fs.readFileSync(path.join(SKILL, 'manifest.json'), 'utf8'));
const expectedUnloaded = new Set(manifest.expected_unloaded || []);
const notes = manifest.notes || {};

// Jobs that are dropped but should NOT be auto-armed without a human look —
// obsolete one-offs, things waiting on an external blocker, etc. Emitted commented.
const REVIEW = new Set([
  'gmc-optout-reminder',   // GMC suspension risk neutralized 2026-06-17 — reminder likely obsolete
  'color-cleaner-nightly'  // blocked on the capped/compromised Gemini key
]);

function plistMeta(file) {
  try {
    const j = JSON.parse(execSync(`plutil -convert json -o - ${JSON.stringify(path.join(LA, file))}`, { encoding: 'utf8' }));
    const args = (j.ProgramArguments || []).join(' ');
    let sched = '';
    if (j.StartInterval) sched = `every ${j.StartInterval}s`;
    else if (Array.isArray(j.StartCalendarInterval)) sched = `${j.StartCalendarInterval.length} calendar slots`;
    else if (j.StartCalendarInterval) { const c = j.StartCalendarInterval; sched = `daily ${String(c.Hour ?? '?').padStart(2, '0')}:${String(c.Minute ?? 0).padStart(2, '0')}`; }
    else if (j.RunAtLoad) sched = 'RunAtLoad';
    return { args, sched };
  } catch { return { args: '(unreadable plist)', sched: '' }; }
}

function isLoaded(label) {
  try { return !!execSync(`launchctl list 2>/dev/null | grep -F ${label}`, { encoding: 'utf8' }).trim(); } catch { return false; }
}

// Discover dropped jobs (active .plist on disk, not loaded).
const plists = fs.readdirSync(LA).filter(f => /^com\.steve\..+\.plist$/.test(f));
const arm = [], review = [];
for (const f of plists) {
  const label = f.replace(/\.plist$/, '');
  const short = label.replace(/^com\.steve\./, '');
  if (isLoaded(label)) continue;                 // already loaded
  if (expectedUnloaded.has(short)) { review.push({ short, label, f, why: notes[short] || 'expected_unloaded' }); continue; }
  if (REVIEW.has(short)) { review.push({ short, label, f, why: notes[short] || 'flagged for manual review' }); continue; }
  arm.push({ short, label, f });
}
// Always offer the canary's own install (it's gated, not yet bootstrapped).
const selfPlist = 'com.steve.dw-launchd-canary.plist';
if (!isLoaded('com.steve.dw-launchd-canary') && fs.existsSync(path.join(LA, selfPlist)) && !arm.find(a => a.f === selfPlist))
  arm.unshift({ short: 'dw-launchd-canary', label: 'com.steve.dw-launchd-canary', f: selfPlist });

const L = [];
L.push('#!/bin/zsh');
L.push('# ── launchd bootstrap backlog — generated by dw-launchd-canary/make-bootstrap-paste.mjs');
L.push('# User-level launchd only (gui/$UID domain). NO sudo. Review, then paste & run.');
L.push(`# Generated for ${arm.length} job(s) to arm; ${review.length} held for review.`);
L.push('UID_=$(id -u)');
L.push('');
if (!arm.length) L.push('# (nothing to arm — no actionable dropped jobs)');
for (const a of arm) {
  const { args, sched } = plistMeta(a.f);
  L.push(`# ${a.short}${sched ? `  [${sched}]` : ''}  →  ${args}`);
  L.push(`launchctl bootstrap gui/$UID_ "$HOME/Library/LaunchAgents/${a.f}" 2>/dev/null && launchctl kickstart -k "gui/$UID_/${a.label}" && echo "✓ ${a.short}" || echo "✗ ${a.short} (check: launchctl error ${a.label})"`);
  L.push('');
}
if (review.length) {
  L.push('# ─────────────────────────────────────────────────────────────────────');
  L.push('# HELD FOR REVIEW — intentionally NOT armed. Uncomment only if you mean it.');
  for (const r of review) {
    const { args, sched } = plistMeta(r.f);
    L.push(`#   ${r.short}${sched ? `  [${sched}]` : ''}  — ${r.why}`);
    L.push(`#   →  ${args}`);
    L.push(`# launchctl bootstrap gui/$UID_ "$HOME/Library/LaunchAgents/${r.f}"`);
    L.push('');
  }
}
const out = L.join('\n');
console.log(out);
try { const dest = path.join(SKILL, 'data', 'bootstrap-paste.sh'); fs.writeFileSync(dest, out + '\n'); console.error(`\n[written] ${dest}  (${arm.length} arm, ${review.length} review)`); } catch {}