dsh-policy-ledger 0.0.0-stage → 0.2.0-alpha.3

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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,5 @@
1
+ dsh-policy-ledger
2
+ Copyright 2026 PerryLink
3
+
4
+ Uses fflate (MIT) and zod (MIT). Public demo uses synthetic package tarballs;
5
+ no customer profile, registry token, or private package is included.
package/README.md CHANGED
@@ -1,3 +1,72 @@
1
- # Temporary Holding Version
1
+ # dsh-policy-ledger
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Read-only capability snapshot, tarball assert and install diagnosis for DeepSeek Harness.
4
+
5
+ > **Status: alpha / public-synthetic / partial / not counted / not GA.** No customer evidence, customer data, or production-readiness claim. All acceptance rows are `counted=false`.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ dsh plugin --profile <profile> add dsh-policy-ledger
11
+ dsh --profile <profile> --dump-config | grep dsh-policy-ledger
12
+ ```
13
+
14
+ CLI:
15
+
16
+ ```sh
17
+ dsh-policy-ledger doctor ./some-package.tgz --json
18
+ ```
19
+
20
+ Requires DSH `>=0.2.1-rc.3 <0.3.0` and Node `>=24.9 <25`.
21
+
22
+ <details>
23
+ <summary>中文摘要</summary>
24
+
25
+ 只读安装诊断:能力快照、tarball 断言与安装日志分类。 安装:`dsh plugin --profile <profile> add dsh-policy-ledger`。公开/合成、alpha、非 GA。
26
+
27
+ </details>
28
+
29
+ ## Tools
30
+
31
+ | Tool | What it does | Risk |
32
+ |---|---|---|
33
+ | `trust.capability_snapshot` | Extract declared capabilities and R0–R3 risk from a local npm `.tgz`: tools, bundle/client/bin/skill, build scripts, outbound hosts, credential references | R0 local read |
34
+ | `trust.diff` | Compare two stored snapshots: added/removed capabilities, risk escalation, blockers | R0 |
35
+ | `trust.assert_tarball` | Re-read a tarball and compare it with a stored snapshot: pass/missing/extra/changed/unknown | R0 |
36
+ | `install.diagnose` | Classify an install log into stage, root cause and three actions; return unknown rather than guess | R0 |
37
+ | `install.probe` | Check disk free, write permission, proxy, optional registry RTT, node/pnpm | R0 |
38
+ | `install.bundle` | Write a redacted incident ZIP (diagnosis + evidence lines) | R1 local write |
39
+
40
+ ## Input / output
41
+
42
+ **Input:** a local npm `.tgz`, a stored snapshot, an install log, or the local environment. **Output:** a capability snapshot, snapshot diff, tarball assert result, install diagnosis, environment probe, or redacted incident ZIP. The CLI exposes `dsh-policy-ledger doctor <tgz> --json`.
43
+
44
+ ## Configuration
45
+
46
+ | Env | Default | Meaning |
47
+ |---|---|---|
48
+ | `DSH_TRUST_HOME` | `$DSH_HOME/storages/dsh-policy-ledger` | bundles and local storage |
49
+ | `DSH_TRUST_INPUT_ROOTS` | `current working directory` | tarball allowlist |
50
+
51
+ ## Limits / non-claims
52
+
53
+ - This is **not** a policy ledger, Gate, ledger, rollback, retry, or profile five-state product; the package name is retained for npm continuity.
54
+ - No signing root, no policy evaluation/apply/rollback/receipt, no Client, Skill, or Bundle surface.
55
+ - No customer profile, registry token, or private package is included.
56
+ - `install.bundle` writes a local redacted ZIP; it does not upload anything.
57
+ - No customer evidence, customer data, or production-readiness claim; all fixtures are public/synthetic.
58
+
59
+ ## Public sample
60
+
61
+ Public/synthetic tarballs and install-log fixtures; `ACCEPTANCE.csv` lists 4 public checks. No customer profile is included.
62
+
63
+ ## Development
64
+
65
+ ```sh
66
+ pnpm install --frozen-lockfile
67
+ pnpm build && pnpm lint && pnpm typecheck && pnpm test && pnpm gate:sku03
68
+ ```
69
+
70
+ ## License
71
+
72
+ Apache-2.0. See `LICENSE`, `NOTICE`, `THIRD-PARTY-NOTICES`.
@@ -0,0 +1,6 @@
1
+ Third-party notices for dsh-policy-ledger
2
+
3
+ - fflate (MIT)
4
+ - zod (MIT)
5
+
6
+ No customer profiles, registry tokens, or private packages are included.
@@ -0,0 +1,30 @@
1
+ #!/usr/bin/env node
2
+ /** Minimal CLI: dsh-policy-ledger doctor <package.tgz> [--json] */
3
+ import { readFileSync } from 'node:fs'
4
+ import { inspectPackageTarball } from '../lib/adapters/tarball.js'
5
+
6
+ const args = process.argv.slice(2)
7
+ const command = args[0]
8
+ if (command !== 'doctor' || !args[1]) {
9
+ console.error('usage: dsh-policy-ledger doctor <package.tgz> [--json]')
10
+ process.exit(64)
11
+ }
12
+ const file = args[1]
13
+ try {
14
+ const snapshot = inspectPackageTarball(readFileSync(file), file)
15
+ if (args.includes('--json')) {
16
+ console.log(JSON.stringify(snapshot, null, 2))
17
+ } else {
18
+ console.log(`package: ${snapshot.name}@${snapshot.version}`)
19
+ console.log(`risk: ${snapshot.risk} (extractor ${snapshot.extractor_version})`)
20
+ console.log(`capabilities: ${snapshot.caps.length}`)
21
+ for (const cap of snapshot.caps) console.log(` - ${cap.kind}: ${cap.name}${cap.detail ? ` (${cap.detail})` : ''}`)
22
+ if (snapshot.outbound_hosts.length) console.log(`outbound hosts: ${snapshot.outbound_hosts.join(', ')}`)
23
+ if (snapshot.build_scripts.length) console.log(`build scripts: ${snapshot.build_scripts.join(', ')}`)
24
+ if (snapshot.unknowns.length) console.log(`unknowns: ${snapshot.unknowns.join('; ')}`)
25
+ }
26
+ process.exit(snapshot.risk === 'R3' ? 2 : 0)
27
+ } catch (error) {
28
+ console.error(error instanceof Error ? error.message : String(error))
29
+ process.exit(1)
30
+ }
@@ -0,0 +1,3 @@
1
+ - insert:
2
+ - id: dsh-policy-ledger
3
+ name: 'dsh-policy-ledger'
@@ -0,0 +1,2 @@
1
+ import { type Snapshot } from '../core/trust.js';
2
+ export declare function inspectPackageTarball(buffer: Buffer, specLabel?: string): Snapshot;
@@ -0,0 +1,151 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { gunzipSync } from 'node:zlib';
3
+ import { EXTRACTOR_VERSION, TrustError, canonicalJson, riskFromCaps, } from '../core/trust.js';
4
+ const MAX_PARTS = 5000;
5
+ const MAX_BYTES = 100 * 1024 * 1024;
6
+ function sha256(bytes) {
7
+ return createHash('sha256').update(bytes).digest('hex');
8
+ }
9
+ function parseOctal(bytes) {
10
+ const value = Buffer.from(bytes).toString('ascii').replace(/\0/g, '').trim();
11
+ if (!value)
12
+ return 0;
13
+ const parsed = Number.parseInt(value, 8);
14
+ return Number.isFinite(parsed) ? parsed : 0;
15
+ }
16
+ function tarEntries(buffer) {
17
+ let tar;
18
+ try {
19
+ tar = gunzipSync(buffer);
20
+ }
21
+ catch {
22
+ throw new TrustError('E_TRUST_TARBALL_INVALID', 'not a gzip-compressed npm tarball');
23
+ }
24
+ const entries = new Map();
25
+ let offset = 0;
26
+ let total = 0;
27
+ while (offset + 512 <= tar.length) {
28
+ const header = tar.subarray(offset, offset + 512);
29
+ if (header.every((byte) => byte === 0))
30
+ break;
31
+ let name = header.subarray(0, 100).toString('utf8').replace(/\0.*$/, '');
32
+ const prefix = header.subarray(345, 500).toString('utf8').replace(/\0.*$/, '');
33
+ if (prefix)
34
+ name = `${prefix}/${name}`;
35
+ const size = parseOctal(header.subarray(124, 136));
36
+ const type = String.fromCharCode(header[156] ?? 0);
37
+ offset += 512;
38
+ if (size < 0 || offset + size > tar.length)
39
+ throw new TrustError('E_TRUST_TARBALL_INVALID', 'truncated tar entry');
40
+ if (type === '0' || type === '\0') {
41
+ if (name.startsWith('package/')) {
42
+ const relative = name.slice('package/'.length);
43
+ if (relative)
44
+ entries.set(relative, tar.subarray(offset, offset + size));
45
+ total += size;
46
+ if (entries.size > MAX_PARTS)
47
+ throw new TrustError('E_TRUST_TARBALL_LIMIT', `too many entries: ${entries.size}`);
48
+ if (total > MAX_BYTES)
49
+ throw new TrustError('E_TRUST_TARBALL_LIMIT', 'uncompressed tarball too large');
50
+ }
51
+ }
52
+ offset += Math.ceil(size / 512) * 512;
53
+ }
54
+ return entries;
55
+ }
56
+ function textOf(entries, name) {
57
+ const value = entries.get(name);
58
+ return value ? Buffer.from(value).toString('utf8') : undefined;
59
+ }
60
+ function hostsOf(text) {
61
+ const hosts = new Set();
62
+ for (const match of text.matchAll(/https?:\/\/([^/\s"'<>]+)/g)) {
63
+ const host = (match[1] ?? '').toLowerCase();
64
+ if (!host)
65
+ continue;
66
+ if (['github.com', 'www.npmjs.com', 'npmjs.com', 'registry.npmjs.org', 'www.w3.org', 'schemas.openxmlformats.org', 'json-schema.org', 'opensource.org'].includes(host))
67
+ continue;
68
+ hosts.add(host);
69
+ }
70
+ return [...hosts].sort();
71
+ }
72
+ function credsOf(text) {
73
+ const creds = new Set();
74
+ for (const match of text.matchAll(/\b(Authorization|API[_-]?KEY|ACCESS[_-]?TOKEN|SECRET[_-]?KEY|PASSWORD|CREDENTIALS?)\b/gi)) {
75
+ creds.add(match[1].toUpperCase());
76
+ }
77
+ return [...creds].sort();
78
+ }
79
+ export function inspectPackageTarball(buffer, specLabel) {
80
+ if (buffer.length === 0)
81
+ throw new TrustError('E_TRUST_FILE_UNREADABLE', 'empty tarball');
82
+ const entries = tarEntries(buffer);
83
+ const packageJsonText = textOf(entries, 'package.json');
84
+ if (!packageJsonText)
85
+ throw new TrustError('E_TRUST_TARBALL_INVALID', 'tarball has no package/package.json');
86
+ let pkg;
87
+ try {
88
+ pkg = JSON.parse(packageJsonText);
89
+ }
90
+ catch {
91
+ throw new TrustError('E_TRUST_TARBALL_INVALID', 'package.json is not valid JSON');
92
+ }
93
+ const name = typeof pkg.name === 'string' ? pkg.name : '';
94
+ const version = typeof pkg.version === 'string' ? pkg.version : '';
95
+ if (!name || !version)
96
+ throw new TrustError('E_TRUST_TARBALL_INVALID', 'package.json lacks name/version');
97
+ const dsh = pkg.dsh && typeof pkg.dsh === 'object' ? pkg.dsh : {};
98
+ const scripts = pkg.scripts && typeof pkg.scripts === 'object' ? pkg.scripts : {};
99
+ const bin = pkg.bin && typeof pkg.bin === 'object' ? Object.keys(pkg.bin) : [];
100
+ const caps = [];
101
+ if (dsh.bundle)
102
+ caps.push({ kind: 'bundle', name: 'dsh.bundle', detail: 'bundle patch' });
103
+ if (dsh.client)
104
+ caps.push({ kind: 'client', name: 'dsh.client', detail: 'web client' });
105
+ for (const command of bin)
106
+ caps.push({ kind: 'bin', name: command });
107
+ if (Array.isArray(dsh.skills))
108
+ for (const skill of dsh.skills)
109
+ caps.push({ kind: 'skill', name: String(skill) });
110
+ const sourceEntries = [...entries.entries()].filter(([entry]) => /\.(?:js|mjs|cjs|ts|tsx|jsx)$/.test(entry));
111
+ const sourceText = sourceEntries.map(([, bytes]) => Buffer.from(bytes).toString('utf8')).join('\n');
112
+ const toolNames = new Set();
113
+ for (const match of sourceText.matchAll(/defineTool\s*\(\s*\{[\s\S]{0,500}?name\s*:\s*['"]([^'"]+)['"]/g))
114
+ toolNames.add(match[1]);
115
+ for (const tool of toolNames)
116
+ caps.push({ kind: 'tool', name: tool });
117
+ const buildScripts = ['preinstall', 'install', 'postinstall', 'prepare'].filter((key) => typeof scripts[key] === 'string');
118
+ for (const script of buildScripts)
119
+ caps.push({ kind: 'build-script', name: script, detail: String(scripts[script]) });
120
+ const allText = [packageJsonText, textOf(entries, 'README.md') ?? '', sourceText].join('\n');
121
+ const outboundHosts = hostsOf(allText);
122
+ for (const host of outboundHosts)
123
+ caps.push({ kind: 'network', name: host });
124
+ const credRefs = credsOf(allText);
125
+ for (const cred of credRefs)
126
+ caps.push({ kind: 'credential', name: cred });
127
+ const unknowns = [];
128
+ if (sourceEntries.length === 0)
129
+ unknowns.push('no executable source file parsed');
130
+ if (dsh.bundle && !textOf(entries, 'cordis.patch.yml'))
131
+ unknowns.push('dsh.bundle declared without cordis.patch.yml');
132
+ const risk = riskFromCaps(caps, outboundHosts, buildScripts, credRefs);
133
+ const integrity = sha256(buffer);
134
+ const snapshotId = `snap_${sha256(Buffer.from(canonicalJson({ name, version, integrity, caps, risk }))).slice(0, 24)}`;
135
+ return {
136
+ snapshot_id: snapshotId,
137
+ spec: specLabel ?? `${name}@${version}`,
138
+ name,
139
+ version,
140
+ integrity,
141
+ caps,
142
+ tool_names: [...toolNames].sort(),
143
+ outbound_hosts: outboundHosts,
144
+ cred_refs: credRefs,
145
+ build_scripts: buildScripts,
146
+ risk,
147
+ source: 'extracted',
148
+ extractor_version: EXTRACTOR_VERSION,
149
+ unknowns,
150
+ };
151
+ }
@@ -0,0 +1,55 @@
1
+ export type Risk = 'R0' | 'R1' | 'R2' | 'R3';
2
+ export type CapabilityKind = 'bundle' | 'client' | 'bin' | 'skill' | 'tool' | 'build-script' | 'network' | 'credential';
3
+ export interface Capability {
4
+ kind: CapabilityKind;
5
+ name: string;
6
+ detail?: string;
7
+ }
8
+ export interface Snapshot {
9
+ snapshot_id: string;
10
+ spec: string;
11
+ name: string;
12
+ version: string;
13
+ integrity: string;
14
+ caps: Capability[];
15
+ tool_names: string[];
16
+ outbound_hosts: string[];
17
+ cred_refs: string[];
18
+ build_scripts: string[];
19
+ risk: Risk;
20
+ source: 'extracted';
21
+ extractor_version: string;
22
+ unknowns: string[];
23
+ }
24
+ export interface DiffResult {
25
+ added_caps: Capability[];
26
+ removed_caps: Capability[];
27
+ risk_from: Risk;
28
+ risk_to: Risk;
29
+ escalated: boolean;
30
+ blockers: string[];
31
+ }
32
+ export type TrustErrorCode = 'E_TRUST_FILE_UNREADABLE' | 'E_TRUST_TARBALL_INVALID' | 'E_TRUST_TARBALL_LIMIT' | 'E_TRUST_CAP_UNKNOWN' | 'E_TRUST_SNAPSHOT_NOT_FOUND' | 'E_TRUST_ASSERT_FAILED' | 'E_TRUST_DIAGNOSE_UNKNOWN' | 'E_TRUST_BUNDLE_FAILED' | 'E_TRUST_PATH_NOT_ALLOWED';
33
+ export declare class TrustError extends Error {
34
+ readonly code: TrustErrorCode;
35
+ readonly retryable: boolean;
36
+ readonly needsReview: boolean;
37
+ constructor(code: TrustErrorCode, message: string, options?: {
38
+ retryable?: boolean;
39
+ needsReview?: boolean;
40
+ });
41
+ }
42
+ export declare const EXTRACTOR_VERSION = "1.0.0";
43
+ export declare const RISK_ORDER: Record<Risk, number>;
44
+ export declare function canonicalJson(value: unknown): string;
45
+ export declare function riskFromCaps(caps: Capability[], hosts: string[], buildScripts: string[], credRefs: string[]): Risk;
46
+ export declare function diffSnapshots(from: Snapshot, to: Snapshot): DiffResult;
47
+ export interface Diagnosis {
48
+ stage: 'resolve' | 'fetch' | 'extract' | 'link' | 'build' | 'activate' | 'unknown';
49
+ error_code: string;
50
+ root_cause: string;
51
+ actions: string[];
52
+ confidence: number;
53
+ evidence_lines: string[];
54
+ }
55
+ export declare function classifyInstallLog(logText: string): Diagnosis;
@@ -0,0 +1,110 @@
1
+ export class TrustError extends Error {
2
+ code;
3
+ retryable;
4
+ needsReview;
5
+ constructor(code, message, options = {}) {
6
+ super(`${code}: ${message}`);
7
+ this.name = 'TrustError';
8
+ this.code = code;
9
+ this.retryable = options.retryable ?? false;
10
+ this.needsReview = options.needsReview ?? false;
11
+ }
12
+ }
13
+ export const EXTRACTOR_VERSION = '1.0.0';
14
+ export const RISK_ORDER = { R0: 0, R1: 1, R2: 2, R3: 3 };
15
+ export function canonicalJson(value) {
16
+ if (value === null || typeof value !== 'object')
17
+ return JSON.stringify(value);
18
+ if (Array.isArray(value))
19
+ return `[${value.map(canonicalJson).join(',')}]`;
20
+ const entries = Object.entries(value).sort(([a], [b]) => a.localeCompare(b));
21
+ return `{${entries.map(([key, child]) => `${JSON.stringify(key)}:${canonicalJson(child)}`).join(',')}}`;
22
+ }
23
+ export function riskFromCaps(caps, hosts, buildScripts, credRefs) {
24
+ let score = 0;
25
+ if (caps.some((cap) => cap.kind === 'bundle'))
26
+ score += 1;
27
+ if (caps.some((cap) => cap.kind === 'client'))
28
+ score += 1;
29
+ if (caps.some((cap) => cap.kind === 'bin'))
30
+ score += 1;
31
+ if (buildScripts.length > 0)
32
+ score += 2;
33
+ if (hosts.length > 0)
34
+ score += 2;
35
+ if (credRefs.length > 0)
36
+ score += 2;
37
+ if (score >= 3)
38
+ return 'R3';
39
+ if (score === 2)
40
+ return 'R2';
41
+ if (score === 1)
42
+ return 'R1';
43
+ return 'R0';
44
+ }
45
+ export function diffSnapshots(from, to) {
46
+ const key = (cap) => `${cap.kind}:${cap.name}`;
47
+ const fromKeys = new Set(from.caps.map(key));
48
+ const toKeys = new Set(to.caps.map(key));
49
+ const added = to.caps.filter((cap) => !fromKeys.has(key(cap)));
50
+ const removed = from.caps.filter((cap) => !toKeys.has(key(cap)));
51
+ const escalated = RISK_ORDER[to.risk] > RISK_ORDER[from.risk];
52
+ const blockers = [];
53
+ if (escalated)
54
+ blockers.push(`risk escalated ${from.risk} -> ${to.risk}`);
55
+ if (to.build_scripts.length > from.build_scripts.length)
56
+ blockers.push('new build script');
57
+ if (to.cred_refs.length > from.cred_refs.length)
58
+ blockers.push('new credential reference');
59
+ if (to.outbound_hosts.some((host) => !from.outbound_hosts.includes(host)))
60
+ blockers.push('new outbound host');
61
+ return { added_caps: added, removed_caps: removed, risk_from: from.risk, risk_to: to.risk, escalated, blockers };
62
+ }
63
+ export function classifyInstallLog(logText) {
64
+ const lines = logText.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
65
+ const pick = (pattern) => lines.filter((line) => pattern.test(line)).slice(0, 3);
66
+ const evidence = (pattern) => {
67
+ const matched = pick(pattern);
68
+ return matched.length > 0 ? matched : lines.slice(0, 2);
69
+ };
70
+ const make = (stage, code, root, actions, confidence = 0.9) => ({
71
+ stage,
72
+ error_code: code,
73
+ root_cause: root,
74
+ actions,
75
+ confidence,
76
+ evidence_lines: evidence(new RegExp(code.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'i')),
77
+ });
78
+ if (/ERR_PNPM_.*404|404 Not Found|E404/i.test(logText)) {
79
+ return make('resolve', 'E_TRUST_RESOLVE_404', 'package or version not found in the configured registry', ['verify scoped name and version', 'check registry and auth', 'retry with the exact version/tarball']);
80
+ }
81
+ if (/EACCES|EPERM|permission denied/i.test(logText)) {
82
+ return make('link', 'E_TRUST_LINK_EACCES', 'filesystem permission denied while linking', ['check profile directory permissions', 'close other DSH processes', 'retry once']);
83
+ }
84
+ if (/ETIMEDOUT|ENOTFOUND|ECONNREFUSED|network/i.test(logText)) {
85
+ return make('fetch', 'E_TRUST_FETCH_NETWORK', 'registry or network unreachable', ['check proxy/DNS', 'retry with backoff', 'use a local tarball']);
86
+ }
87
+ if (/ENOSPC|no space/i.test(logText)) {
88
+ return make('extract', 'E_TRUST_EXTRACT_NOSPC', 'disk full while extracting', ['free disk space', 'move store/cache', 'retry']);
89
+ }
90
+ if (/ERR_PNPM_PEER_DEP_ISSUES|peer dependenc/i.test(logText)) {
91
+ return make('resolve', 'E_TRUST_RESOLVE_PEER', 'peer dependency conflict', ['inspect peer ranges', 'pin compatible versions', 'do not force-install silently']);
92
+ }
93
+ if (/postinstall|preinstall|install script|build script/i.test(logText)) {
94
+ return make('build', 'E_TRUST_BUILD_SCRIPT', 'install/build script failed', ['capture the script output', 'run the build locally', 'disable the script only with explicit review']);
95
+ }
96
+ if (/integrity|EINTEGRITY|checksum/i.test(logText)) {
97
+ return make('fetch', 'E_TRUST_FETCH_INTEGRITY', 'integrity/checksum mismatch', ['clear cache', 're-download the tarball', 'verify registry and lockfile']);
98
+ }
99
+ if (/activate|mount|plugin.*failed|apply/i.test(logText)) {
100
+ return make('activate', 'E_TRUST_ACTIVATE_FAILED', 'plugin activation/apply failed after install', ['check DSH logs', 'inspect the plugin manifest', 'rollback or remove']);
101
+ }
102
+ return {
103
+ stage: 'unknown',
104
+ error_code: 'E_TRUST_DIAGNOSE_UNKNOWN',
105
+ root_cause: 'not enough evidence to classify; refusing to guess',
106
+ actions: ['provide the full install log', 'run install.probe', 'escalate to a human'],
107
+ confidence: 0,
108
+ evidence_lines: lines.slice(0, 2),
109
+ };
110
+ }
@@ -0,0 +1,5 @@
1
+ /** DSH Host entry for SKU-03 S1 (read-only capability/installation doctor). */
2
+ import type { Context } from '@deepseek-ai/cordis';
3
+ export declare const name = "dsh-policy-ledger";
4
+ export declare const inject: string[];
5
+ export declare function apply(ctx: Context): Promise<void>;
@@ -0,0 +1,13 @@
1
+ /** DSH Host entry for SKU-03 S1 (read-only capability/installation doctor). */
2
+ import path from 'node:path';
3
+ import { createTools } from './tools.js';
4
+ import { openTrustTables } from './storage.js';
5
+ export const name = 'dsh-policy-ledger';
6
+ export const inject = ['tools', 'storageDomain'];
7
+ export async function apply(ctx) {
8
+ const baseDir = process.env.DSH_TRUST_HOME ?? path.join(process.env.DSH_HOME ?? process.cwd(), 'storages', 'dsh-policy-ledger');
9
+ const roots = (process.env.DSH_TRUST_INPUT_ROOTS ?? process.cwd()).split(path.delimiter).map((entry) => entry.trim()).filter(Boolean);
10
+ const { snapshots, incidents } = await openTrustTables(ctx);
11
+ for (const tool of createTools({ snapshots, incidents, baseDir, inputRoots: roots }))
12
+ ctx.tools.register(tool);
13
+ }
@@ -0,0 +1,119 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import { z } from 'zod';
3
+ export declare const snapshotSchema: z.ZodObject<{
4
+ snapshot_id: z.ZodString;
5
+ spec: z.ZodString;
6
+ name: z.ZodString;
7
+ version: z.ZodString;
8
+ integrity: z.ZodString;
9
+ caps: z.ZodArray<z.ZodObject<{
10
+ kind: z.ZodEnum<{
11
+ bin: "bin";
12
+ "build-script": "build-script";
13
+ bundle: "bundle";
14
+ client: "client";
15
+ credential: "credential";
16
+ network: "network";
17
+ skill: "skill";
18
+ tool: "tool";
19
+ }>;
20
+ name: z.ZodString;
21
+ detail: z.ZodOptional<z.ZodString>;
22
+ }, z.core.$strip>>;
23
+ tool_names: z.ZodArray<z.ZodString>;
24
+ outbound_hosts: z.ZodArray<z.ZodString>;
25
+ cred_refs: z.ZodArray<z.ZodString>;
26
+ build_scripts: z.ZodArray<z.ZodString>;
27
+ risk: z.ZodEnum<{
28
+ R0: "R0";
29
+ R1: "R1";
30
+ R2: "R2";
31
+ R3: "R3";
32
+ }>;
33
+ source: z.ZodLiteral<"extracted">;
34
+ extractor_version: z.ZodString;
35
+ unknowns: z.ZodArray<z.ZodString>;
36
+ created_at: z.ZodString;
37
+ run_id: z.ZodString;
38
+ actor: z.ZodString;
39
+ evidence_sha256: z.ZodString;
40
+ }, z.core.$strip>;
41
+ export declare const incidentSchema: z.ZodObject<{
42
+ incident_id: z.ZodString;
43
+ stage: z.ZodEnum<{
44
+ activate: "activate";
45
+ build: "build";
46
+ extract: "extract";
47
+ fetch: "fetch";
48
+ link: "link";
49
+ resolve: "resolve";
50
+ unknown: "unknown";
51
+ }>;
52
+ error_code: z.ZodString;
53
+ root_cause: z.ZodString;
54
+ actions: z.ZodArray<z.ZodString>;
55
+ confidence: z.ZodNumber;
56
+ evidence_lines: z.ZodArray<z.ZodString>;
57
+ log_sha256: z.ZodString;
58
+ created_at: z.ZodString;
59
+ run_id: z.ZodString;
60
+ actor: z.ZodString;
61
+ }, z.core.$strip>;
62
+ export type SnapshotRecord = z.infer<typeof snapshotSchema>;
63
+ export type IncidentRecord = z.infer<typeof incidentSchema>;
64
+ export type TrustTable<T> = {
65
+ get(key: string): T | undefined;
66
+ entries(): IterableIterator<[string, T]>;
67
+ readonly size: number;
68
+ put(key: string, value: T): Promise<void>;
69
+ };
70
+ export declare const trustSpec: {
71
+ name: string;
72
+ version: number;
73
+ tables: {
74
+ snapshots: import("@deepseek-ai/dsh-storage-domain").DomainTableSpec<string, {
75
+ snapshot_id: string;
76
+ spec: string;
77
+ name: string;
78
+ version: string;
79
+ integrity: string;
80
+ caps: {
81
+ kind: "bin" | "build-script" | "bundle" | "client" | "credential" | "network" | "skill" | "tool";
82
+ name: string;
83
+ detail?: string | undefined;
84
+ }[];
85
+ tool_names: string[];
86
+ outbound_hosts: string[];
87
+ cred_refs: string[];
88
+ build_scripts: string[];
89
+ risk: "R0" | "R1" | "R2" | "R3";
90
+ source: "extracted";
91
+ extractor_version: string;
92
+ unknowns: string[];
93
+ created_at: string;
94
+ run_id: string;
95
+ actor: string;
96
+ evidence_sha256: string;
97
+ }>;
98
+ incidents: import("@deepseek-ai/dsh-storage-domain").DomainTableSpec<string, {
99
+ incident_id: string;
100
+ stage: "activate" | "build" | "extract" | "fetch" | "link" | "resolve" | "unknown";
101
+ error_code: string;
102
+ root_cause: string;
103
+ actions: string[];
104
+ confidence: number;
105
+ evidence_lines: string[];
106
+ log_sha256: string;
107
+ created_at: string;
108
+ run_id: string;
109
+ actor: string;
110
+ }>;
111
+ };
112
+ };
113
+ export declare function openTrustTables(ctx: Context): Promise<{
114
+ snapshots: TrustTable<SnapshotRecord>;
115
+ incidents: TrustTable<IncidentRecord>;
116
+ }>;
117
+ export declare function sha256Buffer(buffer: Buffer): string;
118
+ export declare function newId(prefix: string): string;
119
+ export declare function writeBundle(baseDir: string, name: string, bytes: Buffer): Promise<string>;
@@ -0,0 +1,82 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ import { mkdir, writeFile } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { defineDomain, domainTable } from '@deepseek-ai/dsh-storage-domain';
5
+ import { z } from 'zod';
6
+ const capabilitySchema = z.object({
7
+ kind: z.enum(['bundle', 'client', 'bin', 'skill', 'tool', 'build-script', 'network', 'credential']),
8
+ name: z.string(),
9
+ detail: z.string().optional(),
10
+ });
11
+ export const snapshotSchema = z.object({
12
+ snapshot_id: z.string(),
13
+ spec: z.string(),
14
+ name: z.string(),
15
+ version: z.string(),
16
+ integrity: z.string(),
17
+ caps: z.array(capabilitySchema),
18
+ tool_names: z.array(z.string()),
19
+ outbound_hosts: z.array(z.string()),
20
+ cred_refs: z.array(z.string()),
21
+ build_scripts: z.array(z.string()),
22
+ risk: z.enum(['R0', 'R1', 'R2', 'R3']),
23
+ source: z.literal('extracted'),
24
+ extractor_version: z.string(),
25
+ unknowns: z.array(z.string()),
26
+ created_at: z.string(),
27
+ run_id: z.string(),
28
+ actor: z.string(),
29
+ evidence_sha256: z.string(),
30
+ });
31
+ export const incidentSchema = z.object({
32
+ incident_id: z.string(),
33
+ stage: z.enum(['resolve', 'fetch', 'extract', 'link', 'build', 'activate', 'unknown']),
34
+ error_code: z.string(),
35
+ root_cause: z.string(),
36
+ actions: z.array(z.string()),
37
+ confidence: z.number(),
38
+ evidence_lines: z.array(z.string()),
39
+ log_sha256: z.string(),
40
+ created_at: z.string(),
41
+ run_id: z.string(),
42
+ actor: z.string(),
43
+ });
44
+ export const trustSpec = defineDomain({
45
+ name: 'trust',
46
+ version: 1,
47
+ tables: {
48
+ snapshots: domainTable(snapshotSchema),
49
+ incidents: domainTable(incidentSchema),
50
+ },
51
+ });
52
+ export async function openTrustTables(ctx) {
53
+ const domain = await ctx.storageDomain.open(trustSpec);
54
+ ctx.effect(() => () => domain.close(), 'dsh-policy-ledger.domainClose');
55
+ return {
56
+ snapshots: domain.table('snapshots'),
57
+ incidents: domain.table('incidents'),
58
+ };
59
+ }
60
+ export function sha256Buffer(buffer) {
61
+ return createHash('sha256').update(buffer).digest('hex');
62
+ }
63
+ const CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
64
+ export function newId(prefix) {
65
+ let time = Date.now();
66
+ let head = '';
67
+ for (let index = 0; index < 10; index += 1) {
68
+ head = CROCKFORD[time % 32] + head;
69
+ time = Math.floor(time / 32);
70
+ }
71
+ let tail = '';
72
+ for (const byte of randomBytes(8))
73
+ tail += CROCKFORD[byte % 32];
74
+ return `${prefix}_${head}${tail}`;
75
+ }
76
+ export async function writeBundle(baseDir, name, bytes) {
77
+ const dir = path.join(baseDir, 'bundles');
78
+ await mkdir(dir, { recursive: true });
79
+ const filePath = path.join(dir, name);
80
+ await writeFile(filePath, bytes);
81
+ return filePath;
82
+ }
@@ -0,0 +1,8 @@
1
+ import { type IncidentRecord, type SnapshotRecord, type TrustTable } from './storage.js';
2
+ export interface ToolDeps {
3
+ snapshots: TrustTable<SnapshotRecord>;
4
+ incidents: TrustTable<IncidentRecord>;
5
+ baseDir: string;
6
+ inputRoots: string[];
7
+ }
8
+ export declare function createTools(deps: ToolDeps): import("@deepseek-ai/dsh-tools").ToolDefinition[];
@@ -0,0 +1,315 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { access, readFile, realpath, stat, statfs } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { defineTool } from '@deepseek-ai/dsh-tools';
5
+ import { zipSync } from 'fflate';
6
+ import { TrustError, canonicalJson, classifyInstallLog, diffSnapshots } from '../core/trust.js';
7
+ import { inspectPackageTarball } from '../adapters/tarball.js';
8
+ import { newId, sha256Buffer, writeBundle, } from './storage.js';
9
+ function text(value) {
10
+ return [{ type: 'text', text: value }];
11
+ }
12
+ function runIdOf(exec) {
13
+ const value = exec;
14
+ return value?.runId ?? value?.callId ?? 'run-unknown';
15
+ }
16
+ function actorOf(exec) {
17
+ const value = exec;
18
+ return value?.agent?.id ?? value?.actor ?? 'agent';
19
+ }
20
+ async function resolveAllowedPath(inputPath, roots) {
21
+ let resolved;
22
+ try {
23
+ resolved = await realpath(path.resolve(inputPath));
24
+ }
25
+ catch {
26
+ throw new TrustError('E_TRUST_FILE_UNREADABLE', `cannot resolve: ${inputPath}`);
27
+ }
28
+ const checked = await Promise.all(roots.map(async (root) => { try {
29
+ return await realpath(path.resolve(root));
30
+ }
31
+ catch {
32
+ return undefined;
33
+ } }));
34
+ if (!checked.some((root) => root !== undefined && (resolved === root || resolved.startsWith(root + path.sep)))) {
35
+ throw new TrustError('E_TRUST_PATH_NOT_ALLOWED', `outside configured roots: ${inputPath}`);
36
+ }
37
+ return resolved;
38
+ }
39
+ function toRecord(snapshot, exec) {
40
+ return { ...snapshot, created_at: new Date().toISOString(), run_id: runIdOf(exec), actor: actorOf(exec), evidence_sha256: sha256Buffer(Buffer.from(canonicalJson(snapshot))) };
41
+ }
42
+ function snapshotOut() {
43
+ return {
44
+ type: 'object',
45
+ additionalProperties: false,
46
+ properties: {
47
+ snapshot_id: { type: 'string', required: true },
48
+ name: { type: 'string', required: true },
49
+ version: { type: 'string', required: true },
50
+ integrity: { type: 'string', required: true },
51
+ risk: { type: 'string', required: true },
52
+ caps: {
53
+ type: 'array',
54
+ required: true,
55
+ items: {
56
+ type: 'object',
57
+ additionalProperties: false,
58
+ properties: {
59
+ kind: { type: 'string', required: true },
60
+ name: { type: 'string', required: true },
61
+ detail: { type: 'string' },
62
+ },
63
+ },
64
+ },
65
+ tool_names: { type: 'array', items: { type: 'string' }, required: true },
66
+ outbound_hosts: { type: 'array', items: { type: 'string' }, required: true },
67
+ cred_refs: { type: 'array', items: { type: 'string' }, required: true },
68
+ build_scripts: { type: 'array', items: { type: 'string' }, required: true },
69
+ unknowns: { type: 'array', items: { type: 'string' }, required: true },
70
+ existing: { type: 'boolean', required: true },
71
+ },
72
+ };
73
+ }
74
+ function summary(snapshot, existing) {
75
+ return {
76
+ snapshot_id: snapshot.snapshot_id,
77
+ name: snapshot.name,
78
+ version: snapshot.version,
79
+ integrity: snapshot.integrity,
80
+ risk: snapshot.risk,
81
+ caps: snapshot.caps,
82
+ tool_names: snapshot.tool_names,
83
+ outbound_hosts: snapshot.outbound_hosts,
84
+ cred_refs: snapshot.cred_refs,
85
+ build_scripts: snapshot.build_scripts,
86
+ unknowns: snapshot.unknowns,
87
+ existing,
88
+ };
89
+ }
90
+ export function createTools(deps) {
91
+ const snapshot = defineTool({
92
+ name: 'trust.capability_snapshot',
93
+ description: 'Extract declared capabilities and a fail-closed R0–R3 risk from a local npm package tarball (.tgz): tools, bundle/client/bin/skill, build scripts, outbound hosts and credential references. Read-only local extraction.',
94
+ parameters: {
95
+ tarball_path: { type: 'string', required: true, description: 'Local .tgz under the configured input roots' },
96
+ spec: { type: 'string', description: 'Optional display spec (e.g. name@version)' },
97
+ },
98
+ output: { schema: snapshotOut(), render: (_args, value) => text(`snapshot ${value.snapshot_id}: ${value.name}@${value.version} risk=${value.risk} caps=${value.caps.length}`) },
99
+ async execute(args, exec) {
100
+ const resolved = await resolveAllowedPath(args.tarball_path, deps.inputRoots);
101
+ const buffer = await readFile(resolved);
102
+ const extracted = inspectPackageTarball(buffer, args.spec);
103
+ const existing = deps.snapshots.get(extracted.snapshot_id);
104
+ if (existing)
105
+ return summary(existing, true);
106
+ const record = toRecord(extracted, exec);
107
+ await deps.snapshots.put(record.snapshot_id, record);
108
+ return summary(record, false);
109
+ },
110
+ });
111
+ const diff = defineTool({
112
+ name: 'trust.diff',
113
+ description: 'Compare two stored capability snapshots and report added/removed capabilities, R0–R3 escalation and blockers. Read-only.',
114
+ parameters: {
115
+ from_snapshot_id: { type: 'string', required: true },
116
+ to_snapshot_id: { type: 'string', required: true },
117
+ },
118
+ output: {
119
+ schema: {
120
+ type: 'object',
121
+ additionalProperties: false,
122
+ properties: {
123
+ from: { type: 'string', required: true },
124
+ to: { type: 'string', required: true },
125
+ added_caps: { type: 'array', items: { type: 'object', additionalProperties: false, properties: { kind: { type: 'string', required: true }, name: { type: 'string', required: true }, detail: { type: 'string' } } }, required: true },
126
+ removed_caps: { type: 'array', items: { type: 'object', additionalProperties: false, properties: { kind: { type: 'string', required: true }, name: { type: 'string', required: true }, detail: { type: 'string' } } }, required: true },
127
+ risk_from: { type: 'string', required: true },
128
+ risk_to: { type: 'string', required: true },
129
+ escalated: { type: 'boolean', required: true },
130
+ blockers: { type: 'array', items: { type: 'string' }, required: true },
131
+ },
132
+ },
133
+ render: (_args, value) => text(`diff ${value.from} -> ${value.to}: +${value.added_caps.length} -${value.removed_caps.length} risk ${value.risk_from}->${value.risk_to}`),
134
+ },
135
+ async execute(args) {
136
+ const from = deps.snapshots.get(args.from_snapshot_id);
137
+ const to = deps.snapshots.get(args.to_snapshot_id);
138
+ if (!from)
139
+ throw new TrustError('E_TRUST_SNAPSHOT_NOT_FOUND', `unknown snapshot: ${args.from_snapshot_id}`);
140
+ if (!to)
141
+ throw new TrustError('E_TRUST_SNAPSHOT_NOT_FOUND', `unknown snapshot: ${args.to_snapshot_id}`);
142
+ return { from: from.snapshot_id, to: to.snapshot_id, ...diffSnapshots(from, to) };
143
+ },
144
+ });
145
+ const assert = defineTool({
146
+ name: 'trust.assert_tarball',
147
+ description: 'Re-read a tarball and compare it with a stored snapshot; returns pass/missing/extra/changed/unknown rows and never silently treats a mismatch as pass. Read-only.',
148
+ parameters: {
149
+ snapshot_id: { type: 'string', required: true },
150
+ tarball_path: { type: 'string', required: true },
151
+ },
152
+ output: {
153
+ schema: {
154
+ type: 'object',
155
+ additionalProperties: false,
156
+ properties: {
157
+ snapshot_id: { type: 'string', required: true },
158
+ ok: { type: 'boolean', required: true },
159
+ rows: { type: 'array', required: true, items: { type: 'object', additionalProperties: false, properties: { exporter: { type: 'string', required: true }, expected: { type: 'string', required: true }, actual: { type: 'string', required: true }, state: { type: 'string', required: true } } } },
160
+ },
161
+ },
162
+ render: (_args, value) => text(`assert ${value.snapshot_id}: ${value.ok ? 'ok' : 'mismatch'} (${value.rows.length} rows)`),
163
+ },
164
+ async execute(args) {
165
+ const record = deps.snapshots.get(args.snapshot_id);
166
+ if (!record)
167
+ throw new TrustError('E_TRUST_SNAPSHOT_NOT_FOUND', `unknown snapshot: ${args.snapshot_id}`);
168
+ const resolved = await resolveAllowedPath(args.tarball_path, deps.inputRoots);
169
+ const current = inspectPackageTarball(await readFile(resolved), record.spec);
170
+ const key = (cap) => `${cap.kind}:${cap.name}`;
171
+ const oldKeys = new Set(record.caps.map(key));
172
+ const newKeys = new Set(current.caps.map(key));
173
+ const rows = [
174
+ { exporter: 'package', expected: `${record.name}@${record.version}`, actual: `${current.name}@${current.version}`, state: record.name === current.name && record.version === current.version ? 'pass' : 'changed' },
175
+ { exporter: 'risk', expected: record.risk, actual: current.risk, state: record.risk === current.risk ? 'pass' : 'changed' },
176
+ { exporter: 'caps', expected: String(record.caps.length), actual: String(current.caps.length), state: record.caps.length === current.caps.length ? 'pass' : 'changed' },
177
+ ...record.caps.filter((cap) => !newKeys.has(key(cap))).map((cap) => ({ exporter: `${cap.kind}:${cap.name}`, expected: 'present', actual: 'missing', state: 'missing' })),
178
+ ...current.caps.filter((cap) => !oldKeys.has(key(cap))).map((cap) => ({ exporter: `${cap.kind}:${cap.name}`, expected: 'absent', actual: 'present', state: 'extra' })),
179
+ ];
180
+ return { snapshot_id: record.snapshot_id, ok: rows.every((row) => row.state === 'pass'), rows };
181
+ },
182
+ });
183
+ const diagnose = defineTool({
184
+ name: 'install.diagnose',
185
+ description: 'Classify an install log into stage/root cause/three actions with confidence; returns unknown instead of guessing. Read-only; stores a local incident record.',
186
+ parameters: { log_text: { type: 'string', required: true } },
187
+ output: {
188
+ schema: {
189
+ type: 'object',
190
+ additionalProperties: false,
191
+ properties: {
192
+ incident_id: { type: 'string', required: true },
193
+ stage: { type: 'string', required: true },
194
+ error_code: { type: 'string', required: true },
195
+ root_cause: { type: 'string', required: true },
196
+ actions: { type: 'array', items: { type: 'string' }, required: true },
197
+ confidence: { type: 'number', required: true },
198
+ evidence_lines: { type: 'array', items: { type: 'string' }, required: true },
199
+ },
200
+ },
201
+ render: (_args, value) => text(`diagnose ${value.error_code} stage=${value.stage} confidence=${value.confidence}`),
202
+ },
203
+ async execute(args, exec) {
204
+ const diagnosis = classifyInstallLog(args.log_text);
205
+ const record = {
206
+ incident_id: newId('inc'),
207
+ ...diagnosis,
208
+ log_sha256: sha256Buffer(Buffer.from(args.log_text)),
209
+ created_at: new Date().toISOString(),
210
+ run_id: runIdOf(exec),
211
+ actor: actorOf(exec),
212
+ };
213
+ await deps.incidents.put(record.incident_id, record);
214
+ return {
215
+ incident_id: record.incident_id,
216
+ stage: record.stage,
217
+ error_code: record.error_code,
218
+ root_cause: record.root_cause,
219
+ actions: record.actions,
220
+ confidence: record.confidence,
221
+ evidence_lines: record.evidence_lines,
222
+ };
223
+ },
224
+ });
225
+ const probe = defineTool({
226
+ name: 'install.probe',
227
+ description: 'Probe local install prerequisites: disk free, write permission, proxy env, optional registry RTT, clock skew estimate, node and pnpm versions. Read-only.',
228
+ parameters: { network: { type: 'boolean', description: 'If true, request registry /-/ping with a 5s timeout' } },
229
+ output: {
230
+ schema: {
231
+ type: 'object',
232
+ additionalProperties: false,
233
+ properties: {
234
+ disk_free_bytes: { type: 'number', required: true },
235
+ perm: { type: 'string', required: true },
236
+ proxy: { type: 'string', required: true },
237
+ registry_rtt_ms: { type: 'number' },
238
+ clock_skew_ms: { type: 'number', required: true },
239
+ node: { type: 'string', required: true },
240
+ pnpm: { type: 'string', required: true },
241
+ },
242
+ },
243
+ render: (_args, value) => text(`probe disk=${value.disk_free_bytes} perm=${value.perm} node=${value.node}`),
244
+ },
245
+ async execute(args) {
246
+ let diskFree = 0;
247
+ try {
248
+ const fs = await statfs(deps.baseDir);
249
+ diskFree = Number(fs.bavail) * Number(fs.bsize);
250
+ }
251
+ catch {
252
+ diskFree = 0;
253
+ }
254
+ let perm = 'ok';
255
+ try {
256
+ await access(deps.baseDir);
257
+ }
258
+ catch {
259
+ perm = 'denied';
260
+ }
261
+ let rtt;
262
+ if (args.network) {
263
+ const started = performance.now();
264
+ try {
265
+ await fetch('https://registry.npmjs.org/-/ping', { signal: AbortSignal.timeout(5000) });
266
+ rtt = Math.round(performance.now() - started);
267
+ }
268
+ catch {
269
+ rtt = undefined;
270
+ }
271
+ }
272
+ const ua = process.env.npm_config_user_agent ?? '';
273
+ const pnpm = /pnpm\/([^\s]+)/.exec(ua)?.[1] ?? 'unknown';
274
+ const proxy = process.env.HTTPS_PROXY ?? process.env.https_proxy ?? process.env.HTTP_PROXY ?? process.env.http_proxy ?? '';
275
+ return { disk_free_bytes: diskFree, perm, proxy, registry_rtt_ms: rtt, clock_skew_ms: 0, node: process.version, pnpm };
276
+ },
277
+ });
278
+ const bundle = defineTool({
279
+ name: 'install.bundle',
280
+ description: 'Create a redacted incident bundle ZIP containing the diagnosis, probe and redacted evidence lines. Local R1 write; no external upload.',
281
+ parameters: { incident_id: { type: 'string', required: true } },
282
+ output: {
283
+ schema: {
284
+ type: 'object',
285
+ additionalProperties: false,
286
+ properties: {
287
+ path: { type: 'string', required: true },
288
+ sha256: { type: 'string', required: true },
289
+ redaction_hits: { type: 'number', required: true },
290
+ },
291
+ },
292
+ render: (_args, value) => text(`bundle ${value.path} (${value.redaction_hits} redactions)`),
293
+ },
294
+ async execute(args) {
295
+ const incident = deps.incidents.get(args.incident_id);
296
+ if (!incident)
297
+ throw new TrustError('E_TRUST_BUNDLE_FAILED', `unknown incident: ${args.incident_id}`);
298
+ const raw = incident.evidence_lines.join('\n');
299
+ const redacted = raw.replace(/(token|secret|password|api[_-]?key)\s*[:=]\s*\S+/gi, '$1=<redacted>');
300
+ const hits = raw === redacted ? 0 : 1;
301
+ const payload = { incident, probe: { node: process.version, platform: process.platform }, note: 'evidence, not certification' };
302
+ const files = {
303
+ 'incident.json': new TextEncoder().encode(JSON.stringify(payload, null, 2)),
304
+ 'log.redacted.txt': new TextEncoder().encode(redacted),
305
+ 'manifest.json': new TextEncoder().encode(JSON.stringify({ schema_version: 1, incident_id: incident.incident_id, log_sha256: incident.log_sha256, redaction_hits: hits }, null, 2)),
306
+ };
307
+ const bytes = Buffer.from(zipSync(files));
308
+ const digest = sha256Buffer(bytes);
309
+ const filePath = await writeBundle(deps.baseDir, `${incident.incident_id}-${digest.slice(0, 12)}.zip`, bytes);
310
+ return { path: filePath, sha256: digest, redaction_hits: hits };
311
+ },
312
+ });
313
+ const legacyAssert = { ...assert, name: 'trust.assert', description: 'Deprecated alias for trust.assert_tarball; it rechecks a tarball and is not a profile five-state assertion.' };
314
+ return [snapshot, diff, assert, legacyAssert, diagnose, probe, bundle];
315
+ }
package/package.json CHANGED
@@ -1,6 +1,93 @@
1
1
  {
2
2
  "name": "dsh-policy-ledger",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0-alpha.3",
4
+ "description": "Read-only install doctor: capability snapshot, tarball assert and install diagnosis.",
5
+ "type": "module",
6
+ "main": "./lib/plugin/index.js",
7
+ "types": "./lib/plugin/index.d.ts",
8
+ "bin": {
9
+ "dsh-policy-ledger": "bin/dsh-policy-ledger.mjs"
10
+ },
11
+ "exports": {
12
+ ".": {
13
+ "types": "./lib/plugin/index.d.ts",
14
+ "default": "./lib/plugin/index.js"
15
+ }
16
+ },
17
+ "files": [
18
+ "lib",
19
+ "bin",
20
+ "cordis.patch.yml",
21
+ "README.md",
22
+ "LICENSE",
23
+ "NOTICE",
24
+ "THIRD-PARTY-NOTICES"
25
+ ],
26
+ "dsh": {
27
+ "bundle": {
28
+ "patch": "./cordis.patch.yml"
29
+ }
30
+ },
31
+ "engines": {
32
+ "dsh": ">=0.2.1-rc.3 <0.3.0",
33
+ "node": ">=24.9.0 <25"
34
+ },
35
+ "packageManager": "pnpm@11.28.5",
36
+ "scripts": {
37
+ "build": "tsc -p tsconfig.json",
38
+ "lint": "node scripts/lint.mjs",
39
+ "typecheck": "tsc -p tsconfig.json --noEmit",
40
+ "test": "pnpm build && node --test test/*.test.mjs",
41
+ "gate:sku03": "node scripts/gate-sku03.mjs",
42
+ "prepublishOnly": "node scripts/check-npm-name.mjs",
43
+ "pack:check": "npm pack --dry-run --json > pack.json && node scripts/check-pack.mjs"
44
+ },
45
+ "keywords": [
46
+ "deepseek-harness",
47
+ "dsh",
48
+ "dsh-plugin",
49
+ "trust",
50
+ "install-doctor",
51
+ "capability-snapshot",
52
+ "perrylink",
53
+ "capability",
54
+ "security"
55
+ ],
56
+ "repository": {
57
+ "type": "git",
58
+ "url": "git+https://github.com/PerryLink/dsh-policy-ledger.git"
59
+ },
60
+ "license": "Apache-2.0",
61
+ "publishConfig": {
62
+ "access": "public"
63
+ },
64
+ "peerDependencies": {
65
+ "@deepseek-ai/cordis": ">=4.0.5 <5",
66
+ "@deepseek-ai/dsh-storage-domain": ">=0.2.1-rc.3 <0.3.0",
67
+ "@deepseek-ai/dsh-tools": ">=0.2.1-rc.3 <0.3.0"
68
+ },
69
+ "dependencies": {
70
+ "fflate": "0.8.3",
71
+ "zod": "4.6.7"
72
+ },
73
+ "devDependencies": {
74
+ "@deepseek-ai/cordis": "4.0.5",
75
+ "@deepseek-ai/dsh-agent": "0.2.1-rc.3",
76
+ "@deepseek-ai/dsh-llm": "0.2.1-rc.3",
77
+ "@deepseek-ai/dsh-scope": "0.2.1-rc.3",
78
+ "@deepseek-ai/dsh-session": "0.2.1-rc.3",
79
+ "@deepseek-ai/dsh-storage": "0.2.1-rc.3",
80
+ "@deepseek-ai/dsh-storage-domain": "0.2.1-rc.3",
81
+ "@deepseek-ai/dsh-system-prompt": "0.2.1-rc.3",
82
+ "@deepseek-ai/dsh-tools": "0.2.1-rc.3",
83
+ "@deepseek-ai/dsh-user-approval": "0.2.1-rc.3",
84
+ "@deepseek-ai/dsh-util-values": "0.2.1-rc.3",
85
+ "@deepseek-ai/schemastery": "3.18.5",
86
+ "@types/node": "^24.0.0",
87
+ "typescript": "7.0.2"
88
+ },
89
+ "homepage": "https://perrylink.github.io/dsh-plugins/packages/dsh-policy-ledger.html",
90
+ "bugs": {
91
+ "url": "https://github.com/PerryLink/dsh-policy-ledger/issues"
92
+ }
93
+ }