@routinecrew/routinecode 2.31.71 → 2.31.77
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/bin/prompt-vault.js +1 -1
- package/bin/rc-config.js +1 -1
- package/bin/rc-credit-turn.js +1 -1
- package/bin/rc-grant.js +1 -1
- package/bin/rc-team.js +1 -1
- package/hooks/cc-compat-watch.js +1 -1
- package/hooks/maintenance-runner.sh +5 -0
- package/hooks/pre-agent-spawn.mjs +1 -1
- 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-handlers.js +1 -1
- package/mcp-intelligence/dist/mention-extractor.js +1 -1
- package/mcp-intelligence/dist/provenance.js +1 -1
- 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/websocket-server.js +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/attestation.js +1 -1
- package/mcp-routinecode/dist/blast-radius.js +1 -1
- package/mcp-routinecode/dist/changeset.js +1 -1
- package/mcp-routinecode/dist/config-auth.js +1 -1
- package/mcp-routinecode/dist/config-map/arch-graph.js +1 -1
- package/mcp-routinecode/dist/config-map/architect-store.js +1 -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 -0
- package/mcp-routinecode/dist/config-map/briefing.js +1 -1
- package/mcp-routinecode/dist/config-map/cert-gate.js +346 -0
- package/mcp-routinecode/dist/config-map/cert-lib.js +363 -0
- package/mcp-routinecode/dist/config-map/cert-wiring.js +266 -0
- package/mcp-routinecode/dist/config-map/certify.js +240 -0
- package/mcp-routinecode/dist/config-map/const-use.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 -0
- package/mcp-routinecode/dist/config-map/dup-safety.js +1 -0
- package/mcp-routinecode/dist/config-map/extract.js +1 -1
- package/mcp-routinecode/dist/config-map/field-contract.js +1 -0
- package/mcp-routinecode/dist/config-map/gate.js +1 -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 +1 -1
- package/mcp-routinecode/dist/config-map/light-eval.js +1 -1
- package/mcp-routinecode/dist/config-map/link.js +1 -1
- package/mcp-routinecode/dist/config-map/linked-repos.js +1 -0
- 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/proposals.js +1 -1
- package/mcp-routinecode/dist/config-map/recheck.js +1 -1
- package/mcp-routinecode/dist/config-map/repo-id.js +1 -1
- package/mcp-routinecode/dist/config-map/route-security.js +1 -0
- 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 -0
- 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 -0
- package/mcp-routinecode/dist/config-map/task-eval.js +1 -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/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/observed-draft.js +1 -1
- 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/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/package.json +8 -2
- 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
- package/hooks/lib/tests/test_config_bash_track.py +0 -189
- package/hooks/lib/tests/test_maintenance_sync.py +0 -190
- package/hooks/lib/tests/test_w1_core.py +0 -441
|
@@ -0,0 +1,363 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* config-map/cert-lib — 진단 증명서 lib(평문 TCB: front-ts·facts·nir·conventions·kernel.mjs·kernel.py·front_py·nir.py) 위치 해석
|
|
3
|
+
* (설계 14 §11.1 "배포 차단 원인과 증명서 lib 서버 전달").
|
|
4
|
+
*
|
|
5
|
+
* npm 자동 심사가 cert lib 이 든 버전(2.31.68~74)을 전부 차단했다 → npm 배포본에서 hooks/lib/cert 를 빼고 knowledge 서버가 전달한다.
|
|
6
|
+
* 1) 패키지 안에 hooks/lib/cert 가 있으면(개발·레포 체크아웃) 그것을 쓴다.
|
|
7
|
+
* 2) 없으면 GET /api/v1/cert-lib/current?clientVersion=V[&have=<sha>] → {sha256, kid, sig, files?}
|
|
8
|
+
* - 서명 검증: 임베드 레코드 공개키 목록(index-store.recordPubKeys — embed-pubkey 가 채우는 그 목록)으로
|
|
9
|
+
* "rc-certlib-v1\n"+sha256 (도메인 분리 — 결정 레코드 claims 서명과 혼동 불가)
|
|
10
|
+
* - 파일 검증: 파일 이름 화이트리스트 + bundleDigest(files) === sha256
|
|
11
|
+
* - 설치: <cacheRoot>/<sha256>/hooks/lib/cert/ (디렉터리 0700, 파일 0600) — front-ts 가 PKG_ROOT=HERE/../../.. 에서
|
|
12
|
+
* ts-morph·typescript 를 찾으므로 <sha256>/node_modules·<sha256>/mcp-routinecode/node_modules 를 패키지의 같은 경로로 링크.
|
|
13
|
+
* 3) 오프라인이면 같은 클라 버전으로 받아 둔 검증본(current.json 포인터)을 **재검증 후** 쓴다.
|
|
14
|
+
* 어떤 실패(오프라인+캐시 없음·인증 없음·서명 불일치·파일 변조)도 throw 하지 않고 {dir:null, reason} — 호출측은 증명서 없음(보류)으로 처리한다.
|
|
15
|
+
* 검증 안 된 코드로의 폴백은 없다(정밀도 규칙: unavailable = abstain).
|
|
16
|
+
*/
|
|
17
|
+
import * as fs from 'fs';
|
|
18
|
+
import * as path from 'path';
|
|
19
|
+
import * as crypto from 'crypto';
|
|
20
|
+
import { fileURLToPath } from 'url';
|
|
21
|
+
import { homeDir, readSyncConfig, recordPubKeys, verifyCertLibSig } from './index-store.js';
|
|
22
|
+
export const PKG_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', '..');
|
|
23
|
+
/** 패키지 안 평문 TCB 위치(개발·레포 체크아웃). npm 배포본에는 없다 */
|
|
24
|
+
export const PKG_CERT_DIR = path.join(PKG_ROOT, 'hooks', 'lib', 'cert');
|
|
25
|
+
/** 번들 파일 이름 — 평평한 이름만(경로 구분자·상위 이동 불가), .mjs/.py 만 */
|
|
26
|
+
export const CERT_LIB_NAME_RE = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,63}\.(?:mjs|py)$/;
|
|
27
|
+
/** 있어야 하는 파일(certify 가 import 하는 셋) */
|
|
28
|
+
export const CERT_LIB_REQUIRED = ['facts.mjs', 'front-ts.mjs', 'kernel.mjs', 'nir.mjs'];
|
|
29
|
+
export const CERT_LIB_MAX_FILES = 32;
|
|
30
|
+
export const CERT_LIB_MAX_FILE_BYTES = 4 * 1024 * 1024;
|
|
31
|
+
export const CERT_LIB_MAX_TOTAL_BYTES = 12 * 1024 * 1024;
|
|
32
|
+
const SHA_RE = /^[0-9a-f]{64}$/;
|
|
33
|
+
const sha256Hex = (s) => crypto.createHash('sha256').update(s).digest('hex');
|
|
34
|
+
/**
|
|
35
|
+
* 번들 다이제스트 — 이름 정렬 순서로 `name\n sha256(content utf8)\n` 를 이어 붙인 문자열의 sha256.
|
|
36
|
+
* 빌드 스크립트(scripts/build-cert-bundle.mjs)·서버(knowledge cert-lib.service.bundleDigest)와 같은 정의(골든 벡터 테스트로 동치 확인).
|
|
37
|
+
*/
|
|
38
|
+
export function bundleDigest(files) {
|
|
39
|
+
const names = Object.keys(files).sort();
|
|
40
|
+
return sha256Hex(names.map(n => `${n}\n${sha256Hex(Buffer.from(files[n], 'utf8'))}\n`).join(''));
|
|
41
|
+
}
|
|
42
|
+
/** 번들 파일 집합 형식 검사 — 위반 사유 또는 null */
|
|
43
|
+
export function bundleFilesProblem(files) {
|
|
44
|
+
if (!files || typeof files !== 'object' || Array.isArray(files))
|
|
45
|
+
return 'files-not-object';
|
|
46
|
+
const o = files;
|
|
47
|
+
const names = Object.keys(o);
|
|
48
|
+
if (!names.length || names.length > CERT_LIB_MAX_FILES)
|
|
49
|
+
return 'files-count';
|
|
50
|
+
let total = 0;
|
|
51
|
+
for (const n of names) {
|
|
52
|
+
if (!CERT_LIB_NAME_RE.test(n))
|
|
53
|
+
return 'file-name';
|
|
54
|
+
const v = o[n];
|
|
55
|
+
if (typeof v !== 'string')
|
|
56
|
+
return 'file-content';
|
|
57
|
+
const len = Buffer.byteLength(v, 'utf8');
|
|
58
|
+
if (len > CERT_LIB_MAX_FILE_BYTES)
|
|
59
|
+
return 'file-size';
|
|
60
|
+
total += len;
|
|
61
|
+
}
|
|
62
|
+
if (total > CERT_LIB_MAX_TOTAL_BYTES)
|
|
63
|
+
return 'total-size';
|
|
64
|
+
for (const r of CERT_LIB_REQUIRED)
|
|
65
|
+
if (!(r in o))
|
|
66
|
+
return `missing:${r}`;
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
export function certLibCacheRoot() {
|
|
70
|
+
return process.env.ROUTINECODE_CERT_LIB_DIR || path.join(process.env.ROUTINECODE_DIR || path.join(homeDir(), '.routinecode'), 'cert-lib');
|
|
71
|
+
}
|
|
72
|
+
function clientVersionOf(o) {
|
|
73
|
+
if (o.clientVersion)
|
|
74
|
+
return o.clientVersion;
|
|
75
|
+
try {
|
|
76
|
+
return String(JSON.parse(fs.readFileSync(path.join(o.pkgRoot ?? PKG_ROOT, 'package.json'), 'utf-8')).version || '0.0.0');
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
return '0.0.0';
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
function hasPkgLib(dir) {
|
|
83
|
+
return CERT_LIB_REQUIRED.every(f => fs.existsSync(path.join(dir, f)));
|
|
84
|
+
}
|
|
85
|
+
const pointerPath = (root) => path.join(root, 'current.json');
|
|
86
|
+
const libDirOf = (root, sha) => path.join(root, sha, 'hooks', 'lib', 'cert');
|
|
87
|
+
function readJsonSafe(p) {
|
|
88
|
+
try {
|
|
89
|
+
return JSON.parse(fs.readFileSync(p, 'utf-8'));
|
|
90
|
+
}
|
|
91
|
+
catch {
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
function writeFileAtomic(p, data, mode = 0o600) {
|
|
96
|
+
const tmp = `${p}.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`;
|
|
97
|
+
fs.writeFileSync(tmp, data, { mode });
|
|
98
|
+
fs.renameSync(tmp, p);
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* <sha>/node_modules·<sha>/mcp-routinecode/node_modules → 패키지의 같은 경로(있을 때만). front-ts.loadTs 의 두 해석 기준
|
|
102
|
+
* (PKG_ROOT/package.json·PKG_ROOT/mcp-routinecode/package.json)이 패키지에서와 같은 ts-morph·typescript 를 찾게 한다.
|
|
103
|
+
*/
|
|
104
|
+
function linkNodeModules(shaDir, pkgRoot) {
|
|
105
|
+
const pairs = [
|
|
106
|
+
[path.join(shaDir, 'node_modules'), path.join(pkgRoot, 'node_modules')],
|
|
107
|
+
[path.join(shaDir, 'mcp-routinecode', 'node_modules'), path.join(pkgRoot, 'mcp-routinecode', 'node_modules')],
|
|
108
|
+
];
|
|
109
|
+
for (const [link, target] of pairs) {
|
|
110
|
+
try {
|
|
111
|
+
if (!fs.existsSync(target)) {
|
|
112
|
+
try {
|
|
113
|
+
fs.rmSync(link, { force: true, recursive: false });
|
|
114
|
+
}
|
|
115
|
+
catch { /* 없음 */ }
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
let cur = null;
|
|
119
|
+
try {
|
|
120
|
+
cur = fs.readlinkSync(link);
|
|
121
|
+
}
|
|
122
|
+
catch {
|
|
123
|
+
cur = null;
|
|
124
|
+
}
|
|
125
|
+
if (cur === target)
|
|
126
|
+
continue;
|
|
127
|
+
try {
|
|
128
|
+
fs.unlinkSync(link);
|
|
129
|
+
}
|
|
130
|
+
catch { /* 없음 */ }
|
|
131
|
+
fs.mkdirSync(path.dirname(link), { recursive: true, mode: 0o700 });
|
|
132
|
+
fs.symlinkSync(target, link, 'dir');
|
|
133
|
+
}
|
|
134
|
+
catch { /* 링크 실패 = loadTs 실패 → certify 가 보류로 처리 */ }
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* 서명 없이 번들 파일을 <root>/<sha>/hooks/lib/cert 에 설치 — 다이제스트 일치는 확인한다(빌드 스크립트의 함정 시험지 실행·내부용).
|
|
139
|
+
* 서버에서 받은 번들은 installVerifiedBundle 만 쓴다.
|
|
140
|
+
*/
|
|
141
|
+
export function installBundleFiles(root, sha256, files, pkgRoot = PKG_ROOT) {
|
|
142
|
+
const problem = bundleFilesProblem(files);
|
|
143
|
+
if (problem)
|
|
144
|
+
throw new Error(`cert-lib bundle: ${problem}`);
|
|
145
|
+
if (!SHA_RE.test(sha256) || bundleDigest(files) !== sha256)
|
|
146
|
+
throw new Error('cert-lib bundle: digest mismatch');
|
|
147
|
+
fs.mkdirSync(root, { recursive: true, mode: 0o700 });
|
|
148
|
+
try {
|
|
149
|
+
fs.chmodSync(root, 0o700);
|
|
150
|
+
}
|
|
151
|
+
catch { /* 무시 */ }
|
|
152
|
+
const shaDir = path.join(root, sha256);
|
|
153
|
+
const dir = libDirOf(root, sha256);
|
|
154
|
+
if (!verifyInstalledFiles(dir, sha256, Object.keys(files))) {
|
|
155
|
+
// 새로 쓴다: 임시 디렉터리에 다 쓴 뒤 교체(부분 설치가 보이지 않게)
|
|
156
|
+
const tmp = fs.mkdtempSync(path.join(root, `.tmp-${sha256.slice(0, 8)}-`));
|
|
157
|
+
try {
|
|
158
|
+
const tdir = path.join(tmp, 'hooks', 'lib', 'cert');
|
|
159
|
+
fs.mkdirSync(tdir, { recursive: true, mode: 0o700 });
|
|
160
|
+
for (const [n, c] of Object.entries(files))
|
|
161
|
+
fs.writeFileSync(path.join(tdir, n), c, { mode: 0o600 });
|
|
162
|
+
fs.rmSync(shaDir, { recursive: true, force: true });
|
|
163
|
+
fs.renameSync(tmp, shaDir);
|
|
164
|
+
}
|
|
165
|
+
finally {
|
|
166
|
+
try {
|
|
167
|
+
fs.rmSync(tmp, { recursive: true, force: true });
|
|
168
|
+
}
|
|
169
|
+
catch { /* 이미 옮겨짐 */ }
|
|
170
|
+
}
|
|
171
|
+
for (const d of [shaDir, path.join(shaDir, 'hooks'), path.join(shaDir, 'hooks', 'lib'), dir]) {
|
|
172
|
+
try {
|
|
173
|
+
fs.chmodSync(d, 0o700);
|
|
174
|
+
}
|
|
175
|
+
catch { /* 무시 */ }
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
linkNodeModules(shaDir, pkgRoot);
|
|
179
|
+
return dir;
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* 설치된 파일 재검증 — 정확히 그 이름 집합만(여분 파일 = 실패: kernel.py 가 자기 디렉터리를 sys.path 앞에 두므로 심은 모듈이 섞이면 안 된다),
|
|
183
|
+
* 다이제스트 일치. python 바이트코드 캐시(__pycache__)는 지운다(검증된 소스에서 다시 만든다).
|
|
184
|
+
*/
|
|
185
|
+
export function verifyInstalledFiles(dir, sha256, names) {
|
|
186
|
+
try {
|
|
187
|
+
const want = new Set(names);
|
|
188
|
+
const files = {};
|
|
189
|
+
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
190
|
+
if (e.name === '__pycache__' && e.isDirectory()) {
|
|
191
|
+
fs.rmSync(path.join(dir, e.name), { recursive: true, force: true });
|
|
192
|
+
continue;
|
|
193
|
+
}
|
|
194
|
+
if (!e.isFile() || !want.has(e.name))
|
|
195
|
+
return false;
|
|
196
|
+
files[e.name] = fs.readFileSync(path.join(dir, e.name), 'utf-8');
|
|
197
|
+
}
|
|
198
|
+
if (Object.keys(files).length !== want.size)
|
|
199
|
+
return false;
|
|
200
|
+
return bundleDigest(files) === sha256;
|
|
201
|
+
}
|
|
202
|
+
catch {
|
|
203
|
+
return false;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
/** 캐시(포인터)의 검증본 — 서명·파일 재검증. 클라 버전이 다르면 쓰지 않는다 */
|
|
207
|
+
function cachedLib(root, version, keys, pkgRoot) {
|
|
208
|
+
const p = readJsonSafe(pointerPath(root));
|
|
209
|
+
if (!p || p.v !== 1 || p.clientVersion !== version || !SHA_RE.test(String(p.sha256)) || !Array.isArray(p.files))
|
|
210
|
+
return null;
|
|
211
|
+
if (!verifyCertLibSig(p.sha256, p.kid, p.sig, keys))
|
|
212
|
+
return null;
|
|
213
|
+
const dir = libDirOf(root, p.sha256);
|
|
214
|
+
if (!verifyInstalledFiles(dir, p.sha256, p.files))
|
|
215
|
+
return null;
|
|
216
|
+
linkNodeModules(path.join(root, p.sha256), pkgRoot);
|
|
217
|
+
return { dir, source: 'cache', sha256: p.sha256 };
|
|
218
|
+
}
|
|
219
|
+
function parseServerLib(data) {
|
|
220
|
+
if (!data || typeof data !== 'object' || Array.isArray(data))
|
|
221
|
+
return null;
|
|
222
|
+
const d = data;
|
|
223
|
+
if (typeof d.sha256 !== 'string' || typeof d.kid !== 'string' || typeof d.sig !== 'string')
|
|
224
|
+
return null;
|
|
225
|
+
const out = { sha256: d.sha256, kid: d.kid, sig: d.sig };
|
|
226
|
+
if (d.files !== undefined && d.files !== null)
|
|
227
|
+
out.files = d.files;
|
|
228
|
+
return out;
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* 서명 검증 후 설치 + 포인터 갱신. 서명 불일치·파일 변조 → throw 대신 사유 문자열.
|
|
232
|
+
*/
|
|
233
|
+
export function installVerifiedBundle(root, lib, keys, version, now, pkgRoot = PKG_ROOT) {
|
|
234
|
+
if (!verifyCertLibSig(lib.sha256, lib.kid, lib.sig, keys))
|
|
235
|
+
return { dir: null, reason: keys ? 'cert-lib-bad-signature' : 'cert-lib-no-pubkeys' };
|
|
236
|
+
if (!lib.files)
|
|
237
|
+
return { dir: null, reason: 'cert-lib-files-missing' };
|
|
238
|
+
const problem = bundleFilesProblem(lib.files);
|
|
239
|
+
if (problem)
|
|
240
|
+
return { dir: null, reason: `cert-lib-bundle-invalid:${problem}` };
|
|
241
|
+
if (bundleDigest(lib.files) !== lib.sha256)
|
|
242
|
+
return { dir: null, reason: 'cert-lib-digest-mismatch' };
|
|
243
|
+
let dir;
|
|
244
|
+
try {
|
|
245
|
+
dir = installBundleFiles(root, lib.sha256, lib.files, pkgRoot);
|
|
246
|
+
}
|
|
247
|
+
catch (e) {
|
|
248
|
+
return { dir: null, reason: 'cert-lib-install:' + String(e?.message ?? e).slice(0, 80) };
|
|
249
|
+
}
|
|
250
|
+
const ptr = { v: 1, clientVersion: version, sha256: lib.sha256, kid: lib.kid, sig: lib.sig, files: Object.keys(lib.files).sort(), fetchedAt: now };
|
|
251
|
+
const meta = { v: 1, sha256: lib.sha256, kid: lib.kid, sig: lib.sig, files: ptr.files };
|
|
252
|
+
try {
|
|
253
|
+
writeFileAtomic(path.join(root, lib.sha256, 'meta.json'), JSON.stringify(meta));
|
|
254
|
+
writeFileAtomic(pointerPath(root), JSON.stringify(ptr));
|
|
255
|
+
}
|
|
256
|
+
catch { /* 포인터 저장 실패 = 다음에 다시 받는다(이번 실행은 검증본 사용) */ }
|
|
257
|
+
return { dir, source: 'server', sha256: lib.sha256 };
|
|
258
|
+
}
|
|
259
|
+
function getFetch(o) {
|
|
260
|
+
if (o.fetchImpl)
|
|
261
|
+
return o.fetchImpl;
|
|
262
|
+
const f = globalThis.fetch;
|
|
263
|
+
return typeof f === 'function' ? f : null;
|
|
264
|
+
}
|
|
265
|
+
async function fetchCurrent(cfg, version, have, o) {
|
|
266
|
+
const f = getFetch(o);
|
|
267
|
+
if (!f)
|
|
268
|
+
return { status: 0, data: null };
|
|
269
|
+
const ctl = new AbortController();
|
|
270
|
+
const timer = setTimeout(() => ctl.abort(), o.timeoutMs ?? 30_000);
|
|
271
|
+
try {
|
|
272
|
+
const q = `?clientVersion=${encodeURIComponent(version)}${have ? `&have=${have}` : ''}`;
|
|
273
|
+
const r = await f(`${cfg.serverUrl}/api/v1/cert-lib/current${q}`, {
|
|
274
|
+
method: 'GET', headers: { Authorization: 'Bearer ' + cfg.apiKey, Accept: 'application/json' }, signal: ctl.signal,
|
|
275
|
+
});
|
|
276
|
+
let parsed = null;
|
|
277
|
+
try {
|
|
278
|
+
parsed = JSON.parse(await r.text());
|
|
279
|
+
}
|
|
280
|
+
catch {
|
|
281
|
+
parsed = null;
|
|
282
|
+
}
|
|
283
|
+
const data = parsed && typeof parsed === 'object' && 'data' in parsed ? parsed.data : parsed;
|
|
284
|
+
return { status: r.status, data };
|
|
285
|
+
}
|
|
286
|
+
catch {
|
|
287
|
+
return { status: 0, data: null };
|
|
288
|
+
}
|
|
289
|
+
finally {
|
|
290
|
+
clearTimeout(timer);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* 네트워크 없이 해석 — 패키지 안 TCB 또는 같은 클라 버전의 검증된 캐시. 동기(교차검증 verify 용).
|
|
295
|
+
*/
|
|
296
|
+
export function resolveCertLibSync(o = {}) {
|
|
297
|
+
try {
|
|
298
|
+
const pkgDir = o.pkgCertDir ?? PKG_CERT_DIR;
|
|
299
|
+
if (hasPkgLib(pkgDir))
|
|
300
|
+
return { dir: pkgDir, source: 'package' };
|
|
301
|
+
const keys = o.pubKeys ?? recordPubKeys();
|
|
302
|
+
if (!keys)
|
|
303
|
+
return { dir: null, reason: 'cert-lib-no-pubkeys' };
|
|
304
|
+
const c = cachedLib(o.cacheRoot ?? certLibCacheRoot(), clientVersionOf(o), keys, o.pkgRoot ?? PKG_ROOT);
|
|
305
|
+
return c ?? { dir: null, reason: 'cert-lib-not-cached' };
|
|
306
|
+
}
|
|
307
|
+
catch (e) {
|
|
308
|
+
return { dir: null, reason: 'cert-lib-error:' + String(e?.message ?? e).slice(0, 80) };
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* 증명서 lib 해석 — 패키지 안 TCB → (포인터 TTL 안이면 캐시) → 서버(서명·다이제스트 검증) → 오프라인이면 검증된 캐시.
|
|
313
|
+
* 절대 throw 하지 않는다. 실패 = {dir:null, reason}.
|
|
314
|
+
*/
|
|
315
|
+
export async function resolveCertLib(o = {}) {
|
|
316
|
+
try {
|
|
317
|
+
const pkgDir = o.pkgCertDir ?? PKG_CERT_DIR;
|
|
318
|
+
if (hasPkgLib(pkgDir))
|
|
319
|
+
return { dir: pkgDir, source: 'package' };
|
|
320
|
+
const keys = o.pubKeys ?? recordPubKeys();
|
|
321
|
+
if (!keys)
|
|
322
|
+
return { dir: null, reason: 'cert-lib-no-pubkeys' };
|
|
323
|
+
const root = o.cacheRoot ?? certLibCacheRoot();
|
|
324
|
+
const version = clientVersionOf(o);
|
|
325
|
+
const pkgRoot = o.pkgRoot ?? PKG_ROOT;
|
|
326
|
+
const now = (o.now ?? Date.now)();
|
|
327
|
+
const ptr = readJsonSafe(pointerPath(root));
|
|
328
|
+
const cached = cachedLib(root, version, keys, pkgRoot);
|
|
329
|
+
if (cached && ptr && now - ptr.fetchedAt >= 0 && now - ptr.fetchedAt < (o.ttlMs ?? 3_600_000))
|
|
330
|
+
return cached;
|
|
331
|
+
const cfg = o.syncConfig !== undefined ? o.syncConfig : readSyncConfig();
|
|
332
|
+
if (!cfg)
|
|
333
|
+
return cached ?? { dir: null, reason: 'cert-lib-no-auth' };
|
|
334
|
+
const r = await fetchCurrent(cfg, version, cached ? cached.sha256 ?? null : null, o);
|
|
335
|
+
if (r.status === 0 || r.status >= 500 || r.status === 429)
|
|
336
|
+
return cached ?? { dir: null, reason: r.status === 0 ? 'cert-lib-offline' : `cert-lib-http-${r.status}` };
|
|
337
|
+
if (r.status === 401 || r.status === 403)
|
|
338
|
+
return { dir: null, reason: `cert-lib-unauthorized-${r.status}` };
|
|
339
|
+
if (r.status === 404)
|
|
340
|
+
return { dir: null, reason: 'cert-lib-none-for-version' };
|
|
341
|
+
if (r.status !== 200)
|
|
342
|
+
return { dir: null, reason: `cert-lib-http-${r.status}` };
|
|
343
|
+
const lib = parseServerLib(r.data);
|
|
344
|
+
if (!lib)
|
|
345
|
+
return { dir: null, reason: 'cert-lib-malformed' };
|
|
346
|
+
// 서버가 "가진 것과 같다"(files 생략) — 캐시 검증본이 그 sha 일 때만, 서명도 서버 응답으로 다시 확인
|
|
347
|
+
if (!lib.files) {
|
|
348
|
+
if (cached && cached.sha256 === lib.sha256 && verifyCertLibSig(lib.sha256, lib.kid, lib.sig, keys)) {
|
|
349
|
+
try {
|
|
350
|
+
if (ptr)
|
|
351
|
+
writeFileAtomic(pointerPath(root), JSON.stringify({ ...ptr, kid: lib.kid, sig: lib.sig, fetchedAt: now }));
|
|
352
|
+
}
|
|
353
|
+
catch { /* 무시 */ }
|
|
354
|
+
return cached;
|
|
355
|
+
}
|
|
356
|
+
return { dir: null, reason: 'cert-lib-files-missing' };
|
|
357
|
+
}
|
|
358
|
+
return installVerifiedBundle(root, lib, keys, version, now, pkgRoot);
|
|
359
|
+
}
|
|
360
|
+
catch (e) {
|
|
361
|
+
return { dir: null, reason: 'cert-lib-error:' + String(e?.message ?? e).slice(0, 80) };
|
|
362
|
+
}
|
|
363
|
+
}
|
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* config-map/cert-wiring — 진단 증명서(certify) 결과를 감사·제안·스냅샷·적용 게이트에 연결 (설계 13 §3·§5·§6.1·§6.2·§6.4·§6.5, W4).
|
|
3
|
+
*
|
|
4
|
+
* 하는 일(판정은 만들지 않는다 — 검사기 A 의 verdicts 파일을 읽어 옮기기만):
|
|
5
|
+
* - 업로드 플래그 `ROUTINECODE_CERT_UPLOAD`(기본 on — W5 서버 배포 확인 10/30, off 로만 끈다)
|
|
6
|
+
* - `<storeDir>/certs/latest.json` 포인터(마지막 certify 날짜·레포 최상위·요약) — 게이트·verify 가 레포 위치를 찾는다
|
|
7
|
+
* - 증명서 색인(CertIndex): 증명서 id → state·reason, 묶음(연결 성분), 쌍·단일 대상 → 증명서 id
|
|
8
|
+
* - 보장 기준 그래프 입력(§6.5): 노드 issues.dupL1/orphans 를 보장 항목만으로
|
|
9
|
+
* - `<storeDir>/architect/uploaded.json`(§6.2): 업로드 집합 + 철회 묘비 최초 전송일(30일 보존)
|
|
10
|
+
* - 적용 게이트 동기 래퍼 certFresh(§6.4): 별도 node 프로세스(cert-gate.js)로 제안 하나만 재증명
|
|
11
|
+
*
|
|
12
|
+
* 무거운 의존 없음(fs·path·crypto·child_process) — zero-dep CLI(bin/rc-config.js)가 proposals.js 를 통해 import 한다.
|
|
13
|
+
*/
|
|
14
|
+
import * as fs from 'fs';
|
|
15
|
+
import * as path from 'path';
|
|
16
|
+
import * as crypto from 'crypto';
|
|
17
|
+
import { spawnSync } from 'child_process';
|
|
18
|
+
import { fileURLToPath } from 'url';
|
|
19
|
+
// ── 플래그 ───────────────────────────────────────────────────────────
|
|
20
|
+
/**
|
|
21
|
+
* 설계 13 §11: 스냅샷 `cert`·제안 certState 업로드 플래그. 서버 W5(knowledge-service:cert-261030, 2026-10-30) 배포 확인 후
|
|
22
|
+
* **기본 on** — `ROUTINECODE_CERT_UPLOAD=off|0|false|no` 로만 끈다(끄면 업로드 본문은 W4 이전과 같다).
|
|
23
|
+
*/
|
|
24
|
+
export function certUploadOn(env = process.env) {
|
|
25
|
+
const v = String(env.ROUTINECODE_CERT_UPLOAD ?? '').trim().toLowerCase();
|
|
26
|
+
return !(v === '0' || v === 'false' || v === 'off' || v === 'no');
|
|
27
|
+
}
|
|
28
|
+
/** `file#name` — 증명서 대상 키(레포 최상위 상대 경로, SCHEMA §1) */
|
|
29
|
+
export const certKey = (file, name) => `${file}#${name}`;
|
|
30
|
+
/** 쌍 키(순서 무관) */
|
|
31
|
+
export const pairKey = (a, b) => (a < b ? `${a}|${b}` : `${b}|${a}`);
|
|
32
|
+
export function readCertLines(file) {
|
|
33
|
+
let t = '';
|
|
34
|
+
try {
|
|
35
|
+
t = fs.readFileSync(file, 'utf-8');
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return [];
|
|
39
|
+
}
|
|
40
|
+
const out = [];
|
|
41
|
+
for (const ln of t.split('\n')) {
|
|
42
|
+
if (!ln.trim())
|
|
43
|
+
continue;
|
|
44
|
+
try {
|
|
45
|
+
const c = JSON.parse(ln);
|
|
46
|
+
if (c && typeof c.id === 'string' && Array.isArray(c.targets))
|
|
47
|
+
out.push(c);
|
|
48
|
+
}
|
|
49
|
+
catch { /* 손상 줄 = 무시(그 대상은 증명서 없음 → 보류) */ }
|
|
50
|
+
}
|
|
51
|
+
return out;
|
|
52
|
+
}
|
|
53
|
+
export function readVerdicts(file) {
|
|
54
|
+
if (!file)
|
|
55
|
+
return null;
|
|
56
|
+
try {
|
|
57
|
+
const v = JSON.parse(fs.readFileSync(file, 'utf-8'));
|
|
58
|
+
return v && Array.isArray(v.items) && Array.isArray(v.clusters) ? v : null;
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
/** 증명서·판정 → 색인. 판정이 없거나(ok=false) 증명이 미완이면 certified 를 보류('cert-not-ok')로 내린다 — 거짓 보장 금지(P6) */
|
|
65
|
+
export function loadCertIndex(certsFile, verdictsFile, ok, date = path.basename(certsFile).replace(/\.jsonl$/, '')) {
|
|
66
|
+
const lines = readCertLines(certsFile);
|
|
67
|
+
const v = readVerdicts(verdictsFile);
|
|
68
|
+
const items = new Map();
|
|
69
|
+
const usable = ok && !!v;
|
|
70
|
+
if (v)
|
|
71
|
+
for (const it of v.items)
|
|
72
|
+
items.set(it.id, { state: it.state, reason: it.reason });
|
|
73
|
+
for (const c of lines) {
|
|
74
|
+
const cur = items.get(c.id) ?? { state: 'abstained', reason: 'verdicts-missing' };
|
|
75
|
+
items.set(c.id, !usable && cur.state === 'certified' ? { state: 'abstained', reason: 'cert-not-ok' } : cur);
|
|
76
|
+
}
|
|
77
|
+
const pairId = new Map();
|
|
78
|
+
const unusedId = new Map();
|
|
79
|
+
const byId = new Map();
|
|
80
|
+
for (const c of lines) {
|
|
81
|
+
byId.set(c.id, c);
|
|
82
|
+
if (c.kind === 'DUP-EQ' && c.targets.length === 2)
|
|
83
|
+
pairId.set(pairKey(certKey(c.targets[0].file, c.targets[0].name), certKey(c.targets[1].file, c.targets[1].name)), c.id);
|
|
84
|
+
else if (c.kind === 'UNUSED-EXPORT' && c.targets.length === 1)
|
|
85
|
+
unusedId.set(certKey(c.targets[0].file, c.targets[0].name), c.id);
|
|
86
|
+
}
|
|
87
|
+
return { date, ok: usable, items, lines: byId, clusters: usable && v ? v.clusters : [], pairId, unusedId };
|
|
88
|
+
}
|
|
89
|
+
/** 감사 멤버 파일 → 증명서 키(레포 최상위 상대) — certify.certCandidates 와 같은 규칙(레포 밖 멤버 = null) */
|
|
90
|
+
export function certKeyFn(run, top) {
|
|
91
|
+
const roots = new Map(run.map.members.map(m => [m.name, m.root]));
|
|
92
|
+
return (member, file, name) => {
|
|
93
|
+
const root = roots.get(member);
|
|
94
|
+
if (!root)
|
|
95
|
+
return null;
|
|
96
|
+
const r = path.relative(top, path.join(root, file)).split(path.sep).join('/');
|
|
97
|
+
return r.startsWith('..') || path.isAbsolute(r) ? null : certKey(r, name);
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
export function certsDir(storeDir) { return path.join(storeDir, 'certs'); }
|
|
101
|
+
export function certLatestPath(storeDir) { return path.join(certsDir(storeDir), 'latest.json'); }
|
|
102
|
+
export function readCertLatest(storeDir) {
|
|
103
|
+
try {
|
|
104
|
+
const l = JSON.parse(fs.readFileSync(certLatestPath(storeDir), 'utf-8'));
|
|
105
|
+
return l && l.v === 1 && typeof l.date === 'string' && typeof l.top === 'string' ? l : null;
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
return null;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
export function writeCertLatest(storeDir, l) {
|
|
112
|
+
const p = certLatestPath(storeDir);
|
|
113
|
+
fs.mkdirSync(path.dirname(p), { recursive: true });
|
|
114
|
+
const tmp = `${p}.${process.pid}.tmp`;
|
|
115
|
+
fs.writeFileSync(tmp, JSON.stringify(l, null, 2) + '\n');
|
|
116
|
+
fs.renameSync(tmp, p);
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* certify 실패(예외·시간 초과로 요약 자체가 없음) 날의 요약 — ok=false, 수치 0(P6 "그 날 검증 미완").
|
|
120
|
+
* entrypointsDigest 는 빈 목록의 다이제스트(SCHEMA §2 — 진입점 미계산을 뜻한다).
|
|
121
|
+
*/
|
|
122
|
+
export function failedCertSummary(minTokens) {
|
|
123
|
+
return {
|
|
124
|
+
v: 2, frontVer: 0, kernelVer: 0, ok: false,
|
|
125
|
+
dup: { clusters: 0, decls: 0, archivedClusters: 0 },
|
|
126
|
+
unused: { exports: 0, archived: 0 },
|
|
127
|
+
abstained: { dup: 0, unused: 0, byReason: {} },
|
|
128
|
+
refuted: { dup: 0, unused: 0 },
|
|
129
|
+
missed: null,
|
|
130
|
+
coverage: { byLang: {}, analyzedFiles: 0, codeFiles: 0 },
|
|
131
|
+
minTokens, entrypointsDigest: crypto.createHash('sha256').update('').digest('hex'), entrypointsConfirmed: false,
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
/** 서버 CertDto(knowledge config.dto.ts) 와 정확히 같은 필드만 — 그 밖의 키는 stripUnknown 이 지우므로 애초에 싣지 않는다 */
|
|
135
|
+
export function certPayload(s) {
|
|
136
|
+
return {
|
|
137
|
+
v: 2, frontVer: s.frontVer, kernelVer: s.kernelVer, ok: s.ok,
|
|
138
|
+
dup: { clusters: s.dup.clusters, decls: s.dup.decls, archivedClusters: s.dup.archivedClusters },
|
|
139
|
+
unused: { exports: s.unused.exports, archived: s.unused.archived },
|
|
140
|
+
abstained: { dup: s.abstained.dup, unused: s.abstained.unused, byReason: { ...s.abstained.byReason } },
|
|
141
|
+
refuted: { dup: s.refuted.dup, unused: s.refuted.unused },
|
|
142
|
+
missed: s.missed ? { dup: s.missed.dup } : null,
|
|
143
|
+
coverage: {
|
|
144
|
+
byLang: Object.fromEntries(Object.keys(s.coverage.byLang).sort().map(k => [k, { files: s.coverage.byLang[k].files, analyzed: s.coverage.byLang[k].analyzed }])),
|
|
145
|
+
analyzedFiles: s.coverage.analyzedFiles, codeFiles: s.coverage.codeFiles,
|
|
146
|
+
},
|
|
147
|
+
minTokens: s.minTokens, entrypointsDigest: s.entrypointsDigest, entrypointsConfirmed: s.entrypointsConfirmed,
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
/** 설계 13 §7.3: 확정 표시는 사용자가 확인한 유효 진입점 목록(다이제스트)이 오늘 것과 같을 때만 — 목록이 바뀌면 다시 "자동 추정" */
|
|
151
|
+
export function entrypointsConfirmedFor(storeDir, digest) {
|
|
152
|
+
try {
|
|
153
|
+
const b = JSON.parse(fs.readFileSync(path.join(storeDir, 'baseline.json'), 'utf-8'));
|
|
154
|
+
return !!b && !!b.entrypointsConfirmed && b.entrypointsConfirmed.digest === digest;
|
|
155
|
+
}
|
|
156
|
+
catch {
|
|
157
|
+
return false;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* 노드 issues 를 보장 기준으로(설계 13 §6.5): dupL1 = 최종 certified 묶음(멤버 = 찾는 엔진 멤버로 역매핑), dupL2 = 없음(이중 집계 R2 제거),
|
|
162
|
+
* orphans = export-ref 는 UNUSED-EXPORT certified 만 + 증명서 체계 밖 단선(route·api·model·env)은 그대로(§6.4 와 같은 경계).
|
|
163
|
+
* 필드 이름은 유지(서버 GraphNodeDto 에 `certified` 가 없어 노드 표기는 싣지 않는다 — stripUnknown 이 조용히 지움).
|
|
164
|
+
*/
|
|
165
|
+
export function certifiedAuditInput(report, idx, keyOf) {
|
|
166
|
+
const byKey = new Map();
|
|
167
|
+
for (const c of [...report.dupL1, ...report.dupL2])
|
|
168
|
+
for (const m of c.members) {
|
|
169
|
+
const k = keyOf(m.member, m.file, m.name);
|
|
170
|
+
if (k && !byKey.has(k))
|
|
171
|
+
byKey.set(k, m);
|
|
172
|
+
}
|
|
173
|
+
const dupL1 = [];
|
|
174
|
+
for (const cl of idx.clusters) {
|
|
175
|
+
const members = cl.map(k => byKey.get(k)).filter((m) => !!m);
|
|
176
|
+
if (members.length >= 2)
|
|
177
|
+
dupL1.push({ hash: 'cert:' + crypto.createHash('sha1').update(cl.join('\n')).digest('hex').slice(0, 12), size: members.length, members, note: 'certified (설계 13 DUP-EQ)' });
|
|
178
|
+
}
|
|
179
|
+
const orphans = report.orphans.filter(o => {
|
|
180
|
+
if (o.check !== 'export-ref')
|
|
181
|
+
return true;
|
|
182
|
+
const k = keyOf(o.member, o.file, o.name);
|
|
183
|
+
const id = k ? idx.unusedId.get(k) : undefined;
|
|
184
|
+
return !!id && idx.items.get(id)?.state === 'certified';
|
|
185
|
+
});
|
|
186
|
+
return { dupL1, dupL2: [], orphans, constraintFindings: report.constraintFindings };
|
|
187
|
+
}
|
|
188
|
+
export function uploadedPath(storeDir) { return path.join(storeDir, 'architect', 'uploaded.json'); }
|
|
189
|
+
export function readUploaded(storeDir) {
|
|
190
|
+
try {
|
|
191
|
+
const u = JSON.parse(fs.readFileSync(uploadedPath(storeDir), 'utf-8'));
|
|
192
|
+
return u && u.v === 1 && u.tombstones && u.uploaded ? u : null;
|
|
193
|
+
}
|
|
194
|
+
catch {
|
|
195
|
+
return null;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
/** 철회 묘비 보존 일수(설계 13 §6.2 — 최초 전송일부터 30일) */
|
|
199
|
+
export const TOMBSTONE_DAYS = 30;
|
|
200
|
+
export function daysBetween(a, b) {
|
|
201
|
+
return Math.round((Date.parse(b + 'T00:00:00Z') - Date.parse(a + 'T00:00:00Z')) / 86_400_000);
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* 업로드 직후 기록: id → 대상·certState·대상 파일 sha256, 철회 묘비(finder-changed)는 최초 전송일을 보존(없으면 오늘).
|
|
205
|
+
* 이번 본문에 없는 묘비 기록은 지운다(보존 기간이 끝났거나 해소됨).
|
|
206
|
+
*/
|
|
207
|
+
export function recordUploaded(storeDir, projectDir, today, proposals) {
|
|
208
|
+
const prev = readUploaded(storeDir);
|
|
209
|
+
const tombstones = {};
|
|
210
|
+
const uploaded = {};
|
|
211
|
+
const shaCache = new Map();
|
|
212
|
+
const sha = (f) => {
|
|
213
|
+
if (!shaCache.has(f)) {
|
|
214
|
+
let h = 'missing';
|
|
215
|
+
try {
|
|
216
|
+
h = crypto.createHash('sha256').update(fs.readFileSync(path.join(projectDir, f))).digest('hex');
|
|
217
|
+
}
|
|
218
|
+
catch { /* 없음 */ }
|
|
219
|
+
shaCache.set(f, h);
|
|
220
|
+
}
|
|
221
|
+
return shaCache.get(f);
|
|
222
|
+
};
|
|
223
|
+
for (const p of [...proposals].sort((a, b) => a.id.localeCompare(b.id))) {
|
|
224
|
+
uploaded[p.id] = { targets: p.targets.map(t => ({ file: t.file, name: t.name })), certState: p.certState ?? null, sha256: Object.fromEntries(Array.from(new Set(p.targets.map(t => t.file))).sort().map(f => [f, sha(f)])) };
|
|
225
|
+
if (p.certState === 'withdrawn' && p.certReason === 'finder-changed')
|
|
226
|
+
tombstones[p.id] = { firstSent: prev?.tombstones[p.id]?.firstSent ?? today, reason: 'finder-changed' };
|
|
227
|
+
}
|
|
228
|
+
const out = { v: 1, date: today, tombstones, uploaded };
|
|
229
|
+
const p = uploadedPath(storeDir);
|
|
230
|
+
fs.mkdirSync(path.dirname(p), { recursive: true });
|
|
231
|
+
const tmp = `${p}.${process.pid}.tmp`;
|
|
232
|
+
fs.writeFileSync(tmp, JSON.stringify(out, null, 2) + '\n');
|
|
233
|
+
fs.renameSync(tmp, p);
|
|
234
|
+
return out;
|
|
235
|
+
}
|
|
236
|
+
/** 게이트 대상 = 증명서가 있는 유형만(설계 13 §6.4 — wire·layer-fix 는 영구 차단 방지로 제외) */
|
|
237
|
+
export function certGateApplies(type) { return type === 'merge' || type === 'delete'; }
|
|
238
|
+
const GATE_JS = path.join(path.dirname(fileURLToPath(import.meta.url)), 'cert-gate.js');
|
|
239
|
+
function gateTimeoutMs() {
|
|
240
|
+
const n = Number(process.env.CERT_TIME_BUDGET_MS);
|
|
241
|
+
return (Number.isFinite(n) && n > 0 ? n : 120_000) + 60_000;
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* certFresh(storeDir, proposalId) — 그 제안 하나만 재증명(국소 재증명 + 레포 전역 텍스트 재스캔, cert-gate.ts).
|
|
245
|
+
* 별도 node 프로세스(메모리 상한 1024MB)로 돌려 동기 호출 경로(runnableApprovals·setLocalResult)에서 쓸 수 있게 한다.
|
|
246
|
+
* 인프라 실패(스크립트 없음·시간 초과·출력 손상) = 실패(fail-closed).
|
|
247
|
+
*/
|
|
248
|
+
export function certFresh(storeDir, proposalId) {
|
|
249
|
+
if (!fs.existsSync(GATE_JS))
|
|
250
|
+
return { ok: false, applicable: true, reason: 'cert-gate-unavailable' };
|
|
251
|
+
const r = spawnSync(process.execPath, ['--max-old-space-size=1024', GATE_JS, 'gate', storeDir, proposalId], {
|
|
252
|
+
encoding: 'utf-8', maxBuffer: 64 * 1024 * 1024, timeout: gateTimeoutMs(), env: process.env,
|
|
253
|
+
});
|
|
254
|
+
if (r.error || r.status !== 0)
|
|
255
|
+
return { ok: false, applicable: true, reason: `cert-gate-error:${r.error ? r.error.code ?? 'spawn' : `exit ${r.status}`}` };
|
|
256
|
+
const last = String(r.stdout).trim().split('\n').pop() ?? '';
|
|
257
|
+
try {
|
|
258
|
+
const o = JSON.parse(last);
|
|
259
|
+
if (typeof o.ok !== 'boolean' || typeof o.reason !== 'string')
|
|
260
|
+
throw new Error('shape');
|
|
261
|
+
return { ok: o.ok, applicable: o.applicable !== false, reason: o.reason, ...(o.certId ? { certId: o.certId } : {}) };
|
|
262
|
+
}
|
|
263
|
+
catch {
|
|
264
|
+
return { ok: false, applicable: true, reason: 'cert-gate-output' };
|
|
265
|
+
}
|
|
266
|
+
}
|