@dsh-cc/session-forensics 0.7.1-rc.1

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,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,6 @@
1
+ # Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
2
+ # side as of the last confirmed-consistent state. Both languages carry equal authority;
3
+ # after editing either side, bring the other along and re-record with:
4
+ # pnpm check:readme --write
5
+ README.md: fd31e59dc49c6287ec58a96f1bc92d104181bc06
6
+ README.zh.md: b923647682c2c03e6bfc59e90762ee1dc58992ca
package/README.md ADDED
@@ -0,0 +1,26 @@
1
+ # @dsh-cc/session-forensics
2
+
3
+ English | [中文](README.zh.md)
4
+
5
+ Pure analysis library behind the `/learn` feature: it walks the durable session JSONL store and distills recurring failure→success corrections. It has no cordis dependency and no runtime dependencies at all — hosts inject a `decompress(file): Promise<string>` seam (a default `decompressJsonl` shells out to the `zstd` binary, mirroring the audit-scripts precedent) so unit tests run on plain fixture text.
6
+
7
+ ## What it does
8
+
9
+ - **Scanner** (`scan.ts`): walks `<DSH_HOME>/sessions/<projectKey>/<sessionId>/session.jsonl.zstd`, reads the session header (`origin`, `delegationDepth`, `parentSession`), and normalizes `tool/call` + `tool/result` events into records. `tool/call` arguments arrive as a JSON-encoded string and are parsed with tolerance for parse failures. Truncated live-tail lines are ignored; corrupt middle lines are skipped and counted — never thrown. A `days` recency filter uses directory mtime first and falls back to the header timestamp only when mtime is missing or unreasonable; a session inside the window is decompressed exactly once.
10
+ - **Approval pairing**: `approval/asked` events are paired with `approval/decided` by `data.id`; `approval/policy` events (e.g. `policy: "never"`) mark sessions excluded from denial analysis.
11
+ - **Analyzers** (`analyze/`), all deterministic — no LLM in v1:
12
+ 1. `path-correlation` — same-tool failures (path-shaped error gate: ENOENT / "No such file" / "not found") correlated with the first later success in line order sharing a basename in a different directory; bash pairs require the same first token plus ≥1 differing path-ish token.
13
+ 2. `env-facts` — same first-token commands failing vs succeeding with distinct error signatures (e.g. `python3` ModuleNotFoundError vs `uv run python` success).
14
+ 3. `search-scope` — failed narrow-root greps followed by successful broader-root greps on similar patterns.
15
+ 4. `permission-denials` — `rejected` approval outcomes only (`cancelled` and `unavailable` are not denials); `approval/policy: never` sessions excluded from the denominator.
16
+ 5. `large-files` — read results above a size threshold → "always use offset/limit".
17
+ - **Aggregation** (`runForensics`): findings merge by `(kind, title)`, rank by occurrence count, and pass a `minOccurrences` gate (default 2). Every finding carries `session:<id>#turn=<n>` evidence anchors.
18
+
19
+ ## Composition
20
+
21
+ This is a library, not a plugin — import it. The consumer that mounts it as a user-facing command is [`@dsh-cc/command-learn`](../command-learn/README.md).
22
+
23
+ ## Known Limitations and Deferred Work
24
+
25
+ - Deterministic analyzers only — an optional LLM summarization pass over the findings is deliberately out of v1.
26
+ - The bash path-ish token rule is intentionally simple (`/`-containing or file-extension-shaped tokens); `minOccurrences` is the actual precision mechanism. Upgrading the rule is future work.
package/README.zh.md ADDED
@@ -0,0 +1,26 @@
1
+ # @dsh-cc/session-forensics
2
+
3
+ [English](README.md) | 中文
4
+
5
+ `/learn` 特性背后的纯分析库:遍历持久化会话 JSONL 存储,蒸馏反复出现的 失败→成功 修正。它不依赖 cordis,也没有任何运行时依赖 —— 宿主注入 `decompress(file): Promise<string>` 缝(默认的 `decompressJsonl` 通过子进程调用 `zstd` 二进制,沿用审计脚本的先例),因此单元测试可以直接跑普通 fixture 文本。
6
+
7
+ ## 它做什么
8
+
9
+ - **扫描器**(`scan.ts`):遍历 `<DSH_HOME>/sessions/<projectKey>/<sessionId>/session.jsonl.zstd`,读取会话头(`origin`、`delegationDepth`、`parentSession`),并将 `tool/call` + `tool/result` 事件归一化为记录。`tool/call` 的 arguments 以 JSON 编码字符串到达,解析时容忍解析失败。截断的实时尾行被忽略;损坏的中间行被跳过并计数 —— 绝不抛异常。`days` 新近度过滤优先使用目录 mtime,仅在 mtime 缺失或不合理时回退到头时间戳;窗口内的会话只解压一次。
10
+ - **审批配对**:`approval/asked` 事件按 `data.id` 与 `approval/decided` 配对;`approval/policy` 事件(如 `policy: "never"`)标记被排除在拒绝分析之外的会话。
11
+ - **分析器**(`analyze/`),全部确定性 —— v1 无 LLM:
12
+ 1. `path-correlation` —— 同工具失败(路径形态错误门:ENOENT / "No such file" / "not found")与行序上首个后继成功共享同名文件但目录不同进行相关;bash 对要求相同首 token 且 ≥1 个不同的路径形态 token。
13
+ 2. `env-facts` —— 相同首 token 的命令失败与成功且错误签名不同(如 `python3` 下 ModuleNotFoundError,`uv run python` 下成功)。
14
+ 3. `search-scope` —— 窄根 grep 失败后紧跟相似 pattern 的更宽根 grep 成功。
15
+ 4. `permission-denials` —— 只计 `rejected` 审批结果(`cancelled` 与 `unavailable` 不算拒绝);`approval/policy: never` 的会话排除在分母之外。
16
+ 5. `large-files` —— 超过大小阈值的读取结果 → "对 X 始终使用 offset/limit"。
17
+ - **聚合**(`runForensics`):findings 按 `(kind, title)` 合并,按出现次数排序,并过 `minOccurrences` 门(默认 2)。每个 finding 携带 `session:<id>#turn=<n>` 证据锚点。
18
+
19
+ ## 组合
20
+
21
+ 这是一个库而非插件 —— 直接 import。把它挂载为用户可见命令的消费者是 [`@dsh-cc/command-learn`](../command-learn/README.md)。
22
+
23
+ ## 已知限制与暂缓事项
24
+
25
+ - 仅确定性分析器 —— 对 findings 的可选 LLM 摘要 pass 刻意排除在 v1 之外。
26
+ - bash 路径形态 token 规则刻意保持简单(含 `/` 或文件扩展名形态的 token);`minOccurrences` 才是真正的精度机制。升级该规则是后续工作。
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Analyzer 2 — environment facts. Same first-token command failing, then a
3
+ * different invocation with that first token succeeding: record the working
4
+ * incantation. Error signatures are normalized result text, not prose parsing.
5
+ */
6
+ import type { Finding, ToolRecord } from "../types.ts";
7
+ export declare function findEnvFacts(records: ToolRecord[]): Finding[];
8
+ //# sourceMappingURL=env-facts.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"env-facts.d.ts","sourceRoot":"","sources":["../../src/analyze/env-facts.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,KAAK,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAoBvD,wBAAgB,YAAY,CAAC,OAAO,EAAE,UAAU,EAAE,GAAG,OAAO,EAAE,CA+B7D"}
@@ -0,0 +1,52 @@
1
+ import { anchor } from "../types.js";
2
+ function firstToken(record) {
3
+ const command = record.args?.command;
4
+ if (typeof command !== "string")
5
+ return undefined;
6
+ const token = command.split(/\s+/).find(Boolean);
7
+ return token;
8
+ }
9
+ function errorSignature(text) {
10
+ const line = text
11
+ .split("\n")
12
+ .map((l) => l.trim())
13
+ .find((l) => l.length > 0);
14
+ // ponytail: naive signature — first non-empty error line. Good enough to
15
+ // distinguish ModuleNotFoundError from exit codes; upgrade if noisy.
16
+ return (line ?? text.slice(0, 120)).slice(0, 160);
17
+ }
18
+ export function findEnvFacts(records) {
19
+ const findings = [];
20
+ const bash = records.filter((r) => r.name.toLowerCase() === "bash" && typeof r.args?.command === "string");
21
+ for (let i = 0; i < bash.length; i++) {
22
+ const failure = bash[i];
23
+ if (!failure.isError || failure.resultText === "")
24
+ continue;
25
+ const first = firstToken(failure);
26
+ if (first === undefined)
27
+ continue;
28
+ const failureSig = errorSignature(failure.resultText);
29
+ for (let j = i + 1; j < bash.length; j++) {
30
+ const success = bash[j];
31
+ if (success.isError || firstToken(success) !== first)
32
+ continue;
33
+ const successSig = errorSignature(success.resultText);
34
+ if (successSig === failureSig)
35
+ continue; // no distinct signature: nothing learned
36
+ const failedCmd = failure.args
37
+ .command;
38
+ const goodCmd = success.args
39
+ .command;
40
+ findings.push({
41
+ kind: "env-fact",
42
+ title: `use \`${goodCmd}\` instead of plain \`${first}\``,
43
+ detail: `\`${failedCmd}\` failed with "${failureSig}"; \`${goodCmd}\` succeeded.`,
44
+ occurrences: 1,
45
+ evidence: [anchor(failure.sessionId, failure.turn)],
46
+ });
47
+ break;
48
+ }
49
+ }
50
+ return findings;
51
+ }
52
+ //# sourceMappingURL=env-facts.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"env-facts.js","sourceRoot":"","sources":["../../src/analyze/env-facts.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAErC,SAAS,UAAU,CAAC,MAAkB;IACpC,MAAM,OAAO,GAAI,MAAM,CAAC,IAAgC,EAAE,OAAO,CAAC;IAClE,IAAI,OAAO,OAAO,KAAK,QAAQ;QAAE,OAAO,SAAS,CAAC;IAClD,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACjD,OAAO,KAAK,CAAC;AACf,CAAC;AAED,SAAS,cAAc,CAAC,IAAY;IAClC,MAAM,IAAI,GAAG,IAAI;SACd,KAAK,CAAC,IAAI,CAAC;SACX,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;SACpB,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IAC7B,yEAAyE;IACzE,qEAAqE;IACrE,OAAO,CAAC,IAAI,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;AACpD,CAAC;AAED,MAAM,UAAU,YAAY,CAAC,OAAqB;IAChD,MAAM,QAAQ,GAAc,EAAE,CAAC;IAC/B,MAAM,IAAI,GAAG,OAAO,CAAC,MAAM,CACzB,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,WAAW,EAAE,KAAK,MAAM,IAAI,OAAQ,CAAC,CAAC,IAAgC,EAAE,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aACpD,CAAC,CAAC;YACH,MAAM;QACR,CAAC;IACH,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC"}
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Analyzer 5 — large read results. A read that dumped a huge file should
3
+ * become "always page with offset/limit" guidance for that path.
4
+ */
5
+ import type { Finding, ToolRecord } from "../types.ts";
6
+ export declare const LARGE_FILE_THRESHOLD = 200000;
7
+ export declare function findLargeFiles(records: ToolRecord[]): Finding[];
8
+ //# sourceMappingURL=large-files.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"large-files.d.ts","sourceRoot":"","sources":["../../src/analyze/large-files.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,KAAK,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAGvD,eAAO,MAAM,oBAAoB,SAAU,CAAC;AAE5C,wBAAgB,cAAc,CAAC,OAAO,EAAE,UAAU,EAAE,GAAG,OAAO,EAAE,CAyB/D"}
@@ -0,0 +1,33 @@
1
+ import { anchor } from "../types.js";
2
+ export const LARGE_FILE_THRESHOLD = 200_000;
3
+ export function findLargeFiles(records) {
4
+ const groups = new Map();
5
+ for (const record of records) {
6
+ if (record.name.toLowerCase() !== "read")
7
+ continue;
8
+ if (record.resultChars <= LARGE_FILE_THRESHOLD)
9
+ continue;
10
+ const path = record.args?.file_path;
11
+ if (typeof path !== "string")
12
+ continue;
13
+ const existing = groups.get(path);
14
+ if (existing === undefined) {
15
+ groups.set(path, { count: 1, session: record.sessionId, turn: record.turn });
16
+ }
17
+ else {
18
+ existing.count++;
19
+ }
20
+ }
21
+ const findings = [];
22
+ for (const [path, group] of groups) {
23
+ findings.push({
24
+ kind: "large-file",
25
+ title: `always use offset/limit on ${path}`,
26
+ detail: `Reading it whole returned ${group.count} oversized result(s) (>${LARGE_FILE_THRESHOLD} chars).`,
27
+ occurrences: group.count,
28
+ evidence: [anchor(group.session, group.turn)],
29
+ });
30
+ }
31
+ return findings;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AAW,EAAE,KAAK,CAAC,KAAK;YACxB,QAAQ,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC;SAC9C,CAAC,CAAC;IACL,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC"}
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Analyzer 1 — success correlation on path-ish tools.
3
+ *
4
+ * Finds failures where a later, same-tool success recovered by pointing at a
5
+ * different directory (same basename). Gated: the failure's error text must be
6
+ * path-shaped, otherwise logic/test failures leak in.
7
+ */
8
+ import type { Finding, ToolRecord } from "../types.ts";
9
+ export declare const CORRELATION_TOOLS: Set<string>;
10
+ /** Extract path-like strings from a tool's parsed args object. */
11
+ export declare function extractPaths(args: unknown): string[];
12
+ /** Emit "prefer <goodDir>/ over <badDir> for <file>" findings for one session. */
13
+ export declare function correlatePaths(records: ToolRecord[]): Finding[];
14
+ //# sourceMappingURL=path-correlation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"path-correlation.d.ts","sourceRoot":"","sources":["../../src/analyze/path-correlation.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,KAAK,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAGvD,eAAO,MAAM,iBAAiB,aAM5B,CAAC;AASH,kEAAkE;AAClE,wBAAgB,YAAY,CAAC,IAAI,EAAE,OAAO,GAAG,MAAM,EAAE,CAiBpD;AAiCD,kFAAkF;AAClF,wBAAgB,cAAc,CAAC,OAAO,EAAE,UAAU,EAAE,GAAG,OAAO,EAAE,CA4E/D"}
@@ -0,0 +1,130 @@
1
+ import { anchor } from "../types.js";
2
+ export const CORRELATION_TOOLS = new Set([
3
+ "read",
4
+ "edit",
5
+ "glob",
6
+ "grep",
7
+ "bash",
8
+ ]);
9
+ /** Path-shaped failure markers (case-insensitive). */
10
+ const PATH_ERROR = /enoent|no such file|not found/i;
11
+ function norm(name) {
12
+ return name.toLowerCase();
13
+ }
14
+ /** Extract path-like strings from a tool's parsed args object. */
15
+ export function extractPaths(args) {
16
+ if (typeof args !== "object" || args === null)
17
+ return [];
18
+ const paths = [];
19
+ for (const [key, value] of Object.entries(args)) {
20
+ if (typeof value === "string") {
21
+ if (key === "file_path" ||
22
+ key === "notebook_path" ||
23
+ key === "path" ||
24
+ key === "directory" ||
25
+ key === "cwd") {
26
+ paths.push(value);
27
+ }
28
+ }
29
+ }
30
+ return paths;
31
+ }
32
+ /** Split a bash command into tokens, stripping trailing punctuation. */
33
+ function bashTokens(command) {
34
+ return command
35
+ .split(/\s+/)
36
+ .filter(Boolean)
37
+ .map((token) => token.replace(/[.,;:)'"`]+$/, ""));
38
+ }
39
+ const PATHISH_TOKEN = /\/[^\s/]+\.[a-z]{1,4}$/i;
40
+ function pathishTokens(command) {
41
+ const tokens = bashTokens(command);
42
+ const paths = new Set();
43
+ for (const token of tokens) {
44
+ if (token.includes("/") || PATHISH_TOKEN.test(token)) {
45
+ paths.add(token.toLowerCase());
46
+ }
47
+ }
48
+ return [...paths];
49
+ }
50
+ function basename(p) {
51
+ const idx = p.lastIndexOf("/");
52
+ return idx === -1 ? p : p.slice(idx + 1);
53
+ }
54
+ function dir(p) {
55
+ const idx = p.lastIndexOf("/");
56
+ return idx === -1 ? p : p.slice(0, idx);
57
+ }
58
+ /** Emit "prefer <goodDir>/ over <badDir> for <file>" findings for one session. */
59
+ export function correlatePaths(records) {
60
+ const findings = [];
61
+ const tools = [...records].filter((r) => CORRELATION_TOOLS.has(norm(r.name)));
62
+ for (let i = 0; i < tools.length; i++) {
63
+ const failure = tools[i];
64
+ if (!failure.isError || !PATH_ERROR.test(failure.resultText))
65
+ continue;
66
+ const nName = norm(failure.name);
67
+ if (nName === "bash") {
68
+ const cmd = typeof failure.args?.command === "string"
69
+ ? failure.args.command
70
+ : "";
71
+ const first = bashTokens(cmd)[0];
72
+ // ponytail: bare first-token comparison ("pnpm", "node" alone are noise)
73
+ // and raw token sets — a real argv/shell parser would cut false
74
+ // positives; upgrade when the 20-finding manual gate says so.
75
+ if (first === undefined)
76
+ continue;
77
+ const failedPaths = pathishTokens(cmd);
78
+ for (let j = i + 1; j < tools.length; j++) {
79
+ const success = tools[j];
80
+ if (norm(success.name) !== nName || success.isError)
81
+ continue;
82
+ const cmd2 = typeof success.args?.command === "string"
83
+ ? success.args.command
84
+ : "";
85
+ if (bashTokens(cmd2)[0] !== first)
86
+ continue;
87
+ const good = pathishTokens(cmd2).find((t) => !failedPaths.some((f) => f === t));
88
+ if (good === undefined)
89
+ continue;
90
+ const token = basename(good);
91
+ if (!success.resultText.toLowerCase().includes(token.toLowerCase()))
92
+ continue;
93
+ findings.push({
94
+ kind: "path-correlation",
95
+ title: `prefer corrected path for \`${token}\` in \`${first}\` commands`,
96
+ detail: `\`${cmd}\` failed; \`${cmd2}\` succeeded. Reuse the working path.`,
97
+ occurrences: 1,
98
+ evidence: [anchor(failure.sessionId, failure.turn)],
99
+ });
100
+ break;
101
+ }
102
+ continue;
103
+ }
104
+ const failedPaths = extractPaths(failure.args);
105
+ for (let j = i + 1; j < tools.length; j++) {
106
+ const success = tools[j];
107
+ if (norm(success.name) !== nName || success.isError)
108
+ continue;
109
+ const goodPaths = extractPaths(success.args);
110
+ const match = goodPaths.find((good) => failedPaths.some((bad) => basename(bad) === basename(good) &&
111
+ dir(bad) !== dir(good) &&
112
+ success.resultText.includes(basename(good))));
113
+ if (match === undefined)
114
+ continue;
115
+ const bad = failedPaths.find((p) => basename(p) === basename(match) && dir(p) !== dir(match));
116
+ if (bad === undefined)
117
+ continue;
118
+ findings.push({
119
+ kind: "path-correlation",
120
+ title: `prefer ${dir(match)}/ over ${dir(bad)} for ${basename(match)}`,
121
+ detail: `${failure.name} failed on ${bad}, succeeded on ${match}.`,
122
+ occurrences: 1,
123
+ evidence: [anchor(failure.sessionId, failure.turn)],
124
+ });
125
+ break;
126
+ }
127
+ }
128
+ return findings;
129
+ }
130
+ //# sourceMappingURL=path-correlation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"path-correlation.js","sourceRoot":"","sources":["../../src/analyze/path-correlation.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAErC,MAAM,CAAC,MAAM,iBAAiB,GAAG,IAAI,GAAG,CAAC;IACvC,MAAM;IACN,MAAM;IACN,MAAM;IACN,MAAM;IACN,MAAM;CACP,CAAC,CAAC;AAEH,sDAAsD;AACtD,MAAM,UAAU,GAAG,gCAAgC,CAAC;AAEpD,SAAS,IAAI,CAAC,IAAY;IACxB,OAAO,IAAI,CAAC,WAAW,EAAE,CAAC;AAC5B,CAAC;AAED,kEAAkE;AAClE,MAAM,UAAU,YAAY,CAAC,IAAa;IACxC,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,IAAI;QAAE,OAAO,EAAE,CAAC;IACzD,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,IAA+B,CAAC,EAAE,CAAC;QAC3E,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;YAC9B,IACE,GAAG,KAAK,WAAW;gBACnB,GAAG,KAAK,eAAe;gBACvB,GAAG,KAAK,MAAM;gBACd,GAAG,KAAK,WAAW;gBACnB,GAAG,KAAK,KAAK,EACb,CAAC;gBACD,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;YACpB,CAAC;QACH,CAAC;IACH,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED,wEAAwE;AACxE,SAAS,UAAU,CAAC,OAAe;IACjC,OAAO,OAAO;SACX,KAAK,CAAC,KAAK,CAAC;SACZ,MAAM,CAAC,OAAO,CAAC;SACf,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,cAAc,EAAE,EAAE,CAAC,CAAC,CAAC;AACvD,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AC,IAAI,EAAE,EAAE,CACpC,WAAW,CAAC,IAAI,CACd,CAAC,GAAG,EAAE,EAAE,CACN,QAAQ,CAAC,GAAG,CAAC,KAAK,QAAQ,CAAC,IAAI,CAAC;gBAChC,GAAG,CAAC,GAAG,CAAC,KAAK,GAAG,CAAC,IAAI,CAAC;gBACtB,OAAO,CAAC,UAAU,CAAC,QAAQ,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAC9C,CACF,CAAC;YACF,IAAI,KAAK,KAAK,SAAS;gBAAE,SAAS;YAClC,MAAM,GAAG,GAAG,WAAW,CAAC,IAAI,CAC1B,CAAC,CAAC,EAAE,EAAE,CAAC,QAAQ,CAAC,CAAC,CAAC,KAAK,QAAQ,CAAC,KAAK,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,KAAK,CAAC,CAChE,CAAC;YACF,IAAI,GAAG,KAAK,SAAS;gBAAE,SAAS;YAChC,QAAQ,CAAC,IAAI,CAAC;gBACZ,IAAI,EAAE,kBAAkB;gBACxB,KAAK,EAAE,UAAU,GAAG,CAAC,KAAK,CAAC,UAAU,GAAG,CAAC,GAAG,CAAC,QAAQ,QAAQ,CAAC,KAAK,CAAC,EAAE;gBACtE,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,cAAc,GAAG,kBAAkB,KAAK,GAAG;gBAClE,WAAW,EAAE,CAAC;gBACd,QAAQ,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,SAAS,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC;aACpD,CAAC,CAAC;YACH,MAAM;QACR,CAAC;IACH,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC"}
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Analyzer 4 — permission denials, driven by approval/asked|decided pairs.
3
+ * Only outcome `rejected` counts as a denial: `cancelled` is user
4
+ * abandonment, `unavailable` is infra. Sessions whose stream carried an
5
+ * `approval/policy` event with `policy: "never"` are excluded (their tools
6
+ * are never asked, so they poison the denominator).
7
+ */
8
+ import type { ApprovalPair, Finding, SessionMeta } from "../types.ts";
9
+ export declare function findPermissionDenials(approvals: ApprovalPair[], sessions: SessionMeta[]): Finding[];
10
+ //# sourceMappingURL=permission-denials.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"permission-denials.d.ts","sourceRoot":"","sources":["../../src/analyze/permission-denials.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,KAAK,EAAE,YAAY,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAEtE,wBAAgB,qBAAqB,CACnC,SAAS,EAAE,YAAY,EAAE,EACzB,QAAQ,EAAE,WAAW,EAAE,GACtB,OAAO,EAAE,CAsCX"}
@@ -0,0 +1,40 @@
1
+ export function findPermissionDenials(approvals, sessions) {
2
+ const excluded = new Set(sessions.filter((s) => s.policyNever).map((s) => s.sessionId));
3
+ const groups = new Map();
4
+ for (const pair of approvals) {
5
+ if (pair.outcome !== "rejected")
6
+ continue;
7
+ if (excluded.has(pair.sessionId))
8
+ continue;
9
+ const tool = pair.toolName ?? "unknown";
10
+ const reason = pair.reason ?? "";
11
+ const key = `${tool}\u0000${reason}`;
12
+ const existing = groups.get(key);
13
+ if (existing === undefined) {
14
+ groups.set(key, {
15
+ count: 1,
16
+ tool,
17
+ reason,
18
+ session: pair.sessionId,
19
+ sample: pair,
20
+ });
21
+ }
22
+ else {
23
+ existing.count++;
24
+ }
25
+ }
26
+ const findings = [];
27
+ for (const group of groups.values()) {
28
+ findings.push({
29
+ kind: "permission-denial",
30
+ title: `user keeps rejecting \`${group.tool}\``,
31
+ detail: group.reason === ""
32
+ ? `Rejected ${group.count}×; ask before invoking or stop proposing it.`
33
+ : `Rejected ${group.count}× (reason: ${group.reason}); ask before invoking or stop proposing it.`,
34
+ occurrences: group.count,
35
+ evidence: [`session:${group.session}`],
36
+ });
37
+ }
38
+ return findings;
39
+ }
40
+ //# sourceMappingURL=permission-denials.js.map
@@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,QAAQ,CAAC,IAAI,CAAC;YACZ,IAAI,EAAE,mBAAmB;YACzB,KAAK,EAAE,0BAA0B,KAAK,CAAC,IAAI,IAAI;YAC/C,MAAM,EACJ,KAAK,CAAC,MAAM,KAAK,EAAE;gBACjB,CAAC,CAAC,YAAY,KAAK,CAAC,KAAK,8CAA8C;gBACvE,CAAC,CAAC,YAAY,KAAK,CAAC,KAAK,cAAc,KAAK,CAAC,MAAM,8CAA8C;YACrG,WAAW,EAAE,KAAK,CAAC,KAAK;YACxB,QAAQ,EAAE,CAAC,WAAW,KAAK,CAAC,OAAO,EAAE,CAAC;SACvC,CAAC,CAAC;IACL,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC"}
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Analyzer 3 — search scope. A failed grep whose root is narrow, followed by
3
+ * a successful grep with a similar pattern on a broader (ancestor) root.
4
+ */
5
+ import type { Finding, ToolRecord } from "../types.ts";
6
+ export declare function findSearchScope(records: ToolRecord[]): Finding[];
7
+ //# sourceMappingURL=search-scope.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"search-scope.d.ts","sourceRoot":"","sources":["../../src/analyze/search-scope.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,KAAK,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AA0BvD,wBAAgB,eAAe,CAAC,OAAO,EAAE,UAAU,EAAE,GAAG,OAAO,EAAE,CA6BhE"}
@@ -0,0 +1,59 @@
1
+ import { anchor } from "../types.js";
2
+ function grepArgs(record) {
3
+ const args = record.args;
4
+ if (record.name.toLowerCase() !== "grep" || args === null)
5
+ return undefined;
6
+ if (typeof args.pattern !== "string")
7
+ return undefined;
8
+ return {
9
+ pattern: args.pattern,
10
+ path: typeof args.path === "string" ? args.path : "",
11
+ };
12
+ }
13
+ /**
14
+ * True when `broader` is strictly wider than `narrow`: either the default
15
+ * (empty path = whole cwd) or a strict ancestor directory of it.
16
+ */
17
+ function isBroaderRoot(broader, narrow) {
18
+ if (broader === "")
19
+ return narrow !== "";
20
+ if (broader === narrow || narrow === "")
21
+ return false;
22
+ const b = broader.endsWith("/") ? broader : broader + "/";
23
+ return narrow.startsWith(b);
24
+ }
25
+ export function findSearchScope(records) {
26
+ const findings = [];
27
+ const greps = records.filter((r) => r.name.toLowerCase() === "grep");
28
+ for (let i = 0; i < greps.length; i++) {
29
+ const failure = greps[i];
30
+ if (!failure.isError)
31
+ continue;
32
+ const failed = grepArgs(failure);
33
+ if (failed === undefined || failed.path === "")
34
+ continue;
35
+ for (let j = i + 1; j < greps.length; j++) {
36
+ const success = greps[j];
37
+ if (success.isError)
38
+ continue;
39
+ const good = grepArgs(success);
40
+ if (good === undefined)
41
+ continue;
42
+ const similar = good.pattern === failed.pattern ||
43
+ good.pattern.includes(failed.pattern) ||
44
+ failed.pattern.includes(good.pattern);
45
+ if (!similar || !isBroaderRoot(good.path, failed.path))
46
+ continue;
47
+ findings.push({
48
+ kind: "search-scope",
49
+ title: `search from ${good.path} for \`${failed.pattern}\``,
50
+ detail: `Grep for \`${failed.pattern}\` under ${failed.path} found nothing; the same pattern under ${good.path} succeeded.`,
51
+ occurrences: 1,
52
+ evidence: [anchor(failure.sessionId, failure.turn)],
53
+ });
54
+ break;
55
+ }
56
+ }
57
+ return findings;
58
+ }
59
+ //# sourceMappingURL=search-scope.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"search-scope.js","sourceRoot":"","sources":["../../src/analyze/search-scope.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAErC,SAAS,QAAQ,CAAC,MAAkB;IAGlC,MAAM,IAAI,GAAG,MAAM,CAAC,IAAsC,CAAC;IAC3D,IAAI,MAAM,CAAC,IAAI,CAAC,WAAW,EAAE,KAAK,MAAM,IAAI,IAAI,KAAK,IAAI;QAAE,OAAO,SAAS,CAAC;IAC5E,IAAI,OAAO,IAAI,CAAC,OAAO,KAAK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,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YAC1C,MAAM,OAAO,GAAG,KAAK,CAAC,CAAC,CAAE,CAAC;YAC1B,IAAI,OAAO,CAAC,OAAO;gBAAE,SAAS;YAC9B,MAAM,IAAI,GAAG,QAAQ,CAAC,OAAO,CAAC,CAAC;YAC/B,IAAI,IAAI,KAAK,SAAS;gBAAE,SAAS;YACjC,MAAM,OAAO,GACX,IAAI,CAAC,OAAO,KAAK,MAAM,CAAC,OAAO;gBAC/B,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC;gBACrC,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;YACxC,IAAI,CAAC,OAAO,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC;gBAAE,SAAS;YACjE,QAAQ,CAAC,IAAI,CAAC;gBACZ,IAAI,EAAE,cAAc;gBACpB,KAAK,EAAE,eAAe,IAAI,CAAC,IAAI,UAAU,MAAM,CAAC,OAAO,IAAI;gBAC3D,MAAM,EAAE,cAAc,MAAM,CAAC,OAAO,YAAY,MAAM,CAAC,IAAI,0CAA0C,IAAI,CAAC,IAAI,aAAa;gBAC3H,WAAW,EAAE,CAAC;gBACd,QAAQ,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,SAAS,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC;aACpD,CAAC,CAAC;YACH,MAAM;QACR,CAAC;IACH,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC"}
package/lib/index.d.ts ADDED
@@ -0,0 +1,26 @@
1
+ /**
2
+ * session-forensics — pure analysis library for /learn.
3
+ * Deterministic analyzers over dsh-cc session JSONL stores; no cordis,
4
+ * no @deepseek-ai runtime dependencies.
5
+ */
6
+ export { APPROVAL_OUTCOMES, decompressJsonl, parseStream, scanSessions, } from "./scan.ts";
7
+ export type { ApprovalOutcome, ParsedStream } from "./scan.ts";
8
+ export { correlatePaths } from "./analyze/path-correlation.ts";
9
+ export { findEnvFacts } from "./analyze/env-facts.ts";
10
+ export { findSearchScope } from "./analyze/search-scope.ts";
11
+ export { findPermissionDenials } from "./analyze/permission-denials.ts";
12
+ export { LARGE_FILE_THRESHOLD, findLargeFiles } from "./analyze/large-files.ts";
13
+ export { anchor } from "./types.ts";
14
+ export type { ApprovalPair, Finding, ForensicsOptions, ForensicsResult, ScanStats, SessionMeta, ToolRecord, } from "./types.ts";
15
+ import type { ForensicsOptions, ForensicsResult } from "./types.ts";
16
+ /** Default seam injected from the host (zstd CLI child process). */
17
+ export type Decompress = (file: string) => Promise<string>;
18
+ /**
19
+ * Full pipeline: scan the sessions store, run every analyzer, aggregate raw
20
+ * findings by (kind, title), rank by occurrences, apply the minOccurrences
21
+ * filter (default 2).
22
+ */
23
+ export declare function runForensics(sessionsRoot: string, options?: ForensicsOptions & {
24
+ decompress?: Decompress;
25
+ }): Promise<ForensicsResult>;
26
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EACL,iBAAiB,EACjB,eAAe,EACf,WAAW,EACX,YAAY,GACb,MAAM,WAAW,CAAC;AACnB,YAAY,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAC/D,OAAO,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AAC/D,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AACtD,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AACxE,OAAO,EAAE,oBAAoB,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAChF,OAAO,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AACpC,YAAY,EACV,YAAY,EACZ,OAAO,EACP,gBAAgB,EAChB,eAAe,EACf,SAAS,EACT,WAAW,EACX,UAAU,GACX,MAAM,YAAY,CAAC;AAOpB,OAAO,KAAK,EACV,gBAAgB,EAChB,eAAe,EAEhB,MAAM,YAAY,CAAC;AAEpB,oEAAoE;AACpE,MAAM,MAAM,UAAU,GAAG,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;AAE3D;;;;GAIG;AACH,wBAAsB,YAAY,CAChC,YAAY,EAAE,MAAM,EACpB,OAAO,GAAE,gBAAgB,GAAG;IAAE,UAAU,CAAC,EAAE,UAAU,CAAA;CAAO,GAC3D,OAAO,CAAC,eAAe,CAAC,CAsC1B"}
package/lib/index.js ADDED
@@ -0,0 +1,62 @@
1
+ /**
2
+ * session-forensics — pure analysis library for /learn.
3
+ * Deterministic analyzers over dsh-cc session JSONL stores; no cordis,
4
+ * no @deepseek-ai runtime dependencies.
5
+ */
6
+ export { APPROVAL_OUTCOMES, decompressJsonl, parseStream, scanSessions, } from "./scan.js";
7
+ export { correlatePaths } from "./analyze/path-correlation.js";
8
+ export { findEnvFacts } from "./analyze/env-facts.js";
9
+ export { findSearchScope } from "./analyze/search-scope.js";
10
+ export { findPermissionDenials } from "./analyze/permission-denials.js";
11
+ export { LARGE_FILE_THRESHOLD, findLargeFiles } from "./analyze/large-files.js";
12
+ export { anchor } from "./types.js";
13
+ import { scanSessions } from "./scan.js";
14
+ import { correlatePaths } from "./analyze/path-correlation.js";
15
+ import { findEnvFacts } from "./analyze/env-facts.js";
16
+ import { findSearchScope } from "./analyze/search-scope.js";
17
+ import { findPermissionDenials } from "./analyze/permission-denials.js";
18
+ import { findLargeFiles } from "./analyze/large-files.js";
19
+ /**
20
+ * Full pipeline: scan the sessions store, run every analyzer, aggregate raw
21
+ * findings by (kind, title), rank by occurrences, apply the minOccurrences
22
+ * filter (default 2).
23
+ */
24
+ export async function runForensics(sessionsRoot, options = {}) {
25
+ const minOccurrences = options.minOccurrences ?? 2;
26
+ const scan = await scanSessions(sessionsRoot, options);
27
+ const findings = [
28
+ ...scan.sessions.flatMap((s) => [
29
+ ...correlatePaths(s.records),
30
+ ...findEnvFacts(s.records),
31
+ ...findSearchScope(s.records),
32
+ ]),
33
+ ...findPermissionDenials(scan.approvals, scan.sessions.map((s) => s.meta)),
34
+ ...findLargeFiles(scan.sessions.flatMap((s) => s.records)),
35
+ ];
36
+ // Aggregate identical findings across sessions/occurrences.
37
+ const merged = new Map();
38
+ for (const finding of findings) {
39
+ const key = `${finding.kind}\u0000${finding.title}`;
40
+ const existing = merged.get(key);
41
+ if (existing === undefined) {
42
+ merged.set(key, { ...finding });
43
+ }
44
+ else {
45
+ existing.occurrences += finding.occurrences;
46
+ existing.evidence.push(...finding.evidence);
47
+ }
48
+ }
49
+ const ranked = [...merged.values()]
50
+ .filter((f) => f.occurrences >= minOccurrences)
51
+ .sort((a, b) => b.occurrences - a.occurrences);
52
+ const stats = {
53
+ sessionsScanned: scan.sessions.length,
54
+ linesParsed: scan.linesParsed,
55
+ corruptLinesSkipped: scan.corruptLinesSkipped,
56
+ truncatedTails: scan.truncatedTails,
57
+ sessionsByPolicyNever: scan.sessions.filter((s) => s.meta.policyNever)
58
+ .length,
59
+ };
60
+ return { findings: ranked, stats };
61
+ }
62
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EACL,iBAAiB,EACjB,eAAe,EACf,WAAW,EACX,YAAY,GACb,MAAM,WAAW,CAAC;AAEnB,OAAO,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AAC/D,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AACtD,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AACxE,OAA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@@
1
+ import type { ApprovalPair, ForensicsOptions, SessionMeta, ToolRecord } from "./types.ts";
2
+ /** Event outcome strings observed on approval/decided events. */
3
+ export type ApprovalOutcome = "allowed-once" | "rejected" | "cancelled" | "unavailable";
4
+ export declare const APPROVAL_OUTCOMES: readonly ApprovalOutcome[];
5
+ /** Default zstd seam: shell out to the `zstd` CLI (precedent: scripts/audit-subagent-children.mjs). */
6
+ export declare function decompressJsonl(file: string): Promise<string>;
7
+ export interface ParsedStream {
8
+ meta: SessionMeta;
9
+ records: ToolRecord[];
10
+ approvals: ApprovalPair[];
11
+ linesParsed: number;
12
+ corruptLinesSkipped: number;
13
+ truncatedTail: boolean;
14
+ headerTs?: number | undefined;
15
+ }
16
+ /**
17
+ * Parse one decompressed JSONL session stream. Tolerant by design:
18
+ * a JSON.parse failure on the LAST non-empty line is a truncated live tail
19
+ * (ignored); failures anywhere else are skipped and counted, never thrown.
20
+ */
21
+ export declare function parseStream(project: string, sessionId: string, text: string): ParsedStream;
22
+ /**
23
+ * Walk the sessions root and return every in-window stream's parsed form.
24
+ * Recency: directory mtime is primary; when missing/unreasonable the header
25
+ * timestamp is used instead. Each stream is decompressed at most once.
26
+ */
27
+ export declare function scanSessions(sessionsRoot: string, options?: ForensicsOptions & {
28
+ decompress?: (file: string) => Promise<string>;
29
+ }): Promise<{
30
+ sessions: Array<{
31
+ meta: SessionMeta;
32
+ records: ToolRecord[];
33
+ }>;
34
+ approvals: ApprovalPair[];
35
+ linesParsed: number;
36
+ corruptLinesSkipped: number;
37
+ truncatedTails: number;
38
+ sessionsScanned: number;
39
+ }>;
40
+ //# sourceMappingURL=scan.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scan.d.ts","sourceRoot":"","sources":["../src/scan.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EACV,YAAY,EACZ,gBAAgB,EAChB,WAAW,EACX,UAAU,EACX,MAAM,YAAY,CAAC;AAEpB,iEAAiE;AACjE,MAAM,MAAM,eAAe,GACvB,cAAc,GACd,UAAU,GACV,WAAW,GACX,aAAa,CAAC;AAElB,eAAO,MAAM,iBAAiB,EAAE,SAAS,eAAe,EAKvD,CAAC;AAKF,uGAAuG;AACvG,wBAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAO7D;AAED,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,WAAW,CAAC;IAClB,OAAO,EAAE,UAAU,EAAE,CAAC;IACtB,SAAS,EAAE,YAAY,EAAE,CAAC;IAC1B,WAAW,EAAE,MAAM,CAAC;IACpB,mBAAmB,EAAE,MAAM,CAAC;IAC5B,aAAa,EAAE,OAAO,CAAC;IACvB,QAAQ,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CAC/B;AAyBD;;;;GAIG;AACH,wBAAgB,WAAW,CACzB,OAAO,EAAE,MAAM,EACf,SAAS,EAAE,MAAM,EACjB,IAAI,EAAE,MAAM,GACX,YAAY,CAkHd;AAID;;;;GAIG;AACH,wBAAsB,YAAY,CAChC,YAAY,EAAE,MAAM,EACpB,OAAO,GAAE,gBAAgB,GAAG;IAC1B,UAAU,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;CAC3C,GACL,OAAO,CAAC;IACT,QAAQ,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,WAAW,CAAC;QAAC,OAAO,EAAE,UAAU,EAAE,CAAA;KAAE,CAAC,CAAC;IAC9D,SAAS,EAAE,YAAY,EAAE,CAAC;IAC1B,WAAW,EAAE,MAAM,CAAC;IACpB,mBAAmB,EAAE,MAAM,CAAC;IAC5B,cAAc,EAAE,MAAM,CAAC;IACvB,eAAe,EAAE,MAAM,CAAC;CACzB,CAAC,CA0DD"}
package/lib/scan.js ADDED
@@ -0,0 +1,248 @@
1
+ /**
2
+ * Scanner: walk the dsh-cc sessions store and normalize events into records.
3
+ *
4
+ * Layout: `<sessionsRoot>/<projectKey>/<sessionId>/session.jsonl.zstd`.
5
+ * Child sessions are separate directories; they are distinguished only by
6
+ * the `type: "session"` header line (`origin`, `delegationDepth`,
7
+ * `parentSession`), never by file naming.
8
+ */
9
+ import { execFileSync } from "node:child_process";
10
+ import { readdirSync, statSync } from "node:fs";
11
+ import { join } from "node:path";
12
+ export const APPROVAL_OUTCOMES = [
13
+ "allowed-once",
14
+ "rejected",
15
+ "cancelled",
16
+ "unavailable",
17
+ ];
18
+ /** How much result text to keep on each record (analyzers only need signatures/anchors). */
19
+ const RESULT_TEXT_CAP = 4096;
20
+ /** Default zstd seam: shell out to the `zstd` CLI (precedent: scripts/audit-subagent-children.mjs). */
21
+ export function decompressJsonl(file) {
22
+ const zstdBin = process.env.DSH_ZSTD_BIN ?? "zstd";
23
+ return Promise.resolve(execFileSync(zstdBin, ["-d", "-c", file], {
24
+ maxBuffer: 256 * 1024 * 1024,
25
+ }).toString("utf8"));
26
+ }
27
+ function toTs(value) {
28
+ if (typeof value === "number" && Number.isFinite(value))
29
+ return value;
30
+ if (typeof value === "string") {
31
+ const n = Date.parse(value);
32
+ return Number.isNaN(n) ? undefined : n;
33
+ }
34
+ return undefined;
35
+ }
36
+ function resultCharsOf(content) {
37
+ let chars = 0;
38
+ let text = "";
39
+ if (Array.isArray(content)) {
40
+ for (const block of content) {
41
+ if (block?.type === "text" && typeof block.text === "string") {
42
+ chars += block.text.length;
43
+ if (text.length < RESULT_TEXT_CAP)
44
+ text += block.text;
45
+ }
46
+ }
47
+ }
48
+ return { chars, text: text.slice(0, RESULT_TEXT_CAP) };
49
+ }
50
+ /**
51
+ * Parse one decompressed JSONL session stream. Tolerant by design:
52
+ * a JSON.parse failure on the LAST non-empty line is a truncated live tail
53
+ * (ignored); failures anywhere else are skipped and counted, never thrown.
54
+ */
55
+ export function parseStream(project, sessionId, text) {
56
+ const meta = { project, sessionId, policyNever: false };
57
+ let headerTs;
58
+ const records = [];
59
+ const approvals = [];
60
+ const pending = new Map();
61
+ const lines = text.split("\n").filter((line) => line.length > 0);
62
+ const stats = { linesParsed: 0, corruptLinesSkipped: 0, truncatedTail: false };
63
+ for (const [i, line] of lines.entries()) {
64
+ let entry;
65
+ try {
66
+ entry = JSON.parse(line);
67
+ }
68
+ catch {
69
+ if (i === lines.length - 1)
70
+ stats.truncatedTail = true;
71
+ else
72
+ stats.corruptLinesSkipped++;
73
+ continue;
74
+ }
75
+ stats.linesParsed++;
76
+ const type = entry?.type;
77
+ const data = entry?.data;
78
+ if (type === "session" && meta.origin === undefined) {
79
+ if (typeof data?.origin === "string")
80
+ meta.origin = data.origin;
81
+ if (typeof data?.delegationDepth === "number")
82
+ meta.delegationDepth = data.delegationDepth;
83
+ headerTs = toTs(entry.ts ?? entry.timestamp);
84
+ continue;
85
+ }
86
+ if (type === "approval/policy") {
87
+ if (data?.policy === "never")
88
+ meta.policyNever = true;
89
+ continue;
90
+ }
91
+ if (type === "approval/asked") {
92
+ if (typeof data?.id === "string") {
93
+ // Decided may already have arrived (out-of-order streams): merge.
94
+ let pair = approvals.find((a) => a.id === data.id);
95
+ if (pair === undefined) {
96
+ pair = { project, sessionId, id: data.id };
97
+ approvals.push(pair);
98
+ }
99
+ if (typeof data.toolName === "string")
100
+ pair.toolName = data.toolName;
101
+ if (typeof data.callId === "string")
102
+ pair.callId = data.callId;
103
+ if (typeof data.reason === "string")
104
+ pair.reason = data.reason;
105
+ }
106
+ continue;
107
+ }
108
+ if (type === "approval/decided") {
109
+ if (typeof data?.id === "string") {
110
+ let pair = approvals.find((a) => a.id === data.id);
111
+ if (pair === undefined) {
112
+ pair = { project, sessionId, id: data.id };
113
+ approvals.push(pair);
114
+ }
115
+ if (typeof data.outcome === "string")
116
+ pair.outcome = data.outcome;
117
+ }
118
+ continue;
119
+ }
120
+ if (type === "tool/call") {
121
+ const name = typeof data?.name === "string" ? data.name : "";
122
+ if (name === "")
123
+ continue;
124
+ const argsRaw = typeof data?.arguments === "string" ? data.arguments : undefined;
125
+ let args = null;
126
+ if (argsRaw !== undefined) {
127
+ try {
128
+ args = JSON.parse(argsRaw);
129
+ }
130
+ catch {
131
+ args = null;
132
+ }
133
+ }
134
+ const record = {
135
+ project,
136
+ sessionId,
137
+ origin: meta.origin,
138
+ delegationDepth: meta.delegationDepth,
139
+ turn: typeof data?.turn === "number" ? data.turn : undefined,
140
+ step: typeof data?.step === "number" ? data.step : undefined,
141
+ name,
142
+ argsRaw,
143
+ args,
144
+ resultChars: 0,
145
+ resultText: "",
146
+ isError: false,
147
+ ts: toTs(entry.ts ?? entry.timestamp),
148
+ };
149
+ records.push(record);
150
+ if (typeof data?.callId === "string")
151
+ pending.set(data.callId, record);
152
+ continue;
153
+ }
154
+ if (type === "tool/result") {
155
+ const callId = data?.message?.source?.callId;
156
+ const record = typeof callId === "string" ? pending.get(callId) : undefined;
157
+ if (record === undefined)
158
+ continue;
159
+ const payload = Array.isArray(data?.message?.content)
160
+ ? data.message.content[0]
161
+ : undefined;
162
+ if (payload?.type !== "tool-result")
163
+ continue;
164
+ const { chars, text: resultText } = resultCharsOf(payload.content);
165
+ record.resultChars = chars;
166
+ record.resultText = resultText;
167
+ record.isError = payload.isError === true;
168
+ continue;
169
+ }
170
+ }
171
+ return {
172
+ meta,
173
+ records,
174
+ approvals,
175
+ headerTs,
176
+ ...stats,
177
+ };
178
+ }
179
+ const DAY_MS = 24 * 60 * 60 * 1000;
180
+ /**
181
+ * Walk the sessions root and return every in-window stream's parsed form.
182
+ * Recency: directory mtime is primary; when missing/unreasonable the header
183
+ * timestamp is used instead. Each stream is decompressed at most once.
184
+ */
185
+ export async function scanSessions(sessionsRoot, options = {}) {
186
+ const decompress = options.decompress ?? decompressJsonl;
187
+ const days = options.days ?? 14;
188
+ const cutoff = Date.now() - days * DAY_MS;
189
+ const sessions = [];
190
+ const approvals = [];
191
+ let linesParsed = 0;
192
+ let corruptLinesSkipped = 0;
193
+ let truncatedTails = 0;
194
+ let projectKeys;
195
+ try {
196
+ projectKeys = readdirSync(sessionsRoot);
197
+ }
198
+ catch {
199
+ // Missing/empty sessions root: zero findings, no throw.
200
+ projectKeys = [];
201
+ }
202
+ for (const projectKey of projectKeys) {
203
+ if (options.project !== undefined && projectKey !== options.project)
204
+ continue;
205
+ const projectDir = join(sessionsRoot, projectKey);
206
+ for (const sessionId of readdirSync(projectDir)) {
207
+ const dir = join(projectDir, sessionId);
208
+ const file = join(dir, "session.jsonl.zstd");
209
+ let mtimeMs;
210
+ try {
211
+ mtimeMs = statSync(dir).mtimeMs;
212
+ }
213
+ catch {
214
+ mtimeMs = undefined;
215
+ }
216
+ const mtimeReasonable = mtimeMs !== undefined && Number.isFinite(mtimeMs) && mtimeMs > 0;
217
+ if (mtimeReasonable && mtimeMs < cutoff)
218
+ continue; // mtime out of window: skip without decompressing
219
+ let text;
220
+ try {
221
+ text = await decompress(file);
222
+ }
223
+ catch {
224
+ continue;
225
+ }
226
+ const parsed = parseStream(projectKey, sessionId, text);
227
+ // mtime unreliable (or absent): fall back to the header timestamp.
228
+ const headerTs = parsed.headerTs;
229
+ if (!mtimeReasonable && headerTs !== undefined && headerTs < cutoff)
230
+ continue;
231
+ sessions.push({ meta: parsed.meta, records: parsed.records });
232
+ approvals.push(...parsed.approvals);
233
+ linesParsed += parsed.linesParsed;
234
+ corruptLinesSkipped += parsed.corruptLinesSkipped;
235
+ if (parsed.truncatedTail)
236
+ truncatedTails++;
237
+ }
238
+ }
239
+ return {
240
+ sessions,
241
+ approvals,
242
+ sessionsScanned: sessions.length,
243
+ linesParsed,
244
+ corruptLinesSkipped,
245
+ truncatedTails,
246
+ };
247
+ }
248
+ //# sourceMappingURL=scan.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scan.js","sourceRoot":"","sources":["../src/scan.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAChD,OAAO,EAAE,IAAI,EAAE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,IAAI,QAAQ,GAAG,MAAM;gBACjE,SAAS;YACX,QAAQ,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,EAAE,CAAC,CAAC;YAC9D,SAAS,CAAC,IAAI,CAAC,GAAG,MAAM,CAAC,SAAS,CAAC,CAAC;YACpC,WAAW,IAAI,MAAM,CAAC,WAAW,CAAC;YAClC,mBAAmB,IAAI,MAAM,CAAC,mBAAmB,CAAC;YAClD,IAAI,MAAM,CAAC,aAAa;gBAAE,cAAc,EAAE,CAAC;QAC7C,CAAC;IACH,CAAC;IACD,OAAO;QACL,QAAQ;QACR,SAAS;QACT,eAAe,EAAE,QAAQ,CAAC,MAAM;QAChC,WAAW;QACX,mBAAmB;QACnB,cAAc;KACf,CAAC;AACJ,CAAC"}
package/lib/types.d.ts ADDED
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Shared types for the session-forensics analysis library.
3
+ */
4
+ /** One normalized tool call, paired with its result when present. */
5
+ export interface ToolRecord {
6
+ project: string;
7
+ sessionId: string;
8
+ origin?: string | undefined;
9
+ delegationDepth?: number | undefined;
10
+ turn?: number | undefined;
11
+ step?: number | undefined;
12
+ /** Tool name as written in the event (lowercased copy is used for matching). */
13
+ name: string;
14
+ /** Raw JSON-encoded `arguments` string from the tool/call event. */
15
+ argsRaw?: string | undefined;
16
+ /** JSON.parse of argsRaw, or null when absent/unparseable. */
17
+ args: unknown;
18
+ /** Total length of text content in the paired tool result. */
19
+ resultChars: number;
20
+ /** First chunk of the paired result text (bounded) for gates/signatures. */
21
+ resultText: string;
22
+ isError: boolean;
23
+ ts?: number | undefined;
24
+ }
25
+ /** An approval/asked event paired with its approval/decided outcome by `data.id`. */
26
+ export interface ApprovalPair {
27
+ project: string;
28
+ sessionId: string;
29
+ id: string;
30
+ toolName?: string | undefined;
31
+ callId?: string | undefined;
32
+ reason?: string | undefined;
33
+ outcome?: string | undefined;
34
+ }
35
+ /** Per-session header facts the analyzers need. */
36
+ export interface SessionMeta {
37
+ project: string;
38
+ sessionId: string;
39
+ origin?: string | undefined;
40
+ delegationDepth?: number | undefined;
41
+ /** True when the stream carried an `approval/policy` event with `policy: "never"`. */
42
+ policyNever: boolean;
43
+ }
44
+ export interface Finding {
45
+ kind: "path-correlation" | "env-fact" | "search-scope" | "permission-denial" | "large-file";
46
+ title: string;
47
+ detail: string;
48
+ occurrences: number;
49
+ /** Anchors of the form `session:<sessionId>#turn=<n>`. */
50
+ evidence: string[];
51
+ }
52
+ export interface ScanStats {
53
+ sessionsScanned: number;
54
+ linesParsed: number;
55
+ corruptLinesSkipped: number;
56
+ truncatedTails: number;
57
+ sessionsByPolicyNever: number;
58
+ }
59
+ export interface ForensicsResult {
60
+ findings: Finding[];
61
+ stats: ScanStats;
62
+ }
63
+ export interface ForensicsOptions {
64
+ /** Only include sessions whose (mtime or header) timestamp is within the last N days. */
65
+ days?: number | undefined;
66
+ /** Restrict to one project key; omit for all projects. */
67
+ project?: string | undefined;
68
+ /** Drop findings seen fewer than this many times (default 2). */
69
+ minOccurrences?: number | undefined;
70
+ }
71
+ /** Anchor string for evidence lists. */
72
+ export declare function anchor(sessionId: string, turn?: number): string;
73
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,qEAAqE;AACrE,MAAM,WAAW,UAAU;IACzB,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC5B,eAAe,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACrC,IAAI,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC1B,IAAI,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC1B,gFAAgF;IAChF,IAAI,EAAE,MAAM,CAAC;IACb,oEAAoE;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MAAM,CAAC;IACvB,qBAAqB,EAAE,MAAM,CAAC;CAC/B;AAED,MAAM,WAAW,eAAe;IAC9B,QAAQ,EAAE,OAAO,EAAE,CAAC;IACpB,KAAK,EAAE,SAAS,CAAC;CAClB;AAED,MAAM,WAAW,gBAAgB;IAC/B,yFAAyF;IACzF,IAAI,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC1B,0DAA0D;IAC1D,OAAO,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC7B,iEAAiE;IACjE,cAAc,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CACrC;AAED,wCAAwC;AACxC,wBAAgB,MAAM,CAAC,SAAS,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,MAAM,CAI/D"}
package/lib/types.js ADDED
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Shared types for the session-forensics analysis library.
3
+ */
4
+ /** Anchor string for evidence lists. */
5
+ export function anchor(sessionId, turn) {
6
+ return turn === undefined
7
+ ? `session:${sessionId}`
8
+ : `session:${sessionId}#turn=${turn}`;
9
+ }
10
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;GAEG;AAiFH,wCAAwC;AACxC,MAAM,UAAU,MAAM,CAAC,SAAiB,EAAE,IAAa;IACrD,OAAO,IAAI,KAAK,SAAS;QACvB,CAAC,CAAC,WAAW,SAAS,EAAE;QACxB,CAAC,CAAC,WAAW,SAAS,SAAS,IAAI,EAAE,CAAC;AAC1C,CAAC"}
package/package.json ADDED
@@ -0,0 +1,26 @@
1
+ {
2
+ "name": "@dsh-cc/session-forensics",
3
+ "description": "Pure analysis library distilling session failure patterns (used by /learn)",
4
+ "version": "0.7.1-rc.1",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/dsh-cc/dsh-cc.git",
8
+ "directory": "packages/session/session-forensics"
9
+ },
10
+ "type": "module",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./lib/index.d.ts",
14
+ "default": "./lib/index.js"
15
+ },
16
+ "./src/*": "./src/*",
17
+ "./package.json": "./package.json"
18
+ },
19
+ "files": [
20
+ "lib"
21
+ ],
22
+ "license": "Apache-2.0",
23
+ "publishConfig": {
24
+ "access": "public"
25
+ }
26
+ }