clawdie-ai/skills-engine/state.ts

120 lines
3.2 KiB
TypeScript
Raw Permalink Normal View History

Skills engine v0.1 + multi-channel infrastructure (#307) * refactor: multi-channel infrastructure with explicit channel/is_group tracking - Add channels[] array and findChannel() routing in index.ts, replacing hardcoded whatsapp.* calls with channel-agnostic callbacks - Add channel TEXT and is_group INTEGER columns to chats table with COALESCE upsert to protect existing values from null overwrites - is_group defaults to 0 (safe: unknown chats excluded from groups) - WhatsApp passes explicit channel='whatsapp' and isGroup to onChatMetadata - getAvailableGroups filters on is_group instead of JID pattern matching - findChannel logs warnings instead of silently dropping unroutable JIDs - Migration backfills channel/is_group from JID patterns for existing DBs Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat: skills engine v0.1 — deterministic skill packages with rerere resolution Three-way merge engine for applying skill packages on top of a core codebase. Skills declare which files they add/modify, and the engine uses git merge-file for conflict detection with git rerere for automatic resolution of previously-seen conflicts. Key components: - apply: three-way merge with backup/rollback safety net - replay: clean-slate replay for uninstall and rebase - update: core version updates with deletion detection - rebase: bake applied skills into base (one-way) - manifest: validation with path traversal protection - resolution-cache: pre-computed rerere resolutions - structured: npm deps, env vars, docker-compose merging - CI: per-skill test matrix with conflict detection 151 unit tests covering merge, rerere, backup, replay, uninstall, update, rebase, structured ops, and edge cases. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat: add Discord and Telegram skill packages Skill packages for adding Discord and Telegram channels to NanoClaw. Each package includes: - Channel implementation (add/src/channels/) - Three-way merge targets for index.ts, config.ts, routing.test.ts - Intent docs explaining merge invariants - Standalone integration tests - manifest.yaml with dependency/conflict declarations Applied via: npx tsx scripts/apply-skill.ts .claude/skills/add-discord These are inert until applied — no runtime impact. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * remove unused docs (skills-system-status, implementation-guide) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-19 01:55:00 +02:00
import crypto from 'crypto';
import fs from 'fs';
import path from 'path';
import { parse, stringify } from 'yaml';
import {
SKILLS_SCHEMA_VERSION,
NANOCLAW_DIR,
STATE_FILE,
} from './constants.js';
Skills engine v0.1 + multi-channel infrastructure (#307) * refactor: multi-channel infrastructure with explicit channel/is_group tracking - Add channels[] array and findChannel() routing in index.ts, replacing hardcoded whatsapp.* calls with channel-agnostic callbacks - Add channel TEXT and is_group INTEGER columns to chats table with COALESCE upsert to protect existing values from null overwrites - is_group defaults to 0 (safe: unknown chats excluded from groups) - WhatsApp passes explicit channel='whatsapp' and isGroup to onChatMetadata - getAvailableGroups filters on is_group instead of JID pattern matching - findChannel logs warnings instead of silently dropping unroutable JIDs - Migration backfills channel/is_group from JID patterns for existing DBs Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat: skills engine v0.1 — deterministic skill packages with rerere resolution Three-way merge engine for applying skill packages on top of a core codebase. Skills declare which files they add/modify, and the engine uses git merge-file for conflict detection with git rerere for automatic resolution of previously-seen conflicts. Key components: - apply: three-way merge with backup/rollback safety net - replay: clean-slate replay for uninstall and rebase - update: core version updates with deletion detection - rebase: bake applied skills into base (one-way) - manifest: validation with path traversal protection - resolution-cache: pre-computed rerere resolutions - structured: npm deps, env vars, docker-compose merging - CI: per-skill test matrix with conflict detection 151 unit tests covering merge, rerere, backup, replay, uninstall, update, rebase, structured ops, and edge cases. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat: add Discord and Telegram skill packages Skill packages for adding Discord and Telegram channels to NanoClaw. Each package includes: - Channel implementation (add/src/channels/) - Three-way merge targets for index.ts, config.ts, routing.test.ts - Intent docs explaining merge invariants - Standalone integration tests - manifest.yaml with dependency/conflict declarations Applied via: npx tsx scripts/apply-skill.ts .claude/skills/add-discord These are inert until applied — no runtime impact. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * remove unused docs (skills-system-status, implementation-guide) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-19 01:55:00 +02:00
import { AppliedSkill, CustomModification, SkillState } from './types.js';
function getStatePath(): string {
return path.join(process.cwd(), NANOCLAW_DIR, STATE_FILE);
}
export function readState(): SkillState {
const statePath = getStatePath();
if (!fs.existsSync(statePath)) {
throw new Error(
'.nanoclaw/state.yaml not found. Run initSkillsSystem() first.',
);
}
const content = fs.readFileSync(statePath, 'utf-8');
const state = parse(content) as SkillState;
if (compareSemver(state.skills_system_version, SKILLS_SCHEMA_VERSION) > 0) {
throw new Error(
`state.yaml version ${state.skills_system_version} is newer than tooling version ${SKILLS_SCHEMA_VERSION}. Update your skills engine.`,
);
}
return state;
}
export function writeState(state: SkillState): void {
const statePath = getStatePath();
fs.mkdirSync(path.dirname(statePath), { recursive: true });
const content = stringify(state, { sortMapEntries: true });
// Write to temp file then atomic rename to prevent corruption on crash
const tmpPath = statePath + '.tmp';
fs.writeFileSync(tmpPath, content, 'utf-8');
fs.renameSync(tmpPath, statePath);
}
export function recordSkillApplication(
skillName: string,
version: string,
fileHashes: Record<string, string>,
structuredOutcomes?: Record<string, unknown>,
): void {
const state = readState();
// Remove previous application of same skill if exists
state.applied_skills = state.applied_skills.filter(
(s) => s.name !== skillName,
);
state.applied_skills.push({
name: skillName,
version,
applied_at: new Date().toISOString(),
file_hashes: fileHashes,
structured_outcomes: structuredOutcomes,
});
writeState(state);
}
export function getAppliedSkills(): AppliedSkill[] {
const state = readState();
return state.applied_skills;
}
export function recordCustomModification(
description: string,
filesModified: string[],
patchFile: string,
): void {
const state = readState();
if (!state.custom_modifications) {
state.custom_modifications = [];
}
const mod: CustomModification = {
description,
applied_at: new Date().toISOString(),
files_modified: filesModified,
patch_file: patchFile,
};
state.custom_modifications.push(mod);
writeState(state);
}
export function getCustomModifications(): CustomModification[] {
const state = readState();
return state.custom_modifications || [];
}
export function computeFileHash(filePath: string): string {
const content = fs.readFileSync(filePath);
return crypto.createHash('sha256').update(content).digest('hex');
}
/**
* Compare two semver strings. Returns negative if a < b, 0 if equal, positive if a > b.
*/
export function compareSemver(a: string, b: string): number {
const partsA = a.split('.').map(Number);
const partsB = b.split('.').map(Number);
for (let i = 0; i < Math.max(partsA.length, partsB.length); i++) {
const diff = (partsA[i] || 0) - (partsB[i] || 0);
if (diff !== 0) return diff;
}
return 0;
}