Skip to content

sno-ai/sno-station-skills / skills/R-recursive-self-improvement/rem-reflect/skill

rem-reflect

Verified

Self Learning from this machine's Claude Code, Codex, Hermes, OpenClaw and Cursor sessions. Decide skill changes and lessons with accept/reject/tbd; recall lessons at session start.

FileKindSize
SKILL.mdskill md14.1 KB
references/labeler.mdmarkdown1.2 KB
references/labeler.schema.jsonconfig1.7 KB
references/local-settings.jsonconfig126 B
references/local-writer.schema.jsonconfig2.3 KB
references/proposal.schema.jsonconfig3.2 KB
references/render.jsonconfig245 B
references/signals.jsonconfig71 B
references/text.jsonconfig4.0 KB
scripts/adopt.test.tsscript13.0 KB
scripts/adopt.tsscript14.3 KB
scripts/agent-sessions.tsscript9.1 KB
scripts/allowance-fallback.test.tsscript16.0 KB
scripts/allowance-request-isolation.test.tsscript7.1 KB
scripts/backend.tsscript9.1 KB
scripts/calls.tsscript8.6 KB
scripts/catalogue-cloud.test.tsscript1.5 KB
scripts/catalogue.tsscript3.2 KB
scripts/chunk.tsscript2.1 KB
scripts/cloud-apply.test.tsscript25.2 KB
scripts/cloud-batch.test.tsscript11.2 KB
scripts/cloud-day.test.tsscript6.8 KB
scripts/cloud-verdict.test.tsscript12.1 KB
scripts/cloud-wait.test.tsscript1.3 KB
scripts/cloud.tsscript24.4 KB
scripts/config.tsscript8.1 KB
scripts/cursor.test.tsscript16.1 KB
scripts/cursor.tsscript6.7 KB
scripts/evidence.tsscript1.5 KB
scripts/first-message.test.tsscript10.3 KB
scripts/harvest.test.tsscript16.5 KB
scripts/harvest.tsscript22.6 KB
scripts/hermes-openclaw.test.tsscript25.6 KB
scripts/identity.test.tsscript3.3 KB
scripts/identity.tsscript3.5 KB
scripts/installed-roots.test.tsscript11.0 KB
scripts/journey-adopt-lesson.test.tsscript4.1 KB
scripts/journey-ops.test.tsscript8.0 KB
scripts/labeler.test.tsscript3.6 KB
scripts/labeler.tsscript9.5 KB
scripts/ledger.tsscript2.1 KB
scripts/lessons.tsscript4.7 KB
scripts/local-filter.test.tsscript3.9 KB
scripts/local-first-output.test.tsscript22.1 KB
scripts/local-settings.tsscript1.4 KB
scripts/local-writer.tsscript12.6 KB
scripts/login-in-place.test.tsscript5.8 KB
scripts/model-json.tsscript4.1 KB
scripts/no-network.test.tsscript5.0 KB
scripts/observe.tsscript1.4 KB
scripts/page-journey.test.tsscript6.7 KB
scripts/pages.test.tsscript4.1 KB
scripts/pages.tsscript4.8 KB
scripts/proposer-loop.test.tsscript1.5 KB
scripts/proposer-validate.test.tsscript9.1 KB
scripts/proposer.tsscript8.7 KB
scripts/recall-hook.test.tsscript20.9 KB
scripts/recall.test.tsscript31.4 KB
scripts/recall.tsscript18.2 KB
scripts/reflect.test.tsscript9.3 KB
scripts/reflect.tsscript14.3 KB
scripts/rem-reflectexecutablescript823 B
scripts/rem-reflect.tsscript17.8 KB
scripts/render-chunk.test.tsscript7.2 KB
scripts/render.tsscript9.7 KB
scripts/report.tsscript8.2 KB
scripts/run-status.test.tsscript19.1 KB
scripts/sampling.test.tsscript2.1 KB
scripts/sampling.tsscript915 B
scripts/selftest-guard.test.tsscript4.2 KB
scripts/selftest/bin/claudeexecutablescript94 B
scripts/selftest/bin/codexexecutablescript93 B
scripts/selftest/bin/shim-core.cjsscript4.6 KB
scripts/selftest/bin/snoexecutablescript5.7 KB
scripts/selftest/fixtures/hermes-session-export.jsonlother1.5 KB
scripts/selftest/fixtures/openclaw-events.jsonlother3.7 KB
scripts/selftest/fixtures/verdict-traces.jsonconfig16.6 KB
scripts/selftest/journey-e2e.shexecutablescript1.4 KB
scripts/selftest/journey.mjsscript9.5 KB
scripts/selftest/observe-journey.mjsscript12.5 KB
scripts/selftest/run-selftest.shexecutablescript7.0 KB
scripts/selftest/spawn-python.mjsexecutablescript765 B
scripts/session.test.tsscript5.2 KB
scripts/session.tsscript251 B
scripts/signal-local.test.tsscript7.0 KB
scripts/skill-impact.test.tsscript6.2 KB
scripts/station-settings.test.tsscript13.6 KB
scripts/store-memory.test.tsscript3.4 KB
scripts/store.tsscript7.7 KB
scripts/test-helpers.tsscript15.3 KB
scripts/text.tsscript760 B
scripts/trigger.test.tsscript3.6 KB
scripts/trigger.tsscript2.5 KB
scripts/verdicts.test.tsscript8.1 KB
scripts/verdicts.tsscript8.0 KB

scripts/cloud.ts

View on GitHub
import { spawnSync } from 'node:child_process';
import { createHash, randomUUID } from 'node:crypto';
import { appendFileSync, existsSync, readFileSync, readdirSync, unlinkSync } from 'node:fs';
import { basename, join } from 'node:path';
import type { Config } from './config.ts';
import { reflectionFiles, isObject, limits, skillRoots, stationCell, readStationSettings } from './config.ts';
import { installedCatalogue } from './catalogue.ts';
import { chunkRendering } from './chunk.ts';
import { traceKey } from './evidence.ts';
import type { Evidence } from './evidence.ts';
import { lessonTrigger } from './trigger.ts';
import { existingTraces } from './harvest.ts';
import type { Trace } from './harvest.ts';
import type { Label } from './labeler.ts';
import { readLabels } from './labeler.ts';
import { readLedger } from './ledger.ts';
import { appendLedger } from './ledger.ts';
import { appendRows, readLessonReads, readLessons, readLessonsShown } from './lessons.ts';
import { readPages, renderIndex, writePage } from './pages.ts';
import type { Page } from './pages.ts';
import { proposalSignature, validateProposal } from './proposer.ts';
import { loadRenderBudgets, renderTrace } from './render.ts';
import { readCalls } from './calls.ts';
import { externalVerdicts } from './verdicts.ts';
import type { Verdict } from './verdicts.ts';
import { skillImpact } from './report.ts';
import { lessonProject, observe } from './observe.ts';
import { atomicWrite, commitStore, writeJson } from './store.ts';
import { locallyWrittenSessions } from './local-writer.ts';

export interface CloudResponse {
  schema_version: 1;
  run_id: string;
  history_acknowledged: boolean;
  history_links: unknown[];
  halves: unknown[];
}

export class AllowanceUsedUp extends Error {
  readonly reset_at: string;
  constructor(message: string, resetAt: string) { super(message); this.reset_at = resetAt; }
}

export function localConsent(): 'off' | 'metadata-only' | 'full' {
  const result = spawnSync('sno', ['station', 'consent', '--json'], { encoding: 'utf8' });
  if (result.error) throw result.error;
  if (result.status !== 0) throw new Error(result.stderr?.trim() || `sno station consent exited ${result.status}`);
  const answer: unknown = JSON.parse(result.stdout);
  const level = isObject(answer) ? answer.consent : undefined;
  if (level !== 'off' && level !== 'metadata-only' && level !== 'full') throw new Error(`sno station consent returned ${result.stdout.trim()}`);
  return level;
}

// R4 (first-prompt lookup) sends text only when its cell is `sno-gpu` and consent is `full`.
// Daily runs and verdicts instead share by mode, with consent enforced by sno rem. Throws when the
// consent level cannot be read; the caller reports that and sends nothing.
export function cloudStepGate(id: 'R4'): { send: true } | { send: false; reason: string } {
  const cell = stationCell(id);
  if (cell !== 'sno-gpu') return { send: false, reason: `${id} is ${cell} under this mode` };
  const consent = localConsent();
  return consent === 'full' ? { send: true } : { send: false, reason: `consent ${consent}` };
}

export function flushCloudVerdicts(store: string): { sent: number; pending: number; errors: string[] } {
  const newest = new Map<string, Record<string, unknown>>();
  for (const row of readLedger(store).filter(row => row.type === 'cloud-verdict' && typeof row.judgment_id === 'string')) {
    newest.set(String(row.judgment_id), row);
  }
  const pending = [...newest.values()].filter(row => row.status === 'pending');
  const errors: string[] = [];
  if (!pending.length) return { sent: 0, pending: 0, errors };
  let sent = 0;
  for (const row of pending) {
    const id = String(row.judgment_id);
    const verdict = String(row.verdict);
    const promoted = row.applies_to === 'general';
    try {
      if (readStationSettings().mode === 'local-first') break;
      const result = spawnSync('sno', ['rem', 'verdict', id, verdict, ...(promoted ? ['--all-projects'] : [])],
        { encoding: 'utf8' });
      if (result.error) throw result.error;
      if (result.status !== 0) throw new Error(result.stderr?.trim() || `sno rem verdict exited ${result.status}`);
      if (!result.stdout) throw new Error('cloud verdict: empty acknowledgment');
      const answer: unknown = JSON.parse(result.stdout);
      if (!isObject(answer) || answer.schema_version !== 1 || answer.judgment_id !== id
        || answer.verdict !== verdict || answer.acknowledged !== true
        || (promoted && answer.applies_to !== 'general')) throw new Error('cloud verdict: mismatched acknowledgment');
      appendLedger(store, { ...row, status: 'acked', ...(promoted ? { applies_to: answer.applies_to } : {}) });
      commitStore(store, `cloud verdict ${id}`);
      sent++;
    } catch (error) {
      const message = `cloud verdict ${id} send failed: ${String(error)}; local verdict unchanged, upload pending`;
      errors.push(message);
      const logPath = join(store, reflectionFiles.runLog);
      try { appendFileSync(logPath, `${message}\n`); }
      catch (logError) { errors.push(`cloud verdict ${id} log failed at ${logPath}: ${String(logError)}`); }
    }
  }
  return { sent, pending: pending.length - sent, errors };
}

export function buildCloudBatch(store: string, config: Config, runId: string, retained: readonly Trace[],
  labels: ReadonlyMap<string, Label>, includeHistory: boolean) {
  const written = locallyWrittenSessions(store);
  retained = retained.filter(trace => !written.has(traceKey(trace)));
  const selectedSessions = new Set(retained.map(trace => trace.session_id));
  const ledger = readLedger(store);
  const halves = (['claude-code', 'codex', 'hermes', 'openclaw', 'cursor'] as const).map(harness => ({
    harness,
    sessions: retained.filter(trace => trace.agent_id === harness).map(trace => {
      const label = labels.get(traceKey(trace));
      if (!label || label.decision !== 'keep') throw new Error(`cloud batch: missing keep decision for ${trace.trace_id}`);
      const chunks = chunkRendering(trace.trace_id, renderTrace(trace, loadRenderBudgets()));
      const calls = readCalls(trace);
      // Code's verdicts travel beside the calls; a session whose verdicts cannot be computed still uploads, with none.
      let verdicts: Verdict[] = [];
      try { verdicts = externalVerdicts(calls); }
      catch (error) {
        appendFileSync(join(store, reflectionFiles.staging, runId, reflectionFiles.runLog),
          `${trace.trace_id}: external verdicts not computed: ${String(error)}; uploaded with none\n`);
      }
      return {
        trace_id: trace.trace_id, session_id: trace.session_id, project_id: trace.project_id, user_id: trace.user_id,
        version: trace.version, source_mtime_ms: trace.source_mtime, source_line_range: trace.source_line_range,
        skills_loaded: trace.skills_loaded, trivial: trace.trivial, local_outcome: label.outcome, local_reason: label.reason,
        chunks: chunks.map(chunk => ({ id: chunk.id, line_start: chunk.line_range[0], line_end: chunk.line_range[1], text: chunk.text })),
        calls, external_verdicts: verdicts,
      };
    }),
  })).filter(half => half.sessions.length > 0);
  return {
    schema_version: 1,
    run_id: runId,
    halves,
    catalogue: installedCatalogue(skillRoots(config)),
    usage_reads: readLessonReads(store, []).filter(read => selectedSessions.has(read.session_id)),
    usage_shown: readLessonsShown(store, []).filter(row => selectedSessions.has(row.session_id)),
    outcome_summary: { adopted_units: skillImpact(skillRoots(config), existingTraces(store, () => false), readLabels(store), ledger) },
    ...(includeHistory ? { history: {
      pages: readPages(store), lessons: readLessons(store),
      proposals: ledger.filter(row => row.type === 'proposal'),
      skill_impact_rows: ledger.filter(row => row.type !== 'proposal'),
    } } : {}),
  };
}

export function sendCloudBatch(store: string, batch: {
  schema_version: number; run_id: string; halves: unknown; catalogue: unknown; usage_reads: unknown; usage_shown: unknown; outcome_summary: unknown;
}, waitMs: number = limits.cloudWaitMs): CloudResponse {
  const staging = join(store, reflectionFiles.staging);
  const pending = readdirSync(staging).sort().find(id =>
    existsSync(join(staging, id, 'cloud-request.json')) && !existsSync(join(staging, id, 'cloud-response.json')));
  const directory = join(staging, pending ?? batch.run_id);
  const requestPath = join(directory, 'cloud-request.json');
  if (!pending) writeJson(requestPath, batch);
  // A half surrogate pair (from a session or an older truncation) is invalid JSON text for the sno CLI,
  // and a NUL (session text, older proposal signatures) is refused by the cloud's JSON column;
  // the same replacement on every send keeps a replayed request byte-identical.
  const sent: unknown = JSON.parse(readFileSync(requestPath, 'utf8'));
  const input = JSON.stringify(sent, (_key, value: unknown) =>
    typeof value === 'string' ? value.toWellFormed().replaceAll('\0', '') : value);
  if (!isObject(sent) || typeof sent.run_id !== 'string') throw new Error('cloud batch: pending request has no run id');

  const result = spawnSync('sno', ['rem', 'judge', '--json'], { input, encoding: 'utf8', maxBuffer: Infinity, timeout: waitMs, killSignal: 'SIGKILL' });
  if ((result.error as NodeJS.ErrnoException | undefined)?.code === 'ETIMEDOUT') {
    throw new Error(`sno rem judge gave no answer within ${Math.round(waitMs / 60_000)} minutes; the saved request is resent on the next run`);
  }
  if (result.error) throw result.error;
  if (result.status !== 0) {
    let error: unknown;
    try { error = JSON.parse(result.stdout); } catch { /* Other failures keep their existing stderr message. */ }
    if (isObject(error) && error.error === 'allowance_used_up' && typeof error.message === 'string' && typeof error.reset_at === 'string') {
      throw new AllowanceUsedUp(error.message, error.reset_at);
    }
    const message = isObject(error) && typeof error.message === 'string' ? error.message : '';
    throw new Error(message || result.stderr?.trim() || `sno rem judge exited ${result.status}`);
  }
  if (!result.stdout) throw new Error('cloud batch: empty judgment response');
  const response: unknown = JSON.parse(result.stdout);
  if (!isObject(response) || response.schema_version !== 1 || response.run_id !== sent.run_id
    || typeof response.history_acknowledged !== 'boolean'
    || !Array.isArray(response.history_links) || !Array.isArray(response.halves)) {
    throw new Error('cloud batch: response does not match the pending run');
  }
  writeJson(join(directory, 'cloud-response.json'), response);
  slimAnsweredRequest(requestPath);
  return response as unknown as CloudResponse;
}

// Only locally learned session versions leave unanswered uploads; other versions stay pending.
export function removeLocallyWrittenSessions(store: string, log: string[]): void {
  const written = locallyWrittenSessions(store);
  if (!written.size) return;
  const staging = join(store, reflectionFiles.staging);
  for (const id of readdirSync(staging)) {
    const path = join(staging, id, 'cloud-request.json');
    if (!existsSync(path) || existsSync(join(staging, id, 'cloud-response.json'))) continue;
    try {
      const request: unknown = JSON.parse(readFileSync(path, 'utf8'));
      if (!isObject(request) || !Array.isArray(request.halves)) continue;
      const halves = request.halves.filter(isObject).map(half => ({ ...half,
        sessions: (Array.isArray(half.sessions) ? half.sessions : []).filter(session =>
          !isObject(session) || !written.has(`${session.user_id}/${half.harness}/${session.trace_id}`)),
      })).filter(half => half.sessions.length > 0);
      if (!halves.length) { unlinkSync(path); continue; }
      const sessions = new Set(halves.flatMap(half => half.sessions.filter(isObject).map(session => session.session_id)));
      const updated: Record<string, unknown> = { ...request, halves };
      for (const key of ['usage_reads', 'usage_shown']) {
        if (Array.isArray(updated[key])) updated[key] = updated[key].filter(row => isObject(row) && sessions.has(row.session_id));
      }
      if (JSON.stringify(updated) !== JSON.stringify(request)) {
        const nextRunId = `${id}-local-${randomUUID()}`;
        writeJson(join(staging, nextRunId, 'cloud-request.json'), { ...updated, run_id: nextRunId });
        unlinkSync(path);
      }
    } catch (error) {
      log.push(`cloud run ${id} request not edited: ${String(error)}; full request kept, cloud may judge locally learned sessions again after reset`);
    }
  }
}

// Once the cloud has answered, later nights read only the uploaded skill catalogue and which session versions were
// sent; the session text was a copy for the upload and would otherwise stay in the store for every night.
export function slimAnsweredRequest(path: string): void {
  const request: unknown = JSON.parse(readFileSync(path, 'utf8'));
  if (!isObject(request) || !Array.isArray(request.halves)) return;
  const slim = { schema_version: request.schema_version, run_id: request.run_id, catalogue: request.catalogue,
    halves: request.halves.map(half => isObject(half) && Array.isArray(half.sessions)
      ? { harness: half.harness, sessions: half.sessions.map(session => isObject(session)
        ? { session_id: session.session_id, version: session.version } : session) }
      : half) };
  if (JSON.stringify(slim) !== JSON.stringify(request)) writeJson(path, slim);
}

export function applyCloudHistoryLinks(store: string, links: readonly unknown[]): Set<string> {
  const linked = new Set(readLedger(store).flatMap(row => typeof row.judgment_id === 'string' ? [row.judgment_id] : []));
  for (const raw of links) {
    if (!isObject(raw) || typeof raw.kind !== 'string' || typeof raw.local_id !== 'string'
      || typeof raw.judgment_id !== 'string') throw new Error('cloud batch: invalid history link');
    if (linked.has(raw.judgment_id)) continue;
    appendLedger(store, { type: 'cloud-link', kind: raw.kind, local_id: raw.local_id, judgment_id: raw.judgment_id });
    linked.add(raw.judgment_id);
  }
  return linked;
}

export function applyCloudResponse(store: string, config: Config, response: CloudResponse): void {
  let userLessonsIssued = 0;
  const projectLessonsIssued = new Map<string, number>();
  const request: unknown = JSON.parse(readFileSync(join(store, reflectionFiles.staging, response.run_id, 'cloud-request.json'), 'utf8'));
  if (!isObject(request) || !Array.isArray(request.catalogue)) throw new Error('cloud batch: saved catalogue missing');
  const uploaded = new Map<string, string>();
  for (const entry of request.catalogue) {
    if (!isObject(entry) || typeof entry.path !== 'string' || typeof entry.skill_md !== 'string') throw new Error('cloud batch: saved catalogue invalid');
    uploaded.set(entry.path, entry.skill_md);
  }
  const linked = applyCloudHistoryLinks(store, response.history_links);
  const judged = new Set(readLedger(store).filter(row => row.type === 'lesson-judgment')
    .map(row => `${row.trace_id}::${row.lesson_id}`));
  const runLog = join(store, reflectionFiles.staging, response.run_id, reflectionFiles.runLog);
  // The traces tonight's lessons cite, read with their text once; a lesson's trigger condition is computed from them.
  const citedIds = new Set<string>();
  for (const half of response.halves) {
    if (!isObject(half) || !Array.isArray(half.lessons)) continue;
    for (const item of half.lessons) {
      const first = isObject(item) && isObject(item.lesson) && Array.isArray(item.lesson.evidence) ? item.lesson.evidence[0] : undefined;
      if (isObject(first) && typeof first.trace_id === 'string') citedIds.add(first.trace_id);
    }
  }
  let citedTraces = new Map<string, Trace>();
  try { if (citedIds.size) citedTraces = new Map(existingTraces(store, trace => citedIds.has(trace.trace_id)).map(trace => [trace.trace_id, trace])); }
  catch (error) { appendFileSync(runLog, `trigger match: traces not read: ${String(error)}; lessons land without one\n`); }
  const cited = (id: unknown): Trace | undefined => typeof id === 'string' && citedIds.has(id) ? citedTraces.get(id) : undefined;
  for (const half of response.halves) {
    if (!isObject(half) || !['claude-code', 'codex', 'hermes', 'openclaw', 'cursor'].includes(String(half.harness))
      || !Array.isArray(half.pages) || !Array.isArray(half.lessons) || !Array.isArray(half.proposals)
      || !Array.isArray(half.read_judgments)) {
      throw new Error('cloud batch: invalid half');
    }
    for (const item of half.pages) {
      if (!isObject(item) || typeof item.judgment_id !== 'string' || !isObject(item.page)
        || typeof item.page.page_id !== 'string') throw new Error('cloud batch: invalid page');
      const page = { ...item.page, judgment_id: item.judgment_id } as unknown as Page;
      // Judgment ids are UUIDv7 and sort by time: a replayed older or identical answer never overwrites a newer one.
      const stored = (readPages(store).find(row => row.page_id === page.page_id) as { judgment_id?: string } | undefined)?.judgment_id;
      if (stored && stored >= item.judgment_id) continue;
      writePage(store, page);
      if (page.superseded) {
        const accepted = readLessons(store).find(row => row.page_id === page.page_id && row.status === 'accepted');
        if (accepted) appendRows(join(store, reflectionFiles.lessons), [{ ...accepted, status: 'under_review' }]);
      }
    }
    for (const item of half.lessons) {
      if (!isObject(item) || typeof item.judgment_id !== 'string' || !isObject(item.lesson)
        || typeof item.lesson.lesson_id !== 'string') throw new Error('cloud batch: invalid lesson');
      const lesson = item.lesson;
      const current = readLessons(store).find(row => row.lesson_id === lesson.lesson_id);
      // A replayed cloud answer never undoes the owner's accept or reject, nor the scope chosen with it.
      if (current?.status === 'accepted' || current?.status === 'rejected') {
        if (current.status === 'accepted' && lesson.did_not_prevent === true
          && (current.did_not_prevent !== true || JSON.stringify(current.criterion_judgment) !== JSON.stringify(lesson.criterion_judgment))) {
          appendRows(join(store, reflectionFiles.lessons), [{ ...current, did_not_prevent: true,
            ...(isObject(lesson.criterion_judgment) ? { criterion_judgment: lesson.criterion_judgment } : {}) }]);
        }
        continue;
      }
      if (!current?.judgment_id || current.judgment_id < item.judgment_id) {
        // Cloud citations have the store's evidence shape; the trace was validated when it was harvested.
        const evidence = Array.isArray(lesson.evidence) ? lesson.evidence as Evidence[] : [];
        const trigger = lessonTrigger(cited(evidence[0]?.trace_id), evidence, line => appendFileSync(runLog, `${lesson.lesson_id}: ${line}\n`));
        appendRows(join(store, reflectionFiles.lessons), [{ ...lesson, judgment_id: item.judgment_id, trigger_match: trigger }]);
        const project = lessonProject(lesson.applies_to, config);
        if (project === undefined) userLessonsIssued++;
        else projectLessonsIssued.set(project, (projectLessonsIssued.get(project) ?? 0) + 1);
      }
    }
    if (half.proposals.length > 1) throw new Error('cloud batch: more than one proposal in a half');
    for (const item of half.proposals) {
      if (!isObject(item) || typeof item.judgment_id !== 'string' || !isObject(item.proposal)) throw new Error('cloud batch: invalid proposal');
      if (linked.has(item.judgment_id)) continue;
      const roots = skillRoots(config);
      const target = typeof item.proposal.target === 'string' ? item.proposal.target.replace(/\/SKILL\.md$/, '') : '';
      const hashes: Record<string, string> = {};
      let validated: ReturnType<typeof validateProposal>;
      // A proposal this machine refuses is logged and skipped; the rest of the response still applies.
      try {
        validated = validateProposal(item.proposal, { store, roots, pages: readPages(store) }, new Set([target]));
        if (validated.kind === 'patch' && validated.target) {
          for (const root of roots) {
            const payload = join(root, basename(validated.target));
            const body = uploaded.get(join(payload, 'SKILL.md'));
            if (body) hashes[payload] = createHash('sha256').update(body).digest('hex');
          }
          if (!Object.keys(hashes).length) throw new Error('proposal target was not uploaded');
        }
      } catch (error) {
        appendFileSync(join(store, reflectionFiles.staging, response.run_id, reflectionFiles.runLog),
          `proposal refused: run ${response.run_id} half ${String(half.harness)} target ${target || '(none)'}: ${String(error)}\n`);
        continue;
      }
      const directory = join(store, reflectionFiles.staging, response.run_id, String(half.harness));
      writeJson(join(directory, reflectionFiles.proposal), { ...item.proposal, judgment_id: item.judgment_id, target_hashes: hashes });
      if (validated.kind === 'create') atomicWrite(join(directory, reflectionFiles.skillMd), validated.skillMd ?? '');
      if (validated.kind === 'patch') writeJson(join(directory, reflectionFiles.patch), {
        region: validated.region, ops: validated.ops ?? null, line: validated.reminderLine ?? null,
        replace_line: validated.replaceLine ?? null,
      });
      atomicWrite(join(directory, reflectionFiles.purpose), `${validated.proposal.purpose.summary}\nPages: ${validated.proposal.purpose.page_ids.join(', ')}\n`);
      const p = validated.proposal;
      appendLedger(store, { type: 'proposal', proposal_id: `${response.run_id}/${half.harness}`, run_id: response.run_id,
        half: half.harness, backend: 'sno-cloud', kind: validated.kind, target: validated.target, region: validated.region,
        diff: validated.diff, expertise: { scenario: p.scenario, skills_used: p.skills_used ?? [], skill_target: p.skill_target ?? null,
          knowledge_used: p.knowledge_used ?? [], outcome: p.outcome ?? 'unknown', evidence: p.evidence ?? [] },
        purpose: p.purpose, verdict: 'pending', evidence: p.evidence ?? [], signature: proposalSignature(p),
        judgment_id: item.judgment_id, target_hashes: hashes });
      linked.add(item.judgment_id);
    }
    const traces = new Map(existingTraces(store, () => false).map(trace => [trace.trace_id, trace]));
    const labels = readLabels(store);
    // A judgment counts when this session was shown the lesson at start (the index line carries the advice) or read it in full.
    const seen = new Set(readLessonReads(store, []).map(read => `${read.session_id}::${read.lesson_id}`));
    for (const row of readLessonsShown(store, [])) for (const id of row.lesson_ids) seen.add(`${row.session_id}::${id}`);
    // The cloud sends judgments of lessons that were only shown in their own field, which clients up to 1.0.13 ignore.
    const judgments = [...half.read_judgments, ...(Array.isArray(half.shown_judgments) ? half.shown_judgments : [])];
    for (const item of judgments) {
      if (!isObject(item) || typeof item.trace_id !== 'string' || typeof item.lesson_id !== 'string'
        || !['yes', 'no', 'unclear'].includes(String(item.followed))
        || !['helped', 'harmful', 'neutral'].includes(String(item.effect))) throw new Error('cloud batch: invalid read judgment');
      const trace = traces.get(item.trace_id);
      if (!trace || !seen.has(`${trace.session_id}::${item.lesson_id}`)) throw new Error('cloud batch: read judgment has no lesson shown or read');
      const pair = `${item.trace_id}::${item.lesson_id}`;
      if (judged.has(pair)) continue;
      appendLedger(store, { ...item, type: 'lesson-judgment', run_id: response.run_id });
      judged.add(pair);
      const outcome = labels.get(traceKey(trace))?.outcome;
      const lesson = readLessons(store).find(row => row.lesson_id === item.lesson_id);
      if (item.followed !== 'yes' || !['helped', 'harmful'].includes(String(item.effect))
        || (!(lesson?.expected_result && lesson.success_criteria) && outcome !== 'success' && outcome !== 'fail')) continue;
      if (!lesson) continue;
      appendRows(join(store, reflectionFiles.lessons), [{ ...lesson, measured: true,
        helped: lesson.helped + Number(item.effect === 'helped'),
        harmful: lesson.harmful + Number(item.effect === 'harmful') }]);
    }
  }
  atomicWrite(join(store, reflectionFiles.index), renderIndex(readPages(store), existingTraces(store, () => false)));
  observe('rsi.lesson', { level: 'user', count: userLessonsIssued },
    join(store, reflectionFiles.staging, response.run_id, reflectionFiles.runLog));
  for (const [project, count] of projectLessonsIssued) {
    observe('rsi.lesson', { level: 'project', project, count },
      join(store, reflectionFiles.staging, response.run_id, reflectionFiles.runLog));
  }
}
reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.Stars: 472kUpdated Claude CodeCodexUnverifiedInstall
diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.Stars: 322kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 322kUpdated Claude CodeCodexVerifiedInstall
executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is availableStars: 322kUpdated Claude CodeCodexVerifiedInstall