@routinecrew/routinecode 2.31.77 → 2.31.86
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/README.md +2 -2
- package/bin/cli.sh +23 -0
- package/bin/prompt-vault.dat +1 -0
- package/bin/prompt-vault.js +51 -1
- package/bin/rc-board.js +58 -0
- package/bin/rc-config.js +756 -1
- package/bin/rc-credit-turn.js +2 -1
- package/bin/rc-grant.js +2 -1
- package/bin/rc-login.js +2 -0
- package/bin/rc-map.js +132 -0
- package/bin/rc-privacy.js +200 -0
- package/bin/rc-skills.js +31 -0
- package/bin/rc-team.js +2 -1
- package/bin/setup.js +4 -0
- package/hooks/cc-compat-watch.js +2 -1
- package/hooks/claim-questions.json +40 -0
- package/hooks/hooks-config.json +108 -1
- package/hooks/lib/agent_budget.py +122 -0
- package/hooks/lib/agent_telemetry.py +143 -0
- package/hooks/lib/attest_reader.py +15 -6
- package/hooks/lib/attribution_judge.py +109 -0
- package/hooks/lib/board-golden.json +268 -0
- package/hooks/lib/board.py +503 -0
- package/hooks/lib/board_sync.py +535 -0
- package/hooks/lib/cc-surface.json +1 -1
- package/hooks/lib/claim_structure.py +412 -0
- package/hooks/lib/completion_log.py +12 -5
- package/hooks/lib/config_bash_track.py +114 -28
- package/hooks/lib/config_guard.py +137 -5
- package/hooks/lib/edit_tracker.py +182 -0
- package/hooks/lib/error_line.py +94 -0
- package/hooks/lib/escalation_restore.py +66 -0
- package/hooks/lib/i18n.py +37 -15
- package/hooks/lib/knowledge_items.py +1407 -0
- package/hooks/lib/knowledge_scope.py +123 -0
- package/hooks/lib/known_solution.py +37 -9
- package/hooks/lib/log_compact.py +85 -0
- package/hooks/lib/metacog_signals.py +228 -0
- package/hooks/lib/orch_decision.py +690 -0
- package/hooks/lib/premise-golden.json +96 -0
- package/hooks/lib/presence.py +10 -3
- package/hooks/lib/privacy_log.py +35 -0
- package/hooks/lib/receipt.py +137 -14
- package/hooks/lib/review_gate.py +83 -0
- package/hooks/lib/routine_skill_eval.py +213 -0
- package/hooks/lib/secret_filter.py +2 -1
- package/hooks/lib/skill_drafts.py +188 -0
- package/hooks/lib/sync_manager.py +121 -26
- package/hooks/lib/usage_v2.py +680 -0
- package/hooks/lib/work_kind.py +198 -0
- package/hooks/lib/work_kind_events.py +361 -0
- package/hooks/pending-drainer.sh +28 -0
- package/hooks/post-agent-budget.sh +50 -0
- package/hooks/post-agent-return.sh +89 -3
- package/hooks/post-bash-failure.sh +39 -0
- package/hooks/post-bash-knowledge.sh +15 -34
- package/hooks/post-bash-verify.sh +33 -16
- package/hooks/post-build-check.sh +16 -18
- package/hooks/post-config-context.sh +13 -0
- package/hooks/post-delegation-nudge.sh +12 -1
- package/hooks/post-edit-track.sh +19 -28
- package/hooks/post-orch-decision.sh +35 -0
- package/hooks/post-read-config-context.sh +20 -0
- package/hooks/pre-account-guard.sh +1 -1
- package/hooks/pre-agent-spawn.mjs +2 -1
- package/hooks/pre-agent-spawn.sh +12 -1
- package/hooks/pre-bash-guard.sh +61 -3
- package/hooks/pre-bash-knowledge.sh +46 -0
- package/hooks/pre-credit-guard.sh +1 -1
- package/hooks/pre-edit-board.sh +44 -0
- package/hooks/pre-edit-check.sh +29 -5
- package/hooks/pre-edit-config-gate.sh +1 -1
- package/hooks/pre-edit-domain-gate.sh +23 -22
- package/hooks/pre-mark-complete.sh +32 -4
- package/hooks/pre-read-knowledge-inject.sh +34 -24
- package/hooks/pre-review-gate.sh +17 -0
- package/hooks/recorder-runner.sh +25 -2
- package/hooks/session-start-compact.sh +28 -0
- package/hooks/session-start.sh +167 -19
- package/hooks/skill-knowledge.sh +37 -0
- package/hooks/stop-claim-check.v3.sh +21 -3
- package/hooks/stop-usage-metrics.sh +138 -83
- package/hooks/subagent-stop-usage.sh +25 -0
- package/hooks/user-prompt-submit.sh +10 -4
- package/mcp-db-manager/dist/analyzers/duplicate-detector.js +1 -1
- package/mcp-db-manager/dist/core/model-parser.js +1 -1
- package/mcp-db-manager/dist/core/schema-reader.js +1 -1
- package/mcp-db-manager/dist/executors/migration-executor.js +1 -1
- package/mcp-db-manager/dist/generators/migration-generator.js +1 -1
- package/mcp-db-manager/dist/index.js +1 -1
- package/mcp-db-manager/dist/validators/schema-validator.js +1 -1
- package/mcp-dev-tester/dist/analyzers/auth-diagnoser.js +1 -1
- package/mcp-dev-tester/dist/analyzers/backend-analyzer.js +1 -1
- package/mcp-dev-tester/dist/analyzers/endpoint-diagnoser.js +1 -1
- package/mcp-dev-tester/dist/analyzers/frontend-analyzer.js +1 -1
- package/mcp-dev-tester/dist/analyzers/runtime-diagnoser.js +1 -1
- package/mcp-dev-tester/dist/analyzers/type-comparator.js +1 -1
- package/mcp-dev-tester/dist/analyzers/validation-diagnoser.js +1 -1
- package/mcp-dev-tester/dist/attestation.js +1 -1
- package/mcp-dev-tester/dist/browser/playwright-manager.js +1 -1
- package/mcp-dev-tester/dist/browser/ui-tester.js +1 -1
- package/mcp-dev-tester/dist/config/project-config.js +1 -1
- package/mcp-dev-tester/dist/index.js +1 -1
- package/mcp-dev-tester/dist/testers/api-tester.js +1 -1
- package/mcp-doc-fetcher/dist/index.js +1 -1
- package/mcp-html-renderer/dist/index.js +1 -1
- package/mcp-html-renderer/dist/preview.js +1 -1
- package/mcp-html-renderer/dist/template-engine.js +1 -1
- package/mcp-intelligence/dist/concept-catalog.js +1 -1
- package/mcp-intelligence/dist/concept-server-proxy.js +1 -1
- package/mcp-intelligence/dist/config-auth.js +1 -1
- package/mcp-intelligence/dist/contracts.generated.js +1 -1
- package/mcp-intelligence/dist/domain-templates.js +1 -1
- package/mcp-intelligence/dist/grounding.js +1 -1
- package/mcp-intelligence/dist/handlers.js +1 -1
- package/mcp-intelligence/dist/index.js +1 -1
- package/mcp-intelligence/dist/intelligence-file.js +1 -1
- package/mcp-intelligence/dist/knowledge-critic.js +1 -1
- package/mcp-intelligence/dist/knowledge-guide.js +1 -0
- package/mcp-intelligence/dist/knowledge-handlers.js +1 -1
- package/mcp-intelligence/dist/knowledge-migrate.js +1 -0
- package/mcp-intelligence/dist/knowledge-record.js +1 -0
- package/mcp-intelligence/dist/knowledge-scope.js +1 -0
- package/mcp-intelligence/dist/mention-extractor.js +1 -1
- package/mcp-intelligence/dist/provenance.js +1 -1
- package/mcp-intelligence/dist/sanitize.generated.js +242 -0
- package/mcp-intelligence/dist/semantic-embedder.js +1 -1
- package/mcp-log-watcher/dist/config-auth.js +1 -1
- package/mcp-log-watcher/dist/file-watcher.js +1 -1
- package/mcp-log-watcher/dist/index.js +1 -1
- package/mcp-log-watcher/dist/known-solutions.js +1 -1
- package/mcp-log-watcher/dist/log-store.js +1 -1
- package/mcp-log-watcher/dist/sanitize.generated.js +242 -0
- package/mcp-log-watcher/dist/websocket-server.js +1 -1
- package/mcp-log-watcher/package.json +1 -1
- package/mcp-plan-manager/dist/__tests__/file-ops-knowledge-dir.test.js +1 -1
- package/mcp-plan-manager/dist/__tests__/plan-parser.test.js +1 -1
- package/mcp-plan-manager/dist/file-ops.js +1 -1
- package/mcp-plan-manager/dist/index.js +1 -1
- package/mcp-plan-manager/dist/plan-parser.js +1 -1
- package/mcp-project-context/dist/git-ops.js +1 -1
- package/mcp-project-context/dist/index.js +1 -1
- package/mcp-project-context/dist/project-analysis.js +1 -1
- package/mcp-routinecode/dist/agent-tracker.js +1 -1
- package/mcp-routinecode/dist/analysis-ledger.js +590 -0
- package/mcp-routinecode/dist/attestation.js +1 -1
- package/mcp-routinecode/dist/blast-radius.js +1 -1
- package/mcp-routinecode/dist/board.js +1 -0
- package/mcp-routinecode/dist/build-id.js +1 -0
- package/mcp-routinecode/dist/changeset.js +1 -1
- package/mcp-routinecode/dist/config-auth.js +1 -1
- package/mcp-routinecode/dist/config-map/applied.js +1 -0
- package/mcp-routinecode/dist/config-map/arch-graph.js +1 -1
- package/mcp-routinecode/dist/config-map/architect-store.js +1132 -1
- package/mcp-routinecode/dist/config-map/assign.js +1 -1
- package/mcp-routinecode/dist/config-map/audit-cli.js +1 -1
- package/mcp-routinecode/dist/config-map/audit.js +1 -1
- package/mcp-routinecode/dist/config-map/blocks.js +1 -1
- package/mcp-routinecode/dist/config-map/briefing.js +541 -1
- package/mcp-routinecode/dist/config-map/certify.js +10 -5
- package/mcp-routinecode/dist/config-map/const-use.js +1 -1
- package/mcp-routinecode/dist/config-map/context.js +219 -0
- package/mcp-routinecode/dist/config-map/convention-candidates.js +1 -0
- package/mcp-routinecode/dist/config-map/decisions.js +1 -1
- package/mcp-routinecode/dist/config-map/decls.js +1 -1
- package/mcp-routinecode/dist/config-map/drift.js +1 -1
- package/mcp-routinecode/dist/config-map/dup-safety.js +1 -1
- package/mcp-routinecode/dist/config-map/extract.js +1 -1
- package/mcp-routinecode/dist/config-map/field-contract.js +1 -1
- package/mcp-routinecode/dist/config-map/gate.js +796 -1
- package/mcp-routinecode/dist/config-map/hash.js +1 -1
- package/mcp-routinecode/dist/config-map/ident-norm.js +1 -1
- package/mcp-routinecode/dist/config-map/index-store.js +1051 -1
- package/mcp-routinecode/dist/config-map/light-eval.js +253 -1
- package/mcp-routinecode/dist/config-map/link.js +1 -1
- package/mcp-routinecode/dist/config-map/linked-repos.js +1 -1
- package/mcp-routinecode/dist/config-map/lookup.js +1 -1
- package/mcp-routinecode/dist/config-map/louvain.js +1 -1
- package/mcp-routinecode/dist/config-map/maintenance-cli.js +1 -1
- package/mcp-routinecode/dist/config-map/names.js +1 -1
- package/mcp-routinecode/dist/config-map/post-bash-eval.js +105 -0
- package/mcp-routinecode/dist/config-map/proposals.js +1 -1
- package/mcp-routinecode/dist/config-map/ratchet.js +148 -0
- package/mcp-routinecode/dist/config-map/recheck.js +148 -1
- package/mcp-routinecode/dist/config-map/repo-id.js +1 -1
- package/mcp-routinecode/dist/config-map/route-security.js +1 -1
- package/mcp-routinecode/dist/config-map/rule-import.js +1 -1
- package/mcp-routinecode/dist/config-map/scc.js +1 -1
- package/mcp-routinecode/dist/config-map/shape-eval.js +1 -1
- package/mcp-routinecode/dist/config-map/shape.js +1 -1
- package/mcp-routinecode/dist/config-map/snapshot.js +1 -1
- package/mcp-routinecode/dist/config-map/sole-impl.js +1 -1
- package/mcp-routinecode/dist/config-map/stable-id.js +1 -1
- package/mcp-routinecode/dist/config-map/store.js +1 -1
- package/mcp-routinecode/dist/config-map/swagger-check.js +1 -1
- package/mcp-routinecode/dist/config-map/task-eval.js +369 -1
- package/mcp-routinecode/dist/config-map/templates.js +1 -1
- package/mcp-routinecode/dist/contracts.generated.js +1 -1
- package/mcp-routinecode/dist/coverage.js +1 -1
- package/mcp-routinecode/dist/edit-tracker.js +1 -0
- package/mcp-routinecode/dist/explorer-advisor.js +1 -1
- package/mcp-routinecode/dist/failure-tracker.js +1 -1
- package/mcp-routinecode/dist/file-lock-registry.js +1 -1
- package/mcp-routinecode/dist/file-risk-scorer.js +1 -1
- package/mcp-routinecode/dist/index.js +1 -1
- package/mcp-routinecode/dist/known-solutions.js +1 -1
- package/mcp-routinecode/dist/ledger-miner.js +1 -1
- package/mcp-routinecode/dist/normalize-sig.js +1 -0
- package/mcp-routinecode/dist/observed-draft.js +1 -1
- package/mcp-routinecode/dist/observed-escalation.js +1 -0
- package/mcp-routinecode/dist/pattern-matcher.js +1 -1
- package/mcp-routinecode/dist/route-match.js +1 -1
- package/mcp-routinecode/dist/routines.js +1 -1
- package/mcp-routinecode/dist/rule-engine.js +1 -1
- package/mcp-routinecode/dist/rule-promoter.js +1 -1
- package/mcp-routinecode/dist/sanitize.generated.js +242 -0
- package/mcp-routinecode/dist/session-registry.js +1 -0
- package/mcp-routinecode/dist/skill-pack/sync.js +629 -0
- package/mcp-routinecode/dist/skill-pack/validate.js +278 -0
- package/mcp-routinecode/dist/telemetry-analyzer.js +1 -1
- package/mcp-routinecode/dist/test-runner.js +1 -1
- package/mcp-routinecode/dist/verification.js +1 -1
- package/mcp-routinecode/dist/viral-loop.js +1 -1
- package/mcp-routinecode/package.json +1 -1
- package/package.json +3 -3
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/agents/analyzer.md.sealed +1 -1
- package/plugin/agents/architect.md.sealed +1 -1
- package/plugin/agents/crawler.md.sealed +1 -1
- package/plugin/agents/explorer.md.sealed +1 -1
- package/plugin/agents/implementor.md.sealed +1 -1
- package/plugin/agents/looker.md.sealed +1 -1
- package/plugin/agents/planner.md.sealed +1 -1
- package/plugin/agents/recorder.md.sealed +1 -1
- package/plugin/agents/reviewer.md.sealed +1 -1
- package/plugin/agents/verifier.md.sealed +1 -1
- package/plugin/commands/analyze.md.sealed +1 -1
- package/plugin/commands/plan.md.sealed +1 -1
- package/plugin/commands/rc.md.sealed +1 -1
- package/plugin/commands/receipt.md.sealed +1 -1
- package/plugin/commands/recharge.md.sealed +1 -1
- package/plugin/commands/routines.md.sealed +1 -1
- package/plugin/commands/share.md.sealed +1 -1
- package/plugin/routinecode-prompt.md.sealed +1 -1
|
@@ -0,0 +1,629 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* skill-pack/sync — 디자인 스킬 팩 내려받기·검증·설치 (설계 23 §5, 2 단계).
|
|
3
|
+
*
|
|
4
|
+
* routinecode skills status | on | off | sync (bin/rc-skills.js → main)
|
|
5
|
+
*
|
|
6
|
+
* - 기본 꺼짐: `on` 전에는 내려받지 않는다. 처음 한 번만 안내(state.noticeShown).
|
|
7
|
+
* - 서버: GET {serverUrl}/api/v1/skill-pack/current?clientVersion=V[&have=<sha>] (per-user apiKey), 24시간에 한 번(lastCheckAt).
|
|
8
|
+
* fetch 는 AbortSignal.timeout(4000). 전체 5초 예산이 지나면 쓰기 전 단계는 중단, 교체 중이면 마치고 끝낸다.
|
|
9
|
+
* - 검증: 서명(index-store.verifySkillPackSig, 임베드 레코드 공개키) → 다이제스트 → §3.1 규칙 → format·minClientVersion → 재전송 규칙.
|
|
10
|
+
* 실패하면 아무것도 바꾸지 않고 state.lastError 에 이유.
|
|
11
|
+
* - 로컬 보관: 검증된 팩(서명 포함)을 ~/.routinecode/skill-packs/<sha>.json(0600)에 두고 설치는 항상 보관본에서. 현재 팩 하나만 남긴다.
|
|
12
|
+
* 보관본이 있고 재검증을 통과할 때만 have=<sha>.
|
|
13
|
+
* - 재전송 방지: state.highest[line]={serial,sha}. serial 이 낮거나, 같은 serial 에 다른 sha, revoked sha 면 서명이 맞아도 거부.
|
|
14
|
+
* 같은 (serial, sha) 는 다시 설치할 수 있다(off→on, 폴더 삭제, CLAUDE_CONFIG_DIR 변경, 만료 후 복귀).
|
|
15
|
+
* - 설치: ${CLAUDE_CONFIG_DIR:-~/.claude}/.rc-skillpack/staging-<sha>/ 에 모두 쓴 뒤 스킬마다 기존 → old-<sha>-x, staging → skills/x, old 삭제.
|
|
16
|
+
* state.pending 으로 진행을 남기고 다음 실행이 남은 staging·old 를 정리(되돌림)한 뒤 보관본에서 다시 맞춘다.
|
|
17
|
+
* 각 디렉터리에 .routinecode-managed 표식. 표식 있는 rc-* 만 만들고 바꾸고 지운다(표식 없는 같은 이름은 건너뜀).
|
|
18
|
+
* - 동시 세션: state.json.lock(O_EXCL), 10분 넘은 잠금은 제거. 회수: 응답 revoked 에 설치 sha → 삭제.
|
|
19
|
+
* 만료: 서버 확인에 마지막으로 성공한 지 90일 → 표식 디렉터리·보관본 삭제(apiKey 없어도 로컬 판정).
|
|
20
|
+
* - env: ROUTINECODE_SKILL_PACKS=0 은 동기화만 멈춘다(설치본 유지). 백그라운드 세션(ROUTINECODE_RECORDER·ARCHITECT·MAINTENANCE=1)은 건너뛴다.
|
|
21
|
+
* 하위 프로세스 실행 없음, 글(.md/.txt)만 쓴다. npm 배포본에서 평문 유지(obfuscate.js PLAIN_DIST, §8).
|
|
22
|
+
*/
|
|
23
|
+
import * as fs from 'fs';
|
|
24
|
+
import * as path from 'path';
|
|
25
|
+
import * as crypto from 'crypto';
|
|
26
|
+
import { PKG_ROOT } from '../config-map/cert-lib.js';
|
|
27
|
+
import { homeDir, readSyncConfig, recordPubKeys, verifySkillPackSig } from '../config-map/index-store.js';
|
|
28
|
+
import { packProblem, packDigest, compareVersion, SKILLPACK_FORMAT, SKILL_DIR_RE } from './validate.js';
|
|
29
|
+
const DAY_MS = 86_400_000;
|
|
30
|
+
export const CHECK_INTERVAL_MS = DAY_MS;
|
|
31
|
+
export const EXPIRY_MS = 90 * DAY_MS;
|
|
32
|
+
export const LOCK_STALE_MS = 10 * 60_000;
|
|
33
|
+
export const FETCH_TIMEOUT_MS = 4000;
|
|
34
|
+
export const RUN_BUDGET_MS = 5000;
|
|
35
|
+
export const MARKER = '.routinecode-managed';
|
|
36
|
+
const REVOKED_KEEP = 500;
|
|
37
|
+
const SHA_RE = /^[0-9a-f]{64}$/;
|
|
38
|
+
export const NOTICE_TEXT = 'RoutineCode design skills are available (off by default). Installed skills are visible in every Claude Code session. Turn on: routinecode skills on';
|
|
39
|
+
/** ~/.routinecode/skill-packs(ROUTINECODE_DIR 존중) · ${CLAUDE_CONFIG_DIR:-~/.claude}/skills · …/.rc-skillpack(감시 폴더 밖, 같은 파일시스템) */
|
|
40
|
+
export function skillPackPaths(env = process.env) {
|
|
41
|
+
const home = env.HOME || env.USERPROFILE || homeDir();
|
|
42
|
+
const stateDir = path.join(env.ROUTINECODE_DIR || path.join(home, '.routinecode'), 'skill-packs');
|
|
43
|
+
const configDir = env.CLAUDE_CONFIG_DIR || path.join(home, '.claude');
|
|
44
|
+
const statePath = path.join(stateDir, 'state.json');
|
|
45
|
+
return { stateDir, statePath, lockPath: `${statePath}.lock`, configDir, skillsDir: path.join(configDir, 'skills'), workDir: path.join(configDir, '.rc-skillpack') };
|
|
46
|
+
}
|
|
47
|
+
export function defaultState() {
|
|
48
|
+
return { enabled: false, noticeShown: false, lastCheckAt: null, lastSuccessAt: null, highest: {}, installed: {}, revoked: [], pending: null, lastError: null };
|
|
49
|
+
}
|
|
50
|
+
const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
|
|
51
|
+
const numOrNull = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);
|
|
52
|
+
export function readState(P) {
|
|
53
|
+
const d = defaultState();
|
|
54
|
+
let raw;
|
|
55
|
+
try {
|
|
56
|
+
raw = JSON.parse(fs.readFileSync(P.statePath, 'utf-8'));
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
return d;
|
|
60
|
+
}
|
|
61
|
+
if (!isObj(raw))
|
|
62
|
+
return d;
|
|
63
|
+
const st = {
|
|
64
|
+
enabled: raw.enabled === true,
|
|
65
|
+
noticeShown: raw.noticeShown === true,
|
|
66
|
+
lastCheckAt: numOrNull(raw.lastCheckAt),
|
|
67
|
+
lastSuccessAt: numOrNull(raw.lastSuccessAt),
|
|
68
|
+
highest: {},
|
|
69
|
+
installed: {},
|
|
70
|
+
revoked: Array.isArray(raw.revoked) ? raw.revoked.filter((s) => typeof s === 'string' && SHA_RE.test(s)) : [],
|
|
71
|
+
pending: null,
|
|
72
|
+
lastError: typeof raw.lastError === 'string' ? raw.lastError : null,
|
|
73
|
+
};
|
|
74
|
+
if (isObj(raw.highest))
|
|
75
|
+
for (const [k, v] of Object.entries(raw.highest))
|
|
76
|
+
if (isObj(v) && Number.isSafeInteger(v.serial) && typeof v.sha === 'string' && SHA_RE.test(v.sha))
|
|
77
|
+
st.highest[k] = { serial: v.serial, sha: v.sha };
|
|
78
|
+
if (isObj(raw.installed))
|
|
79
|
+
for (const [k, v] of Object.entries(raw.installed))
|
|
80
|
+
if (isObj(v) && Number.isSafeInteger(v.serial) && typeof v.sha === 'string' && Array.isArray(v.dirs))
|
|
81
|
+
st.installed[k] = { serial: v.serial, sha: v.sha, dirs: v.dirs.filter((x) => typeof x === 'string' && SKILL_DIR_RE.test(x)) };
|
|
82
|
+
if (isObj(raw.pending) && typeof raw.pending.sha === 'string' && SHA_RE.test(raw.pending.sha))
|
|
83
|
+
st.pending = { op: 'install', sha: raw.pending.sha, done: Array.isArray(raw.pending.done) ? raw.pending.done.filter((x) => typeof x === 'string') : [] };
|
|
84
|
+
return st;
|
|
85
|
+
}
|
|
86
|
+
function writeFileAtomic(p, data, mode = 0o600) {
|
|
87
|
+
const tmp = `${p}.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`;
|
|
88
|
+
fs.writeFileSync(tmp, data, { mode });
|
|
89
|
+
fs.renameSync(tmp, p);
|
|
90
|
+
}
|
|
91
|
+
/** 공백 없는 JSON — session-start.sh 가 `"enabled":false` 를 grep 해 node 를 띄우지 않고 건너뛴다 */
|
|
92
|
+
export function writeState(P, st) {
|
|
93
|
+
fs.mkdirSync(P.stateDir, { recursive: true, mode: 0o700 });
|
|
94
|
+
writeFileAtomic(P.statePath, JSON.stringify(st));
|
|
95
|
+
}
|
|
96
|
+
// ── 잠금 ─────────────────────────────────────────────────────────────
|
|
97
|
+
/** 오래된 잠금 판정은 파일 mtime 과 같은 실제 시계로 한다(주입 시계 아님) */
|
|
98
|
+
export function acquireLock(P, now = Date.now()) {
|
|
99
|
+
fs.mkdirSync(P.stateDir, { recursive: true, mode: 0o700 });
|
|
100
|
+
for (let i = 0; i < 2; i++) {
|
|
101
|
+
try {
|
|
102
|
+
const fd = fs.openSync(P.lockPath, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY, 0o600);
|
|
103
|
+
fs.writeSync(fd, String(process.pid));
|
|
104
|
+
fs.closeSync(fd);
|
|
105
|
+
return true;
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
try {
|
|
109
|
+
if (now - fs.statSync(P.lockPath).mtimeMs > LOCK_STALE_MS) {
|
|
110
|
+
fs.unlinkSync(P.lockPath);
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
catch {
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
return false;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return false;
|
|
121
|
+
}
|
|
122
|
+
export function releaseLock(P) {
|
|
123
|
+
try {
|
|
124
|
+
fs.unlinkSync(P.lockPath);
|
|
125
|
+
}
|
|
126
|
+
catch { /* 이미 없음 */ }
|
|
127
|
+
}
|
|
128
|
+
const archivePath = (P, sha) => path.join(P.stateDir, `${sha}.json`);
|
|
129
|
+
/** 서명·다이제스트·규칙·format 재검증을 통과한 보관본만 */
|
|
130
|
+
export function loadArchive(P, sha, keys) {
|
|
131
|
+
if (!SHA_RE.test(sha))
|
|
132
|
+
return null;
|
|
133
|
+
let a;
|
|
134
|
+
try {
|
|
135
|
+
a = JSON.parse(fs.readFileSync(archivePath(P, sha), 'utf-8'));
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
return null;
|
|
139
|
+
}
|
|
140
|
+
if (!isObj(a) || a.sha256 !== sha)
|
|
141
|
+
return null;
|
|
142
|
+
if (!verifySkillPackSig(a.sha256, a.kid, a.sig, keys))
|
|
143
|
+
return null;
|
|
144
|
+
if (!isObj(a.bundle) || a.bundle.sha256 !== sha || packProblem(a.bundle) !== null)
|
|
145
|
+
return null;
|
|
146
|
+
return a;
|
|
147
|
+
}
|
|
148
|
+
function saveArchive(P, a) {
|
|
149
|
+
fs.mkdirSync(P.stateDir, { recursive: true, mode: 0o700 });
|
|
150
|
+
writeFileAtomic(archivePath(P, a.sha256), JSON.stringify(a), 0o600);
|
|
151
|
+
for (const n of fs.readdirSync(P.stateDir)) {
|
|
152
|
+
if (/^[0-9a-f]{64}\.json$/.test(n) && n !== `${a.sha256}.json`) {
|
|
153
|
+
try {
|
|
154
|
+
fs.unlinkSync(path.join(P.stateDir, n));
|
|
155
|
+
}
|
|
156
|
+
catch { /* 무시 */ }
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
function deleteArchives(P, only) {
|
|
161
|
+
let names = [];
|
|
162
|
+
try {
|
|
163
|
+
names = fs.readdirSync(P.stateDir);
|
|
164
|
+
}
|
|
165
|
+
catch {
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
for (const n of names) {
|
|
169
|
+
if (!/^[0-9a-f]{64}\.json$/.test(n))
|
|
170
|
+
continue;
|
|
171
|
+
if (only && n !== `${only}.json`)
|
|
172
|
+
continue;
|
|
173
|
+
try {
|
|
174
|
+
fs.unlinkSync(path.join(P.stateDir, n));
|
|
175
|
+
}
|
|
176
|
+
catch { /* 무시 */ }
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
/** 실제 디렉터리(심볼릭 링크 아님) 안의 표식 — 없거나 형식이 틀리면 null(= 관리 대상 아님) */
|
|
180
|
+
export function readMarker(dir) {
|
|
181
|
+
try {
|
|
182
|
+
if (!fs.lstatSync(dir).isDirectory())
|
|
183
|
+
return null;
|
|
184
|
+
const m = JSON.parse(fs.readFileSync(path.join(dir, MARKER), 'utf-8'));
|
|
185
|
+
return isObj(m) && typeof m.sha256 === 'string' && typeof m.line === 'string' ? m : null;
|
|
186
|
+
}
|
|
187
|
+
catch {
|
|
188
|
+
return null;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
const exists = (p) => { try {
|
|
192
|
+
fs.lstatSync(p);
|
|
193
|
+
return true;
|
|
194
|
+
}
|
|
195
|
+
catch {
|
|
196
|
+
return false;
|
|
197
|
+
} };
|
|
198
|
+
/** skills 안 표식 있는 rc-* 디렉터리 삭제(filter 로 범위 제한). 반환 = 지운 것이 있는지 */
|
|
199
|
+
function removeManaged(P, filter = () => true) {
|
|
200
|
+
let names = [];
|
|
201
|
+
try {
|
|
202
|
+
names = fs.readdirSync(P.skillsDir);
|
|
203
|
+
}
|
|
204
|
+
catch {
|
|
205
|
+
return false;
|
|
206
|
+
}
|
|
207
|
+
let removed = false;
|
|
208
|
+
for (const n of names) {
|
|
209
|
+
if (!SKILL_DIR_RE.test(n))
|
|
210
|
+
continue;
|
|
211
|
+
const d = path.join(P.skillsDir, n);
|
|
212
|
+
const m = readMarker(d);
|
|
213
|
+
if (!m || !filter(m, n))
|
|
214
|
+
continue;
|
|
215
|
+
fs.rmSync(d, { recursive: true, force: true });
|
|
216
|
+
removed = true;
|
|
217
|
+
}
|
|
218
|
+
return removed;
|
|
219
|
+
}
|
|
220
|
+
/** 표식 없는 같은 이름(사용자 소유) — 건너뛴 디렉터리 */
|
|
221
|
+
function unmanagedClashes(P, pack) {
|
|
222
|
+
return pack.skills.map((s) => s.dir).filter((d) => exists(path.join(P.skillsDir, d)) && !readMarker(path.join(P.skillsDir, d)));
|
|
223
|
+
}
|
|
224
|
+
function installedMatches(P, st, pack) {
|
|
225
|
+
const cur = st.installed[pack.line];
|
|
226
|
+
if (!cur || cur.sha !== pack.sha256)
|
|
227
|
+
return false;
|
|
228
|
+
for (const s of pack.skills) {
|
|
229
|
+
const d = path.join(P.skillsDir, s.dir);
|
|
230
|
+
if (!exists(d))
|
|
231
|
+
return false;
|
|
232
|
+
const m = readMarker(d);
|
|
233
|
+
if (m && m.sha256 !== pack.sha256)
|
|
234
|
+
return false;
|
|
235
|
+
}
|
|
236
|
+
return true;
|
|
237
|
+
}
|
|
238
|
+
function installPack(P, st, pack, hooks) {
|
|
239
|
+
const sha = pack.sha256;
|
|
240
|
+
fs.mkdirSync(P.workDir, { recursive: true, mode: 0o700 });
|
|
241
|
+
fs.mkdirSync(P.skillsDir, { recursive: true });
|
|
242
|
+
const staging = path.join(P.workDir, `staging-${sha}`);
|
|
243
|
+
fs.rmSync(staging, { recursive: true, force: true });
|
|
244
|
+
fs.mkdirSync(staging, { recursive: true, mode: 0o700 });
|
|
245
|
+
const marker = { packId: pack.packId, sha256: sha, line: pack.line, serial: pack.serial };
|
|
246
|
+
for (const s of pack.skills) {
|
|
247
|
+
const root = path.join(staging, s.dir);
|
|
248
|
+
for (const [rel, content] of Object.entries(s.files)) {
|
|
249
|
+
const f = path.join(root, rel);
|
|
250
|
+
fs.mkdirSync(path.dirname(f), { recursive: true });
|
|
251
|
+
fs.writeFileSync(f, content, { mode: 0o644 });
|
|
252
|
+
}
|
|
253
|
+
fs.writeFileSync(path.join(root, MARKER), JSON.stringify(marker) + '\n', { mode: 0o644 });
|
|
254
|
+
}
|
|
255
|
+
hooks.onStep?.('staged', '');
|
|
256
|
+
st.pending = { op: 'install', sha, done: [] };
|
|
257
|
+
writeState(P, st);
|
|
258
|
+
const placed = [];
|
|
259
|
+
for (const s of [...pack.skills].sort((a, b) => (a.dir < b.dir ? -1 : 1))) {
|
|
260
|
+
const target = path.join(P.skillsDir, s.dir);
|
|
261
|
+
if (exists(target) && !readMarker(target))
|
|
262
|
+
continue; // 사용자 소유 같은 이름 — 건너뜀
|
|
263
|
+
const old = path.join(P.workDir, `old-${sha}-${s.dir}`);
|
|
264
|
+
if (exists(target)) {
|
|
265
|
+
fs.rmSync(old, { recursive: true, force: true });
|
|
266
|
+
fs.renameSync(target, old);
|
|
267
|
+
hooks.onStep?.('moved-old', s.dir);
|
|
268
|
+
}
|
|
269
|
+
fs.renameSync(path.join(staging, s.dir), target);
|
|
270
|
+
hooks.onStep?.('placed', s.dir);
|
|
271
|
+
fs.rmSync(old, { recursive: true, force: true });
|
|
272
|
+
st.pending.done.push(s.dir);
|
|
273
|
+
placed.push(s.dir);
|
|
274
|
+
writeState(P, st);
|
|
275
|
+
}
|
|
276
|
+
// 같은 line 의 이전 팩에만 있던 관리 디렉터리 정리
|
|
277
|
+
const keep = new Set(pack.skills.map((s) => s.dir));
|
|
278
|
+
removeManaged(P, (m, dir) => m.line === pack.line && !keep.has(dir));
|
|
279
|
+
fs.rmSync(staging, { recursive: true, force: true });
|
|
280
|
+
st.installed[pack.line] = { serial: pack.serial, sha, dirs: placed };
|
|
281
|
+
st.pending = null;
|
|
282
|
+
writeState(P, st);
|
|
283
|
+
return placed;
|
|
284
|
+
}
|
|
285
|
+
/** 중단된 설치 정리 — old-* 는 자리가 비었으면 되돌리고 아니면 삭제, staging-* 삭제. 이후 reconcile 이 보관본에서 다시 맞춘다 */
|
|
286
|
+
function recoverPending(P, st) {
|
|
287
|
+
let changed = false;
|
|
288
|
+
let names = [];
|
|
289
|
+
try {
|
|
290
|
+
names = fs.readdirSync(P.workDir);
|
|
291
|
+
}
|
|
292
|
+
catch {
|
|
293
|
+
names = [];
|
|
294
|
+
}
|
|
295
|
+
for (const n of names) {
|
|
296
|
+
const full = path.join(P.workDir, n);
|
|
297
|
+
const m = /^old-[0-9a-f]{64}-(rc-[a-z0-9-]{1,61})$/.exec(n);
|
|
298
|
+
if (m) {
|
|
299
|
+
const target = path.join(P.skillsDir, m[1]);
|
|
300
|
+
if (!exists(target)) {
|
|
301
|
+
fs.mkdirSync(P.skillsDir, { recursive: true });
|
|
302
|
+
fs.renameSync(full, target);
|
|
303
|
+
changed = true;
|
|
304
|
+
}
|
|
305
|
+
else
|
|
306
|
+
fs.rmSync(full, { recursive: true, force: true });
|
|
307
|
+
}
|
|
308
|
+
else if (/^staging-[0-9a-f]{64}$/.test(n)) {
|
|
309
|
+
fs.rmSync(full, { recursive: true, force: true });
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
for (const line of Object.keys(st.installed))
|
|
313
|
+
if (st.installed[line].sha === st.pending?.sha)
|
|
314
|
+
delete st.installed[line];
|
|
315
|
+
st.pending = null;
|
|
316
|
+
writeState(P, st);
|
|
317
|
+
return changed;
|
|
318
|
+
}
|
|
319
|
+
function clientVersionOf(o) {
|
|
320
|
+
if (o.clientVersion)
|
|
321
|
+
return o.clientVersion;
|
|
322
|
+
try {
|
|
323
|
+
return String(JSON.parse(fs.readFileSync(path.join(PKG_ROOT, 'package.json'), 'utf-8')).version || '0.0.0');
|
|
324
|
+
}
|
|
325
|
+
catch {
|
|
326
|
+
return '0.0.0';
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
async function fetchCurrent(cfg, version, have, o) {
|
|
330
|
+
const f = o.fetchImpl ?? globalThis.fetch;
|
|
331
|
+
if (typeof f !== 'function')
|
|
332
|
+
return { status: 0, data: null };
|
|
333
|
+
try {
|
|
334
|
+
const q = `?clientVersion=${encodeURIComponent(version)}${have ? `&have=${have}` : ''}`;
|
|
335
|
+
const r = await f(`${cfg.serverUrl}/api/v1/skill-pack/current${q}`, {
|
|
336
|
+
method: 'GET', headers: { Authorization: 'Bearer ' + cfg.apiKey, Accept: 'application/json' }, signal: AbortSignal.timeout(o.fetchTimeoutMs ?? FETCH_TIMEOUT_MS),
|
|
337
|
+
});
|
|
338
|
+
let parsed = null;
|
|
339
|
+
try {
|
|
340
|
+
parsed = JSON.parse(await r.text());
|
|
341
|
+
}
|
|
342
|
+
catch {
|
|
343
|
+
parsed = null;
|
|
344
|
+
}
|
|
345
|
+
return { status: r.status, data: isObj(parsed) && 'data' in parsed ? parsed.data : parsed };
|
|
346
|
+
}
|
|
347
|
+
catch {
|
|
348
|
+
return { status: 0, data: null };
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
/** 받은 팩 검증 — 서명 → 다이제스트 → 규칙 → format·minClientVersion → 재전송. 실패 = 사유 문자열 */
|
|
352
|
+
export function verifyIncoming(d, keys, st, clientVersion) {
|
|
353
|
+
const { sha256, kid, sig, bundle } = d;
|
|
354
|
+
if (!verifySkillPackSig(sha256, kid, sig, keys))
|
|
355
|
+
return keys ? 'bad-signature' : 'no-pubkeys';
|
|
356
|
+
if (!isObj(bundle) || bundle.sha256 !== sha256)
|
|
357
|
+
return 'digest-mismatch';
|
|
358
|
+
if (bundle.format !== SKILLPACK_FORMAT)
|
|
359
|
+
return `update-needed:format-${String(bundle.format)}`;
|
|
360
|
+
let digest = '';
|
|
361
|
+
try {
|
|
362
|
+
digest = packDigest(bundle);
|
|
363
|
+
}
|
|
364
|
+
catch {
|
|
365
|
+
return 'invalid:malformed';
|
|
366
|
+
}
|
|
367
|
+
if (digest !== sha256)
|
|
368
|
+
return 'digest-mismatch';
|
|
369
|
+
const problem = packProblem(bundle);
|
|
370
|
+
if (problem)
|
|
371
|
+
return `invalid:${problem}`;
|
|
372
|
+
const pack = bundle;
|
|
373
|
+
if (compareVersion(clientVersion, pack.minClientVersion) < 0)
|
|
374
|
+
return `update-needed:client-${pack.minClientVersion}`;
|
|
375
|
+
if (st.revoked.includes(pack.sha256))
|
|
376
|
+
return 'replay:revoked';
|
|
377
|
+
const hi = st.highest[pack.line];
|
|
378
|
+
if (hi && pack.serial < hi.serial)
|
|
379
|
+
return 'replay:lower-serial';
|
|
380
|
+
if (hi && pack.serial === hi.serial && pack.sha256 !== hi.sha)
|
|
381
|
+
return 'replay:serial-sha-mismatch';
|
|
382
|
+
return { sha256: pack.sha256, kid: kid, sig: sig, bundle: pack };
|
|
383
|
+
}
|
|
384
|
+
export const isBackgroundSession = (env) => env.ROUTINECODE_RECORDER === '1' || env.ROUTINECODE_ARCHITECT === '1' || env.ROUTINECODE_MAINTENANCE === '1';
|
|
385
|
+
/** 동기화 1회 — 절대 throw 하지 않는다 */
|
|
386
|
+
export async function runSync(o = {}) {
|
|
387
|
+
const env = o.env ?? process.env;
|
|
388
|
+
if (isBackgroundSession(env))
|
|
389
|
+
return { code: 'skipped' };
|
|
390
|
+
const P = o.paths ?? skillPackPaths(env);
|
|
391
|
+
const nowFn = o.now ?? Date.now;
|
|
392
|
+
const deadline = Date.now() + (o.budgetMs ?? RUN_BUDGET_MS);
|
|
393
|
+
let st;
|
|
394
|
+
try {
|
|
395
|
+
st = readState(P);
|
|
396
|
+
if (!st.enabled) {
|
|
397
|
+
if (!st.noticeShown) {
|
|
398
|
+
st.noticeShown = true;
|
|
399
|
+
writeState(P, st);
|
|
400
|
+
return { code: 'notice', message: NOTICE_TEXT };
|
|
401
|
+
}
|
|
402
|
+
return { code: 'disabled' };
|
|
403
|
+
}
|
|
404
|
+
if (env.ROUTINECODE_SKILL_PACKS === '0')
|
|
405
|
+
return { code: 'paused' };
|
|
406
|
+
if (!acquireLock(P))
|
|
407
|
+
return { code: 'locked' };
|
|
408
|
+
}
|
|
409
|
+
catch (e) {
|
|
410
|
+
return { code: 'error', message: String(e?.message ?? e).slice(0, 120) };
|
|
411
|
+
}
|
|
412
|
+
let changed = false;
|
|
413
|
+
try {
|
|
414
|
+
st = readState(P); // 잠금 안에서 다시 읽는다
|
|
415
|
+
const now = nowFn();
|
|
416
|
+
const keys = o.pubKeys ?? recordPubKeys();
|
|
417
|
+
if (st.pending)
|
|
418
|
+
changed = recoverPending(P, st) || changed;
|
|
419
|
+
// 만료 — 로컬만으로 판정(apiKey 없어도)
|
|
420
|
+
if (st.lastSuccessAt !== null && now - st.lastSuccessAt > EXPIRY_MS) {
|
|
421
|
+
const hadAny = Object.keys(st.installed).length > 0;
|
|
422
|
+
changed = removeManaged(P) || changed;
|
|
423
|
+
deleteArchives(P);
|
|
424
|
+
st.installed = {};
|
|
425
|
+
if (hadAny)
|
|
426
|
+
st.lastError = 'expired';
|
|
427
|
+
}
|
|
428
|
+
// 서버 확인(24시간 주기)
|
|
429
|
+
const cfg = o.syncConfig !== undefined ? o.syncConfig : readSyncConfig();
|
|
430
|
+
const due = o.force === true || st.lastCheckAt === null || now - st.lastCheckAt >= CHECK_INTERVAL_MS || now < st.lastCheckAt;
|
|
431
|
+
if (cfg && due) {
|
|
432
|
+
if (!keys) {
|
|
433
|
+
st.lastError = 'no-pubkeys';
|
|
434
|
+
}
|
|
435
|
+
else {
|
|
436
|
+
let have = null;
|
|
437
|
+
for (const h of Object.values(st.highest))
|
|
438
|
+
if (loadArchive(P, h.sha, keys)) {
|
|
439
|
+
have = h.sha;
|
|
440
|
+
break;
|
|
441
|
+
}
|
|
442
|
+
st.lastCheckAt = now;
|
|
443
|
+
const r = await fetchCurrent(cfg, clientVersionOf(o), have, o);
|
|
444
|
+
const d = r.data;
|
|
445
|
+
if (r.status !== 200 || !isObj(d)) {
|
|
446
|
+
st.lastError = r.status === 0 ? 'offline' : `http-${r.status}`;
|
|
447
|
+
}
|
|
448
|
+
else {
|
|
449
|
+
if (Array.isArray(d.revoked)) {
|
|
450
|
+
const add = d.revoked.filter((s) => typeof s === 'string' && SHA_RE.test(s));
|
|
451
|
+
st.revoked = Array.from(new Set([...st.revoked, ...add])).slice(-REVOKED_KEEP);
|
|
452
|
+
}
|
|
453
|
+
if (d.status === 'pack') {
|
|
454
|
+
const v = verifyIncoming(d, keys, st, clientVersionOf(o));
|
|
455
|
+
if (typeof v === 'string') {
|
|
456
|
+
st.lastError = v;
|
|
457
|
+
}
|
|
458
|
+
else {
|
|
459
|
+
saveArchive(P, v);
|
|
460
|
+
st.highest[v.bundle.line] = { serial: v.bundle.serial, sha: v.sha256 };
|
|
461
|
+
st.lastSuccessAt = now;
|
|
462
|
+
st.lastError = null;
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
else if (d.status === 'unchanged') {
|
|
466
|
+
if (have && (d.sha256 === undefined || d.sha256 === have)) {
|
|
467
|
+
st.lastSuccessAt = now;
|
|
468
|
+
st.lastError = null;
|
|
469
|
+
}
|
|
470
|
+
else
|
|
471
|
+
st.lastError = 'unchanged-without-have';
|
|
472
|
+
}
|
|
473
|
+
else if (d.status === 'none') {
|
|
474
|
+
st.lastError = null; // 설치본 유지 — 만료 시계는 갱신하지 않는다(§5.2 표)
|
|
475
|
+
}
|
|
476
|
+
else {
|
|
477
|
+
st.lastError = 'malformed';
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
// 회수
|
|
483
|
+
for (const sha of st.revoked) {
|
|
484
|
+
for (const line of Object.keys(st.installed))
|
|
485
|
+
if (st.installed[line].sha === sha)
|
|
486
|
+
delete st.installed[line];
|
|
487
|
+
if (removeManaged(P, (m) => m.sha256 === sha))
|
|
488
|
+
changed = true;
|
|
489
|
+
deleteArchives(P, sha);
|
|
490
|
+
}
|
|
491
|
+
// 보관본과 설치본 맞추기(폴더 삭제·CLAUDE_CONFIG_DIR 변경·off→on·중단 복구)
|
|
492
|
+
for (const h of Object.values(st.highest)) {
|
|
493
|
+
if (st.revoked.includes(h.sha))
|
|
494
|
+
continue;
|
|
495
|
+
const a = loadArchive(P, h.sha, keys);
|
|
496
|
+
if (!a)
|
|
497
|
+
continue;
|
|
498
|
+
if (installedMatches(P, st, a.bundle))
|
|
499
|
+
continue;
|
|
500
|
+
if (Date.now() > deadline) {
|
|
501
|
+
st.lastError = 'budget-exceeded';
|
|
502
|
+
break;
|
|
503
|
+
} // 쓰기 전 단계 — 다음 실행이 이어 한다
|
|
504
|
+
installPack(P, st, a.bundle, o);
|
|
505
|
+
changed = true;
|
|
506
|
+
}
|
|
507
|
+
writeState(P, st);
|
|
508
|
+
return { code: changed ? 'changed' : 'unchanged' };
|
|
509
|
+
}
|
|
510
|
+
catch (e) {
|
|
511
|
+
try {
|
|
512
|
+
st = readState(P);
|
|
513
|
+
st.lastError = 'error:' + String(e?.message ?? e).slice(0, 120);
|
|
514
|
+
writeState(P, st);
|
|
515
|
+
}
|
|
516
|
+
catch { /* 무시 */ }
|
|
517
|
+
return { code: changed ? 'changed' : 'error', message: String(e?.message ?? e).slice(0, 120) };
|
|
518
|
+
}
|
|
519
|
+
finally {
|
|
520
|
+
releaseLock(P);
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
// ── 사용자 제어 ─────────────────────────────────────────────────────
|
|
524
|
+
export async function turnOn(o = {}) {
|
|
525
|
+
const env = o.env ?? process.env;
|
|
526
|
+
const P = o.paths ?? skillPackPaths(env);
|
|
527
|
+
const st = readState(P);
|
|
528
|
+
st.enabled = true;
|
|
529
|
+
st.noticeShown = true;
|
|
530
|
+
writeState(P, st);
|
|
531
|
+
fs.mkdirSync(P.skillsDir, { recursive: true }); // 세션 시작 때 없던 skills 폴더는 감시되지 않는다(F9) — 먼저 만든다
|
|
532
|
+
return runSync({ ...o, paths: P, env, force: true });
|
|
533
|
+
}
|
|
534
|
+
export function turnOff(o = {}) {
|
|
535
|
+
const env = o.env ?? process.env;
|
|
536
|
+
const P = o.paths ?? skillPackPaths(env);
|
|
537
|
+
if (!acquireLock(P))
|
|
538
|
+
return { removed: false, locked: true };
|
|
539
|
+
try {
|
|
540
|
+
const st = readState(P);
|
|
541
|
+
const removed = removeManaged(P);
|
|
542
|
+
st.installed = {};
|
|
543
|
+
st.enabled = false;
|
|
544
|
+
st.noticeShown = true;
|
|
545
|
+
writeState(P, st);
|
|
546
|
+
return { removed, locked: false };
|
|
547
|
+
}
|
|
548
|
+
finally {
|
|
549
|
+
releaseLock(P);
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
export function statusLines(o = {}) {
|
|
553
|
+
const env = o.env ?? process.env;
|
|
554
|
+
const P = o.paths ?? skillPackPaths(env);
|
|
555
|
+
const st = readState(P);
|
|
556
|
+
const iso = (t) => (t === null ? '-' : new Date(t).toISOString());
|
|
557
|
+
const out = [
|
|
558
|
+
`design skills: ${st.enabled ? 'on' : 'off'}${env.ROUTINECODE_SKILL_PACKS === '0' ? ' (sync paused: ROUTINECODE_SKILL_PACKS=0)' : ''}`,
|
|
559
|
+
`skills folder: ${P.skillsDir}`,
|
|
560
|
+
];
|
|
561
|
+
const lines = Object.keys(st.installed);
|
|
562
|
+
if (!lines.length)
|
|
563
|
+
out.push('installed: none');
|
|
564
|
+
for (const line of lines) {
|
|
565
|
+
const i = st.installed[line];
|
|
566
|
+
out.push(`installed [${line}]: serial ${i.serial}, sha ${i.sha.slice(0, 12)}…, ${i.dirs.join(', ') || '(no dirs)'}`);
|
|
567
|
+
}
|
|
568
|
+
for (const [line, h] of Object.entries(st.highest)) {
|
|
569
|
+
try {
|
|
570
|
+
const a = JSON.parse(fs.readFileSync(path.join(P.stateDir, `${h.sha}.json`), 'utf-8'));
|
|
571
|
+
out.push(`pack [${line}]: ${a.bundle.packId} v${a.bundle.version} (valid ${a.bundle.validFrom} ~ ${a.bundle.validTo})`);
|
|
572
|
+
const clash = unmanagedClashes(P, a.bundle);
|
|
573
|
+
if (clash.length)
|
|
574
|
+
out.push(`skipped (your own folders with the same name): ${clash.join(', ')}`);
|
|
575
|
+
}
|
|
576
|
+
catch { /* 보관본 없음 */ }
|
|
577
|
+
}
|
|
578
|
+
out.push(`last check: ${iso(st.lastCheckAt)}, last success: ${iso(st.lastSuccessAt)}`);
|
|
579
|
+
if (st.lastSuccessAt !== null && lines.length)
|
|
580
|
+
out.push(`expires if offline until: ${iso(st.lastSuccessAt + EXPIRY_MS)}`);
|
|
581
|
+
if (st.lastError)
|
|
582
|
+
out.push(`last error: ${st.lastError}`);
|
|
583
|
+
if (st.lastError?.startsWith('update-needed'))
|
|
584
|
+
out.push('update needed: a newer RoutineCode is required for the latest design skills (npm i -g @routinecrew/routinecode)');
|
|
585
|
+
return out;
|
|
586
|
+
}
|
|
587
|
+
const USAGE = 'usage: routinecode skills status | on | off | sync\n';
|
|
588
|
+
export async function main(argv, o = {}) {
|
|
589
|
+
const out = (s) => process.stdout.write(s + '\n');
|
|
590
|
+
switch (argv[0] ?? 'status') {
|
|
591
|
+
case 'status':
|
|
592
|
+
for (const l of statusLines(o))
|
|
593
|
+
out(l);
|
|
594
|
+
return 0;
|
|
595
|
+
case 'on': {
|
|
596
|
+
const r = await turnOn(o);
|
|
597
|
+
out(r.code === 'changed' ? 'Design skills installed.' : 'Design skills turned on.');
|
|
598
|
+
if (r.code === 'error' || r.code === 'locked')
|
|
599
|
+
out(`(sync: ${r.code}${r.message ? ' ' + r.message : ''} — will retry at the next session start)`);
|
|
600
|
+
for (const l of statusLines(o))
|
|
601
|
+
out(' ' + l);
|
|
602
|
+
if ((o.env ?? process.env).CLAUDECODE === '1' || r.code === 'changed')
|
|
603
|
+
out('If a Claude Code session is already open, run /reload-skills in it to load the skills.');
|
|
604
|
+
return 0;
|
|
605
|
+
}
|
|
606
|
+
case 'off': {
|
|
607
|
+
const r = turnOff(o);
|
|
608
|
+
out(r.locked ? 'Another session is updating the skills — try again in a moment.' : `Design skills turned off${r.removed ? ' and removed' : ''}.`);
|
|
609
|
+
return r.locked ? 1 : 0;
|
|
610
|
+
}
|
|
611
|
+
case 'sync': {
|
|
612
|
+
// session-start.sh 가 첫 줄을 읽는다: changed → reloadSkills, notice → 둘째 줄 안내
|
|
613
|
+
const r = await runSync(o);
|
|
614
|
+
out(r.code);
|
|
615
|
+
if (r.code === 'notice' && r.message)
|
|
616
|
+
out(r.message);
|
|
617
|
+
return 0;
|
|
618
|
+
}
|
|
619
|
+
default:
|
|
620
|
+
process.stderr.write(USAGE);
|
|
621
|
+
return 2;
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
if (process.argv[1] && /skill-pack[\\/]sync\.js$/.test(process.argv[1])) {
|
|
625
|
+
main(process.argv.slice(2)).then((code) => { process.exitCode = code; }).catch((e) => {
|
|
626
|
+
process.stderr.write(`skill-pack: ${e?.message ?? e}\n`);
|
|
627
|
+
process.exitCode = 0;
|
|
628
|
+
});
|
|
629
|
+
}
|