@conarium-ai/core 0.1.0

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.
Files changed (188) hide show
  1. package/CHANGELOG.md +131 -0
  2. package/LICENSE +21 -0
  3. package/README.md +387 -0
  4. package/SECURITY.md +226 -0
  5. package/bin/conarium-anchor-service.mjs +77 -0
  6. package/bin/conarium-anchor-upgrade.mjs +108 -0
  7. package/bin/conarium-coverage.mjs +425 -0
  8. package/bin/conarium-doctor.mjs +480 -0
  9. package/bin/conarium-init.mjs +184 -0
  10. package/bin/conarium-reconcile.mjs +441 -0
  11. package/bin/conarium-stamp.mjs +161 -0
  12. package/bin/conarium-verify.mjs +610 -0
  13. package/conarium.config.json +43 -0
  14. package/deploy/anchor-service/README.md +79 -0
  15. package/deploy/anchor-service/conarium-anchor.service +21 -0
  16. package/deploy/anchor-service/dry-run.mjs +122 -0
  17. package/deploy/anchor-service/ecosystem.config.cjs +21 -0
  18. package/deploy/anchor-service/env.example +11 -0
  19. package/dist/anchor-service.d.ts +39 -0
  20. package/dist/anchor-service.d.ts.map +1 -0
  21. package/dist/anchor-service.js +278 -0
  22. package/dist/anchor-service.js.map +1 -0
  23. package/dist/anchor.d.ts +123 -0
  24. package/dist/anchor.d.ts.map +1 -0
  25. package/dist/anchor.js +246 -0
  26. package/dist/anchor.js.map +1 -0
  27. package/dist/audit-hash.d.ts +4 -0
  28. package/dist/audit-hash.d.ts.map +1 -0
  29. package/dist/audit-hash.js +12 -0
  30. package/dist/audit-hash.js.map +1 -0
  31. package/dist/audit.d.ts +104 -0
  32. package/dist/audit.d.ts.map +1 -0
  33. package/dist/audit.js +391 -0
  34. package/dist/audit.js.map +1 -0
  35. package/dist/config.d.ts +273 -0
  36. package/dist/config.d.ts.map +1 -0
  37. package/dist/config.js +44 -0
  38. package/dist/config.js.map +1 -0
  39. package/dist/connectors/docs.d.ts +23 -0
  40. package/dist/connectors/docs.d.ts.map +1 -0
  41. package/dist/connectors/docs.js +140 -0
  42. package/dist/connectors/docs.js.map +1 -0
  43. package/dist/connectors/index.d.ts +10 -0
  44. package/dist/connectors/index.d.ts.map +1 -0
  45. package/dist/connectors/index.js +37 -0
  46. package/dist/connectors/index.js.map +1 -0
  47. package/dist/connectors/jira.d.ts +16 -0
  48. package/dist/connectors/jira.d.ts.map +1 -0
  49. package/dist/connectors/jira.js +67 -0
  50. package/dist/connectors/jira.js.map +1 -0
  51. package/dist/connectors/openapi.d.ts +28 -0
  52. package/dist/connectors/openapi.d.ts.map +1 -0
  53. package/dist/connectors/openapi.js +447 -0
  54. package/dist/connectors/openapi.js.map +1 -0
  55. package/dist/connectors/postgres.d.ts +17 -0
  56. package/dist/connectors/postgres.d.ts.map +1 -0
  57. package/dist/connectors/postgres.js +131 -0
  58. package/dist/connectors/postgres.js.map +1 -0
  59. package/dist/connectors/slack.d.ts +16 -0
  60. package/dist/connectors/slack.d.ts.map +1 -0
  61. package/dist/connectors/slack.js +65 -0
  62. package/dist/connectors/slack.js.map +1 -0
  63. package/dist/connectors/supabase_rest.d.ts +35 -0
  64. package/dist/connectors/supabase_rest.d.ts.map +1 -0
  65. package/dist/connectors/supabase_rest.js +153 -0
  66. package/dist/connectors/supabase_rest.js.map +1 -0
  67. package/dist/connectors/zion.d.ts +24 -0
  68. package/dist/connectors/zion.d.ts.map +1 -0
  69. package/dist/connectors/zion.js +76 -0
  70. package/dist/connectors/zion.js.map +1 -0
  71. package/dist/console.d.ts +30 -0
  72. package/dist/console.d.ts.map +1 -0
  73. package/dist/console.js +257 -0
  74. package/dist/console.js.map +1 -0
  75. package/dist/coverage.d.ts +100 -0
  76. package/dist/coverage.d.ts.map +1 -0
  77. package/dist/coverage.js +175 -0
  78. package/dist/coverage.js.map +1 -0
  79. package/dist/executor.d.ts +12 -0
  80. package/dist/executor.d.ts.map +1 -0
  81. package/dist/executor.js +77 -0
  82. package/dist/executor.js.map +1 -0
  83. package/dist/governance.d.ts +124 -0
  84. package/dist/governance.d.ts.map +1 -0
  85. package/dist/governance.js +977 -0
  86. package/dist/governance.js.map +1 -0
  87. package/dist/http.d.ts +48 -0
  88. package/dist/http.d.ts.map +1 -0
  89. package/dist/http.js +221 -0
  90. package/dist/http.js.map +1 -0
  91. package/dist/index.d.ts +3 -0
  92. package/dist/index.d.ts.map +1 -0
  93. package/dist/index.js +25 -0
  94. package/dist/index.js.map +1 -0
  95. package/dist/keys.d.ts +51 -0
  96. package/dist/keys.d.ts.map +1 -0
  97. package/dist/keys.js +174 -0
  98. package/dist/keys.js.map +1 -0
  99. package/dist/license.d.ts +35 -0
  100. package/dist/license.d.ts.map +1 -0
  101. package/dist/license.js +122 -0
  102. package/dist/license.js.map +1 -0
  103. package/dist/llm-gate.d.ts +17 -0
  104. package/dist/llm-gate.d.ts.map +1 -0
  105. package/dist/llm-gate.js +19 -0
  106. package/dist/llm-gate.js.map +1 -0
  107. package/dist/openapi_connector.d.ts +6 -0
  108. package/dist/openapi_connector.d.ts.map +1 -0
  109. package/dist/openapi_connector.js +145 -0
  110. package/dist/openapi_connector.js.map +1 -0
  111. package/dist/pseudonymize.d.ts +19 -0
  112. package/dist/pseudonymize.d.ts.map +1 -0
  113. package/dist/pseudonymize.js +25 -0
  114. package/dist/pseudonymize.js.map +1 -0
  115. package/dist/rate_limit.d.ts +41 -0
  116. package/dist/rate_limit.d.ts.map +1 -0
  117. package/dist/rate_limit.js +66 -0
  118. package/dist/rate_limit.js.map +1 -0
  119. package/dist/receipt.d.ts +161 -0
  120. package/dist/receipt.d.ts.map +1 -0
  121. package/dist/receipt.js +210 -0
  122. package/dist/receipt.js.map +1 -0
  123. package/dist/scripts/discover_schema.d.ts +2 -0
  124. package/dist/scripts/discover_schema.d.ts.map +1 -0
  125. package/dist/scripts/discover_schema.js +75 -0
  126. package/dist/scripts/discover_schema.js.map +1 -0
  127. package/dist/scripts/dogfood_prove.d.ts +2 -0
  128. package/dist/scripts/dogfood_prove.d.ts.map +1 -0
  129. package/dist/scripts/dogfood_prove.js +41 -0
  130. package/dist/scripts/dogfood_prove.js.map +1 -0
  131. package/dist/search_policy.d.ts +23 -0
  132. package/dist/search_policy.d.ts.map +1 -0
  133. package/dist/search_policy.js +79 -0
  134. package/dist/search_policy.js.map +1 -0
  135. package/dist/server.d.ts +29 -0
  136. package/dist/server.d.ts.map +1 -0
  137. package/dist/server.js +379 -0
  138. package/dist/server.js.map +1 -0
  139. package/dist/tokens.d.ts +14 -0
  140. package/dist/tokens.d.ts.map +1 -0
  141. package/dist/tokens.js +58 -0
  142. package/dist/tokens.js.map +1 -0
  143. package/dist/types.d.ts +132 -0
  144. package/dist/types.d.ts.map +1 -0
  145. package/dist/types.js +2 -0
  146. package/dist/types.js.map +1 -0
  147. package/docs/ARCHITECTURE.md +42 -0
  148. package/docs/CONSENT-BINDING-SPEC.md +136 -0
  149. package/docs/CONSENT-BINDING-SPEC.md.anchors.jsonl +1 -0
  150. package/docs/PRIOR-ART.md +213 -0
  151. package/docs/PRIOR-ART.md.anchors.jsonl +3 -0
  152. package/docs/RECEIPT-SPEC.md +301 -0
  153. package/docs/RECEIPT-SPEC.md.anchors.jsonl +1 -0
  154. package/docs/dogfood/2026-07-31-anchor.anchors.jsonl +1 -0
  155. package/docs/dogfood/2026-08-06-reconcile.md +140 -0
  156. package/docs/plans/2026-07-02-redteam-harness.md +416 -0
  157. package/docs/specs/2026-07-02-redteam-harness-design.md +90 -0
  158. package/docs/superpowers/TODO-gate1-f4.md +23 -0
  159. package/docs/superpowers/plans/2026-07-29-conarium-receipt-plan.md +200 -0
  160. package/docs/superpowers/plans/2026-07-29-katman0-kapanis-plan.md +231 -0
  161. package/docs/superpowers/plans/2026-07-31-per-user-identity.md +667 -0
  162. package/docs/superpowers/specs/2026-07-29-conarium-receipt-design.md +202 -0
  163. package/docs/superpowers/specs/2026-07-31-per-user-identity-design.md +144 -0
  164. package/docs/superpowers/specs/2026-08-01-coverage-proof-design.md +139 -0
  165. package/docs/superpowers/specs/2026-08-05-receipt-meta-provenance-design.md +116 -0
  166. package/examples/claude-desktop-config.json +9 -0
  167. package/examples/cursor-mcp-settings.json +10 -0
  168. package/package.json +99 -0
  169. package/scripts/audit-chain-check.mjs +119 -0
  170. package/scripts/conarium_sabah_brief.mjs +107 -0
  171. package/scripts/gen-test-vectors.mjs +193 -0
  172. package/scripts/pg-snapshot.sql +27 -0
  173. package/scripts/start-mcp-c1.mjs +70 -0
  174. package/test-vectors/001-single-receipt/receipts.jsonl +1 -0
  175. package/test-vectors/002-chain-of-three/receipts.jsonl +3 -0
  176. package/test-vectors/003-tampered-field/receipts.jsonl +1 -0
  177. package/test-vectors/004-prevhash-break/receipts.jsonl +2 -0
  178. package/test-vectors/005-seq-gap/receipts.jsonl +2 -0
  179. package/test-vectors/006-bad-signature/receipts.jsonl +1 -0
  180. package/test-vectors/007-schema-invalid/receipts.jsonl +1 -0
  181. package/test-vectors/008-unsigned-no-pubkey/receipts.jsonl +1 -0
  182. package/test-vectors/009-unsigned-but-pubkey-given/receipts.jsonl +1 -0
  183. package/test-vectors/README.md +92 -0
  184. package/test-vectors/expected-hashes.json +24 -0
  185. package/test-vectors/keys/vector-key.SECRET-TEST-ONLY.pem +6 -0
  186. package/test-vectors/keys/vector-key.pub.pem +3 -0
  187. package/test-vectors/keys/vector-key.pub.pem.keyid +1 -0
  188. package/test-vectors/manifest.json +95 -0
@@ -0,0 +1,425 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * conarium-coverage — independent offline verifier for Conarium Coverage Declaration v0.1.
4
+ *
5
+ * ZERO imports from src/. Canonicalization is duplicated here on purpose:
6
+ * a third party must be able to run this single file without the Conarium package.
7
+ *
8
+ * Usage:
9
+ * conarium-coverage <declaration.json> --pubkey <path>
10
+ * [--receipts <receipts.jsonl>] [--json]
11
+ *
12
+ * Exit codes (design §6):
13
+ * 0 declaration signature valid (+ consistent with receipts if given), chain contiguous
14
+ * 12 chain has gaps (receipts missing) — use --allow-gaps to verify authenticity only
15
+ * 13 signature invalid / no pubkey / unknown keyId
16
+ * 20 schema invalid
17
+ * 30 inconsistent with receipts (count/seq/coverage mismatch)
18
+ */
19
+ import { createHash, createPublicKey, verify as cryptoVerify } from 'crypto'
20
+ import { readFileSync, existsSync } from 'fs'
21
+
22
+ // v0.1 geriye uyum: eski beyanlar hâlâ doğrulanabilir (kanıtı çöpe atmamak için).
23
+ // v0.2, coverage.unassignedReceiptCount alanını ekler. Hangi sürüm olduğu çıktıda belirtilir.
24
+ const COVERAGE_V = 'conarium-coverage/0.2'
25
+ const COVERAGE_V_LEGACY = 'conarium-coverage/0.1'
26
+
27
+ // ─── JCS subset (must match src/receipt.ts canonicalize) ─────────────────────
28
+
29
+ function canonicalize(obj) {
30
+ return canonValue(obj)
31
+ }
32
+
33
+ function canonValue(v) {
34
+ if (v === null) return 'null'
35
+ if (v === undefined) {
36
+ throw new Error('canonicalize: undefined is not allowed (omit the field)')
37
+ }
38
+ if (typeof v === 'boolean') return v ? 'true' : 'false'
39
+ if (typeof v === 'number') {
40
+ if (!Number.isFinite(v)) throw new Error('canonicalize: non-finite number')
41
+ return JSON.stringify(v)
42
+ }
43
+ if (typeof v === 'string') return JSON.stringify(v)
44
+ if (Array.isArray(v)) {
45
+ return '[' + v.map(canonValue).join(',') + ']'
46
+ }
47
+ if (typeof v === 'object') {
48
+ const keys = Object.keys(v)
49
+ .filter((k) => v[k] !== undefined)
50
+ .sort()
51
+ const parts = []
52
+ for (const k of keys) {
53
+ parts.push(JSON.stringify(k) + ':' + canonValue(v[k]))
54
+ }
55
+ return '{' + parts.join(',') + '}'
56
+ }
57
+ throw new Error(`canonicalize: unsupported type ${typeof v}`)
58
+ }
59
+
60
+ function coverageHash(d) {
61
+ const copy = { ...d }
62
+ delete copy.sig
63
+ const digest = createHash('sha256').update(canonicalize(copy)).digest('hex')
64
+ return `sha256:${digest}`
65
+ }
66
+
67
+ // Exported for cross-check tests (dynamic import of this file).
68
+ export { canonicalize, coverageHash }
69
+
70
+ // ─── CLI ─────────────────────────────────────────────────────────────────────
71
+
72
+ function usage(msg) {
73
+ if (msg) console.error(msg)
74
+ console.error(
75
+ 'Usage: conarium-coverage <declaration.json> --pubkey <path> [--receipts <receipts.jsonl>] [--allow-gaps] [--json]',
76
+ )
77
+ }
78
+
79
+ function parseArgs(argv) {
80
+ const out = { target: null, pubkeys: [], receiptsPath: null, json: false, allowGaps: false }
81
+ const args = [...argv]
82
+ while (args.length) {
83
+ const a = args.shift()
84
+ if (a === '--pubkey') {
85
+ const p = args.shift()
86
+ if (!p) throw new Error('--pubkey requires a path')
87
+ out.pubkeys.push(p)
88
+ } else if (a === '--receipts') {
89
+ const p = args.shift()
90
+ if (!p) throw new Error('--receipts requires a path')
91
+ out.receiptsPath = p
92
+ } else if (a === '--json') {
93
+ out.json = true
94
+ } else if (a === '--allow-gaps') {
95
+ out.allowGaps = true
96
+ } else if (a === '--help' || a === '-h') {
97
+ usage()
98
+ process.exit(0)
99
+ } else if (a.startsWith('-')) {
100
+ throw new Error(`unknown flag: ${a}`)
101
+ } else if (!out.target) {
102
+ out.target = a
103
+ } else {
104
+ throw new Error(`unexpected argument: ${a}`)
105
+ }
106
+ }
107
+ return out
108
+ }
109
+
110
+ function loadVerifyKeys(paths) {
111
+ if (paths.length === 0) {
112
+ return { error: 'no --pubkey given (refusing to skip signature checks)', code: 13 }
113
+ }
114
+ const keys = new Map()
115
+ for (const path of paths) {
116
+ if (!existsSync(path)) {
117
+ return { error: `public key not found: ${path}`, code: 13 }
118
+ }
119
+ let pem
120
+ try {
121
+ pem = readFileSync(path, 'utf-8')
122
+ } catch (err) {
123
+ return { error: `cannot read public key ${path}: ${err.message}`, code: 13 }
124
+ }
125
+ let publicKey
126
+ try {
127
+ publicKey = createPublicKey(pem)
128
+ } catch (err) {
129
+ return { error: `invalid public PEM ${path}: ${err.message}`, code: 13 }
130
+ }
131
+ if (publicKey.asymmetricKeyType !== 'ed25519') {
132
+ return { error: `expected Ed25519 at ${path}, got ${publicKey.asymmetricKeyType}`, code: 13 }
133
+ }
134
+ const sidecar = `${path}.keyid`
135
+ if (!existsSync(sidecar)) {
136
+ return { error: `missing keyId sidecar: ${sidecar}`, code: 13 }
137
+ }
138
+ const keyId = readFileSync(sidecar, 'utf-8').trim()
139
+ if (!keyId) {
140
+ return { error: `empty keyId sidecar: ${sidecar}`, code: 13 }
141
+ }
142
+ keys.set(keyId, publicKey)
143
+ }
144
+ return { keys }
145
+ }
146
+
147
+ function loadDeclaration(path) {
148
+ if (!existsSync(path)) {
149
+ return { error: `declaration not found: ${path}`, code: 20 }
150
+ }
151
+ let obj
152
+ try {
153
+ obj = JSON.parse(readFileSync(path, 'utf-8'))
154
+ } catch (err) {
155
+ return { error: `invalid JSON in declaration: ${err.message}`, code: 20 }
156
+ }
157
+ return { declaration: obj }
158
+ }
159
+
160
+ function loadReceipts(path) {
161
+ if (!existsSync(path)) {
162
+ return { error: `receipts file not found: ${path}`, code: 20 }
163
+ }
164
+ const raw = readFileSync(path, 'utf-8').trim()
165
+ if (!raw) return { receipts: [] }
166
+ const receipts = raw.split('\n').filter(Boolean).map((l) => JSON.parse(l))
167
+ return { receipts }
168
+ }
169
+
170
+ function schemaOk(d) {
171
+ if (!d || typeof d !== 'object') return 'not an object'
172
+ if (d.v !== COVERAGE_V && d.v !== COVERAGE_V_LEGACY) return `unsupported version ${d.v}`
173
+ if (typeof d.id !== 'string' || !d.id) return 'missing id'
174
+ if (typeof d.ts !== 'string') return 'missing ts'
175
+ if (!d.period || typeof d.period !== 'object') return 'missing period'
176
+ if (typeof d.period.start !== 'string' || typeof d.period.end !== 'string') {
177
+ return 'period.start/end must be strings'
178
+ }
179
+ if (!Array.isArray(d.declaredScope) || d.declaredScope.length === 0) {
180
+ return 'declaredScope must be a non-empty array'
181
+ }
182
+ if (!d.chain || typeof d.chain !== 'object') return 'missing chain'
183
+ if (!Number.isInteger(d.chain.firstSeq)) return 'chain.firstSeq not integer'
184
+ if (!Number.isInteger(d.chain.lastSeq)) return 'chain.lastSeq not integer'
185
+ if (!Number.isInteger(d.chain.count)) return 'chain.count not integer'
186
+ if (typeof d.chain.contiguous !== 'boolean') return 'chain.contiguous not boolean'
187
+ if (!Array.isArray(d.chain.gaps)) return 'chain.gaps must be an array'
188
+ if (!d.decisions || typeof d.decisions !== 'object') return 'missing decisions'
189
+ for (const k of ['allow', 'partial', 'deny']) {
190
+ if (!Number.isInteger(d.decisions[k])) return `decisions.${k} not integer`
191
+ }
192
+ if (!d.coverage || typeof d.coverage !== 'object') return 'missing coverage'
193
+ if (!Number.isInteger(d.coverage.declared)) return 'coverage.declared not integer'
194
+ if (!Number.isInteger(d.coverage.accessed)) return 'coverage.accessed not integer'
195
+ if (!Number.isInteger(d.coverage.notRecorded)) return 'coverage.notRecorded not integer'
196
+ if (!Array.isArray(d.coverage.accessedObjects)) return 'coverage.accessedObjects must be an array'
197
+ if (!Array.isArray(d.coverage.notRecordedObjects)) return 'coverage.notRecordedObjects must be an array'
198
+ // v0.2: unassignedReceiptCount zorunlu. v0.1'de alan yoktu — geriye uyum için yoksa 0 varsay.
199
+ if (d.v === COVERAGE_V && !Number.isInteger(d.coverage.unassignedReceiptCount)) {
200
+ return 'coverage.unassignedReceiptCount not integer'
201
+ }
202
+ if (!d.sig || typeof d.sig !== 'object') return 'missing sig'
203
+ if (d.sig.alg !== 'Ed25519') return `unsupported sig.alg ${d.sig.alg}`
204
+ if (typeof d.sig.keyId !== 'string' || !d.sig.keyId) return 'missing sig.keyId'
205
+ if (typeof d.sig.value !== 'string' || !d.sig.value) return 'missing sig.value'
206
+ return null
207
+ }
208
+
209
+ function verifySig(keys, d) {
210
+ const pk = keys.get(d.sig.keyId)
211
+ if (!pk) return `unknown keyId ${d.sig.keyId}`
212
+ try {
213
+ const ok = cryptoVerify(
214
+ null,
215
+ Buffer.from(coverageHash(d), 'utf-8'),
216
+ pk,
217
+ Buffer.from(d.sig.value, 'base64'),
218
+ )
219
+ return ok ? null : 'signature cryptographically invalid'
220
+ } catch (err) {
221
+ return `signature verify error: ${err.message}`
222
+ }
223
+ }
224
+
225
+ /**
226
+ * Beyanı makbuzlarla çapraz kontrol et. Tutarsızlık → hata metni döner, tutarlıysa null.
227
+ * Dürüstlük kuralı: coverage.notRecordedObjects "erişim KAYDEDİLMEDİ" anlamına gelir,
228
+ * "erişilmedi" değil — bu metinlerde de korunur.
229
+ */
230
+ function crossCheck(d, receipts) {
231
+ if (receipts.length === 0) {
232
+ return 'declaration claims coverage over receipts but --receipts file is empty'
233
+ }
234
+ // count
235
+ if (receipts.length !== d.chain.count) {
236
+ return `count mismatch: declaration says ${d.chain.count}, receipts file has ${receipts.length}`
237
+ }
238
+ // seq aralığı + kesintisizlik
239
+ const seqs = receipts.map((r) => r.chain.seq).sort((a, b) => a - b)
240
+ if (seqs[0] !== d.chain.firstSeq) {
241
+ return `firstSeq mismatch: declaration says ${d.chain.firstSeq}, receipts start at ${seqs[0]}`
242
+ }
243
+ if (seqs[seqs.length - 1] !== d.chain.lastSeq) {
244
+ return `lastSeq mismatch: declaration says ${d.chain.lastSeq}, receipts end at ${seqs[seqs.length - 1]}`
245
+ }
246
+ const gaps = []
247
+ for (let expected = seqs[0]; expected < seqs[seqs.length - 1]; expected++) {
248
+ if (!seqs.includes(expected)) {
249
+ let found = expected + 1
250
+ while (found <= seqs[seqs.length - 1] && !seqs.includes(found)) found++
251
+ gaps.push({ expectedSeq: expected, foundSeq: found })
252
+ }
253
+ }
254
+ const contiguous = gaps.length === 0
255
+ if (contiguous !== d.chain.contiguous) {
256
+ return `contiguous mismatch: declaration says ${d.chain.contiguous}, receipts are ${contiguous}`
257
+ }
258
+ if (gaps.length !== d.chain.gaps.length) {
259
+ return `gap count mismatch: declaration says ${d.chain.gaps.length}, receipts have ${gaps.length}`
260
+ }
261
+ for (let i = 0; i < gaps.length; i++) {
262
+ if (gaps[i].expectedSeq !== d.chain.gaps[i].expectedSeq || gaps[i].foundSeq !== d.chain.gaps[i].foundSeq) {
263
+ return `gap mismatch at index ${i}: declaration ${JSON.stringify(d.chain.gaps[i])}, receipts ${JSON.stringify(gaps[i])}`
264
+ }
265
+ }
266
+ // decisions
267
+ const dec = { allow: 0, partial: 0, deny: 0 }
268
+ for (const r of receipts) {
269
+ if (r.policy.decision === 'allow') dec.allow++
270
+ else if (r.policy.decision === 'partial') dec.partial++
271
+ else if (r.policy.decision === 'deny') dec.deny++
272
+ }
273
+ for (const k of ['allow', 'partial', 'deny']) {
274
+ if (dec[k] !== d.decisions[k]) {
275
+ return `decisions.${k} mismatch: declaration says ${d.decisions[k]}, receipts have ${dec[k]}`
276
+ }
277
+ }
278
+ // coverage — aynı mantık src/coverage.ts computeCoverage ile birebir:
279
+ // nesne kaynağı dataRefs[].object + describe_table'da request.target (ikinci kanıt).
280
+ // list_tables veri erişimi değil (sema listeleme) — nesne sayılmaz.
281
+ const recorded = new Set()
282
+ let unassignedReceiptCount = 0
283
+ for (const r of receipts) {
284
+ let hasObject = false
285
+ for (const ref of r.dataRefs || []) {
286
+ recorded.add(ref.object)
287
+ hasObject = true
288
+ }
289
+ if (r.request?.tool === 'describe_table' && r.request?.target) {
290
+ recorded.add(r.request.target)
291
+ hasObject = true
292
+ }
293
+ if (!hasObject && (r.request?.tool === 'query' || r.request?.tool === 'search')) {
294
+ unassignedReceiptCount++
295
+ }
296
+ }
297
+ const accessedObjects = d.declaredScope.filter((o) => recorded.has(o))
298
+ const notRecordedObjects = d.declaredScope.filter((o) => !recorded.has(o))
299
+ if (accessedObjects.length !== d.coverage.accessed) {
300
+ return `coverage.accessed mismatch: declaration says ${d.coverage.accessed}, receipts show ${accessedObjects.length}`
301
+ }
302
+ if (notRecordedObjects.length !== d.coverage.notRecorded) {
303
+ return `coverage.notRecorded mismatch: declaration says ${d.coverage.notRecorded}, receipts show ${notRecordedObjects.length}`
304
+ }
305
+ // v0.2: belirsizlik sayacı makbuzlardan hesaplanıp beyanla karşılaştırılır.
306
+ // v0.1'de alan yoktu — geriye uyum için atla.
307
+ if (d.v === COVERAGE_V && unassignedReceiptCount !== d.coverage.unassignedReceiptCount) {
308
+ return `coverage.unassignedReceiptCount mismatch: declaration says ${d.coverage.unassignedReceiptCount}, receipts show ${unassignedReceiptCount}`
309
+ }
310
+ for (const o of d.coverage.accessedObjects) {
311
+ if (!accessedObjects.includes(o)) {
312
+ return `coverage.accessedObjects contains "${o}" but receipts show no recorded access to it`
313
+ }
314
+ }
315
+ for (const o of d.coverage.notRecordedObjects) {
316
+ if (!notRecordedObjects.includes(o)) {
317
+ return `coverage.notRecordedObjects contains "${o}" but receipts show recorded access to it`
318
+ }
319
+ }
320
+ return null
321
+ }
322
+
323
+ function fail(code, message, jsonMode, extra = {}) {
324
+ const payload = { ok: false, code, message, ...extra }
325
+ console.error(message)
326
+ if (jsonMode) console.log(JSON.stringify(payload))
327
+ process.exit(code)
328
+ }
329
+
330
+ async function main(argv = process.argv.slice(2)) {
331
+ let opts
332
+ try {
333
+ opts = parseArgs(argv)
334
+ } catch (err) {
335
+ usage(err.message)
336
+ process.exit(20)
337
+ }
338
+ if (!opts.target) {
339
+ usage('missing <declaration.json>')
340
+ process.exit(20)
341
+ }
342
+
343
+ const keyResult = loadVerifyKeys(opts.pubkeys)
344
+ if (keyResult.error) {
345
+ fail(keyResult.code, keyResult.error, opts.json)
346
+ }
347
+ const { keys } = keyResult
348
+
349
+ const declResult = loadDeclaration(opts.target)
350
+ if (declResult.error) {
351
+ fail(declResult.code, declResult.error, opts.json)
352
+ }
353
+ const d = declResult.declaration
354
+
355
+ const schemaErr = schemaOk(d)
356
+ if (schemaErr) {
357
+ fail(20, `schema invalid: ${schemaErr}`, opts.json)
358
+ }
359
+
360
+ const expected = coverageHash(d)
361
+ // coverageHash strips sig; recompute over the body and compare against stored hash
362
+ // is not stored in the declaration (hash is implicit in sig). We verify sig directly.
363
+ const sigErr = verifySig(keys, d)
364
+ if (sigErr) {
365
+ fail(13, `signature invalid: ${sigErr}`, opts.json)
366
+ }
367
+
368
+ if (opts.receiptsPath) {
369
+ const recResult = loadReceipts(opts.receiptsPath)
370
+ if (recResult.error) {
371
+ fail(recResult.code, recResult.error, opts.json)
372
+ }
373
+ const crossErr = crossCheck(d, recResult.receipts)
374
+ if (crossErr) {
375
+ fail(30, `inconsistent with receipts: ${crossErr}`, opts.json)
376
+ }
377
+ }
378
+
379
+ // Zincir kesintisizliği: CI'da sorulan soru "kapsamam eksiksiz mi?" (b).
380
+ // Zincirde boşluk = makbuz EKSİK = kapsam eksik. Varsayılan SIKI: boşluk varsa
381
+ // "ok:" yazma ve EXIT 12 ver (conarium-verify'daki seq gap ile aynı anlam).
382
+ // --allow-gaps yalnızca ozgunluk sorusu (a) sorulduğunda EXIT 0 döndürür.
383
+ if (!d.chain.contiguous && !opts.allowGaps) {
384
+ const gapDesc = d.chain.gaps
385
+ .map((g) => `seq ${g.expectedSeq} (found ${g.foundSeq})`)
386
+ .join(', ')
387
+ const msg =
388
+ `chain has ${d.chain.gaps.length} gap(s): ${gapDesc}; ` +
389
+ `receipt chain is NOT contiguous — coverage is incomplete. ` +
390
+ `(use --allow-gaps to verify authenticity only)`
391
+ fail(12, msg, opts.json, { gaps: d.chain.gaps })
392
+ }
393
+
394
+ if (opts.json) {
395
+ console.log(JSON.stringify({ ok: true, code: 0, declaration: d.id, version: d.v }))
396
+ } else {
397
+ const unassigned = d.v === COVERAGE_V ? d.coverage.unassignedReceiptCount : 0
398
+ console.log(
399
+ `ok: coverage declaration ${d.id} verified (version ${d.v}, ${d.chain.count} receipts, ` +
400
+ `contiguous=${d.chain.contiguous}, accessed=${d.coverage.accessed}, ` +
401
+ `notRecorded=${d.coverage.notRecorded})`,
402
+ )
403
+ // Belirsizlik uyarısı: notRecorded listesi ancak unassigned=0 iken "kesin" sayılabilir.
404
+ // "erişilmedi"/"not accessed" ifadesi YASAK — kaydın yokluğu belirsizdir, erişim yokluğu değil.
405
+ if (unassigned > 0) {
406
+ console.warn(
407
+ `warning: notRecorded=${d.coverage.notRecorded} (${unassigned} receipt(s) could not be attributed ` +
408
+ `to a specific object; this list is NOT definitive)`,
409
+ )
410
+ }
411
+ }
412
+ process.exit(0)
413
+ }
414
+
415
+ const isDirect =
416
+ process.argv[1] &&
417
+ (process.argv[1].endsWith('conarium-coverage.mjs') ||
418
+ process.argv[1].endsWith('conarium-coverage'))
419
+
420
+ if (isDirect) {
421
+ main().catch((err) => {
422
+ console.error(err)
423
+ process.exit(20)
424
+ })
425
+ }