threadctx 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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,30 @@
1
+ threadctx — Agent Context Integrity
2
+ Copyright 2026 threadctx
3
+
4
+ Licensed under the Apache License, Version 2.0 (see LICENSE).
5
+ apps/web (the threadctx cloud) is proprietary and excluded from that licence.
6
+
7
+ Portions are derived from the following MIT-licensed projects by the same author.
8
+ Each derived file names its origin repository and commit in a header comment.
9
+
10
+ curatedmcp-launcher https://github.com/oneprofile-dev/mcp-launcher MIT
11
+ mcp-auditor https://github.com/oneprofile-dev/mcp-auditor MIT
12
+ tokenshield https://github.com/oneprofile-dev/tokenshield MIT
13
+ threadctx-mcp https://github.com/threadctx-dev/threadctx-mcp MIT
14
+ archsteer https://github.com/einvoice-dev1/archsteer MIT
15
+
16
+ MIT License text for derived portions:
17
+
18
+ Permission is hereby granted, free of charge, to any person obtaining a copy
19
+ of this software and associated documentation files (the "Software"), to deal
20
+ in the Software without restriction, including without limitation the rights
21
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
22
+ copies of the Software, and to permit persons to whom the Software is
23
+ furnished to do so, subject to the following conditions:
24
+
25
+ The above copyright notice and this permission notice shall be included in all
26
+ copies or substantial portions of the Software.
27
+
28
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
29
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
30
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
package/README.md ADDED
@@ -0,0 +1,88 @@
1
+ # threadctx
2
+
3
+ **Your coding agents' instructions are stale, and copied across tools. See exactly what each agent is told, and fix it.**
4
+
5
+ Claude Code, Cursor, Copilot, Gemini CLI and Codex each read different files. In a benchmark of 210
6
+ public repositories, 64% feed context to two or more agents. Those copies drift: they point at files
7
+ that no longer exist, repeat each other, and grow past what is worth loading on every session.
8
+
9
+ `threadctx` finds every agent context file in a repository (AGENTS.md, CLAUDE.md, Cursor rules,
10
+ Copilot instructions, GEMINI.md, skills, MCP configs), shows what each agent actually loads, and grades it A–F:
11
+
12
+ - **Drift:** dead paths, undefined scripts, the wrong package manager, outdated versions.
13
+ - **Duplication and waste:** the same instructions in several files, bloated always-loaded context.
14
+ - **Isolated copies:** tool-specific files that never see your shared AGENTS.md.
15
+ - **Conflicts:** AGENTS.md says `pnpm`, CLAUDE.md says `npm`.
16
+ - **Injection risks:** hidden Unicode, curl-pipe-to-shell, secrets in context, unpinned MCP servers.
17
+
18
+ It runs locally and offline. No account, and your code never leaves your machine.
19
+
20
+ ```bash
21
+ npx threadctx scan
22
+ ```
23
+
24
+ ```text
25
+ CLAUDE.md
26
+ 2: blocker Conflicting package manager: CLAUDE.md says npm, AGENTS.md:2 says pnpm. Agents reading different files will do different things. CTX-C001
27
+ 2: warning `npm install` uses npm, but pnpm-lock.yaml says this repository uses pnpm. CTX-D003 [fixable]
28
+ 3: warning `npm run build` uses npm, but pnpm-lock.yaml says this repository uses pnpm. CTX-D003 [fixable]
29
+ 4: blocker Contains 1 invisible or bidirectional character (U+200B). Reviewers cannot see what the agent reads. CTX-X001 [fixable]
30
+
31
+ Grade F (40/100) 2 blockers, 2 warnings, 0 info
32
+ 3 findings can be fixed automatically: threadctx fix
33
+ ```
34
+
35
+ ## What each agent loads
36
+
37
+ ```bash
38
+ npx threadctx explain src/payments/refund.ts # every tool, in precedence order
39
+ npx threadctx diff --path src/payments # where the agents disagree
40
+ ```
41
+
42
+ ## Fix
43
+
44
+ ```bash
45
+ npx threadctx fix # print safe fixes as a patch
46
+ npx threadctx fix --apply # write them (never commits)
47
+ ```
48
+
49
+ ## In CI
50
+
51
+ ```bash
52
+ npx threadctx scan --format sarif --output threadctx.sarif # upload to GitHub code scanning
53
+ npx threadctx scan --fail-on warning # exit 1 on warnings or worse
54
+ ```
55
+
56
+ Exit codes: `0` passed · `1` findings at or above the threshold · `2` usage or config error.
57
+
58
+ ## Configure
59
+
60
+ `.threadctx/config.yaml`:
61
+
62
+ ```yaml
63
+ failOn: blocker
64
+ budgets: { default: 5000, claude-code: 8000 } # estimated always-loaded tokens per tool
65
+ rules:
66
+ CTX-B003: off
67
+ suppress:
68
+ - rule: CTX-D001
69
+ path: "docs/**"
70
+ reason: docs describe a sibling repository
71
+ expires: 2026-12-31
72
+ ```
73
+
74
+ Inline: `<!-- ctx-ignore CTX-D001: generated at build time -->` (a reason is required).
75
+
76
+ Add your own rules with YAML [rule packs](docs/extending.md).
77
+
78
+ ## Principles
79
+
80
+ - **Precision over recall.** A false positive is a bug. Each rule's false-positive rate is
81
+ measured on a public benchmark corpus.
82
+ - **Remove, don't add.** threadctx never writes context with an LLM; it shrinks and corrects it.
83
+ - **Declared, not observed.** `explain` shows what a correctly behaving tool loads, according
84
+ to its docs as of the verification date in `threadctx tools`. The Claude Code adapter is also
85
+ checked against the real tool (`fixtures/oracle`).
86
+ - **Offline by default.** No network access, no telemetry.
87
+
88
+ Rules: `npx threadctx rules` · Adapters: `npx threadctx tools` · Licence: Apache-2.0
package/dist/bin.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/bin.js ADDED
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env node
2
+ import { main } from "./cli.js";
3
+ const code = await main(process.argv.slice(2), {
4
+ cwd: process.cwd(),
5
+ env: process.env,
6
+ stdout: (s) => process.stdout.write(s),
7
+ stderr: (s) => process.stderr.write(s),
8
+ isTTY: Boolean(process.stdout.isTTY),
9
+ now: () => new Date(),
10
+ });
11
+ process.exitCode = code;
12
+ //# sourceMappingURL=bin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bin.js","sourceRoot":"","sources":["../src/bin.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,IAAI,EAAE,MAAM,UAAU,CAAC;AAEhC,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE;IAC7C,GAAG,EAAE,OAAO,CAAC,GAAG,EAAE;IAClB,GAAG,EAAE,OAAO,CAAC,GAAG;IAChB,MAAM,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IACtC,MAAM,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IACtC,KAAK,EAAE,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC;IACpC,GAAG,EAAE,GAAG,EAAE,CAAC,IAAI,IAAI,EAAE;CACtB,CAAC,CAAC;AACH,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC"}
package/dist/cli.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ export interface Io {
2
+ cwd: string;
3
+ env: NodeJS.ProcessEnv;
4
+ stdout: (s: string) => void;
5
+ stderr: (s: string) => void;
6
+ isTTY: boolean;
7
+ now: () => Date;
8
+ }
9
+ export declare function main(argv: string[], io: Io): Promise<number>;
10
+ /** Set when the paid capability exists (Phase 2). Until then no upgrade line is printed. */
11
+ export declare const UPGRADE_URL: string | undefined;
package/dist/cli.js ADDED
@@ -0,0 +1,330 @@
1
+ import { existsSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { basename, dirname, join, relative, resolve, sep } from "node:path";
4
+ import { parseArgs } from "node:util";
5
+ import { ADAPTERS, getAdapter, resolveCopilot } from "@threadctx/adapters";
6
+ import { normalizeCommand } from "@threadctx/core";
7
+ import { openRepo } from "@threadctx/discovery";
8
+ import { renderEffective, renderFactTable, renderJson, renderMarkdown, renderSarif, renderText } from "@threadctx/report";
9
+ import { ConfigError, ENGINE_VERSION, exitCodeFor, loadConfig, PackError, parsePack, prepare, REGISTRY_VERSION, RULES, scan, } from "@threadctx/rules";
10
+ import { planFixes } from "./fix.js";
11
+ import { gitHistory, gitRoot } from "./git.js";
12
+ class UsageError extends Error {
13
+ }
14
+ const HELP = `threadctx ${ENGINE_VERSION} — scan, fix and explain what every AI coding agent is told
15
+
16
+ Usage:
17
+ threadctx scan [path] Find and grade agent context (AGENTS.md, CLAUDE.md, Cursor,
18
+ Copilot and Gemini files, MCP configs)
19
+ --format text|json|sarif|md Output format (default text)
20
+ --output <file> Write the report to a file instead of stdout
21
+ --fail-on blocker|warning|info|none
22
+ Exit 1 when a finding is at or above this level
23
+ (default: config failOn, else blocker)
24
+ --rule <id> Only run these rules (repeatable)
25
+ --verbose Show info-level findings in text output
26
+ threadctx explain <file> [--tool <id>|all] [--surface cloud-agent|code-review|chat]
27
+ What each agent loads for this file, in precedence order
28
+ threadctx diff [--path <dir>] What each agent believes about the same directory
29
+ threadctx fix [path] [--apply] [--output <patch>]
30
+ Safe fixes as a patch (never commits; --apply writes files)
31
+ threadctx rules [id] List rules, or show one
32
+ threadctx tools List tool adapters and when each was verified
33
+ threadctx pack validate <file> Check a rule pack before using it
34
+
35
+ Common options: --json (explain, diff, rules, tools), --no-color, --version, --help
36
+
37
+ Exit codes: 0 passed · 1 findings at or above the threshold · 2 usage or config error
38
+ Docs: https://threadctx.dev/docs · Rules: https://threadctx.dev/rules
39
+ `;
40
+ const OPTIONS = {
41
+ format: { type: "string" },
42
+ output: { type: "string" },
43
+ "fail-on": { type: "string" },
44
+ rule: { type: "string", multiple: true },
45
+ verbose: { type: "boolean" },
46
+ tool: { type: "string" },
47
+ surface: { type: "string" },
48
+ path: { type: "string" },
49
+ apply: { type: "boolean" },
50
+ json: { type: "boolean" },
51
+ color: { type: "boolean" },
52
+ "no-color": { type: "boolean" },
53
+ "no-telemetry": { type: "boolean" },
54
+ "no-history": { type: "boolean" },
55
+ version: { type: "boolean", short: "v" },
56
+ help: { type: "boolean", short: "h" },
57
+ };
58
+ export async function main(argv, io) {
59
+ try {
60
+ return await run(argv, io);
61
+ }
62
+ catch (e) {
63
+ if (e instanceof UsageError || e instanceof ConfigError || e instanceof PackError) {
64
+ io.stderr(`threadctx: ${e.message}\n`);
65
+ return 2;
66
+ }
67
+ io.stderr(`threadctx: unexpected error: ${e.stack ?? e}\nPlease report this at https://github.com/threadctx-dev/ctx/issues\n`);
68
+ return 2;
69
+ }
70
+ }
71
+ async function run(argv, io) {
72
+ let parsed;
73
+ try {
74
+ parsed = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true, strict: true });
75
+ }
76
+ catch (e) {
77
+ throw new UsageError(`${e.message}\nRun 'threadctx --help' for usage.`);
78
+ }
79
+ const { values: v, positionals } = parsed;
80
+ if (v.version) {
81
+ io.stdout(`threadctx ${ENGINE_VERSION} (rules ${REGISTRY_VERSION})\n`);
82
+ return 0;
83
+ }
84
+ const [command = "help", ...args] = positionals;
85
+ if (v.help || command === "help") {
86
+ io.stdout(HELP);
87
+ return 0;
88
+ }
89
+ const color = v["no-color"] ? false : v.color ? true : io.isTTY && !io.env.NO_COLOR && io.env.TERM !== "dumb";
90
+ switch (command) {
91
+ case "scan":
92
+ return cmdScan(args[0], v, io, color);
93
+ case "explain":
94
+ return cmdExplain(args[0], v, io, color);
95
+ case "diff":
96
+ return cmdDiff(v, io, color);
97
+ case "fix":
98
+ return cmdFix(args[0], v, io);
99
+ case "rules":
100
+ return cmdRules(args[0], v, io);
101
+ case "tools":
102
+ return cmdTools(v, io);
103
+ case "pack":
104
+ if (args[0] !== "validate" || !args[1])
105
+ throw new UsageError("usage: threadctx pack validate <file>");
106
+ return cmdPackValidate(args[1], io);
107
+ default:
108
+ throw new UsageError(`unknown command '${command}'. Run 'threadctx --help' for usage.`);
109
+ }
110
+ }
111
+ function openRoot(pathArg, io) {
112
+ const target = resolve(io.cwd, pathArg ?? ".");
113
+ if (!existsSync(target))
114
+ throw new UsageError(`path not found: ${pathArg}`);
115
+ if (!statSync(target).isDirectory())
116
+ throw new UsageError(`not a directory: ${pathArg} (scan takes a repository or directory)`);
117
+ return openRepo(target);
118
+ }
119
+ function doScan(repo, v, io) {
120
+ const history = v["no-history"] ? undefined : gitHistory(repo.root);
121
+ return scan(repo, { history, now: io.now(), only: v.rule });
122
+ }
123
+ function cmdScan(pathArg, v, io, color) {
124
+ const format = v.format ?? "text";
125
+ if (!["text", "json", "sarif", "md"].includes(format))
126
+ throw new UsageError(`--format must be text, json, sarif or md (got '${format}')`);
127
+ const failOn = v["fail-on"];
128
+ if (failOn && !["blocker", "warning", "info", "none"].includes(failOn))
129
+ throw new UsageError("--fail-on must be blocker, warning, info or none");
130
+ const repo = openRoot(pathArg, io);
131
+ const result = doScan(repo, v, io);
132
+ const out = format === "json" ? renderJson(result)
133
+ : format === "sarif" ? renderSarif(result)
134
+ : format === "md" ? renderMarkdown(result)
135
+ : renderText(result, { color: v.output ? false : color, verbose: Boolean(v.verbose) });
136
+ if (v.output) {
137
+ const dest = resolve(io.cwd, v.output);
138
+ mkdirSync(dirname(dest), { recursive: true });
139
+ writeFileSync(dest, out);
140
+ io.stderr(`Wrote ${format} report to ${relative(io.cwd, dest) || dest} — grade ${result.grade}, ${result.counts.blocker} blocker, ${result.counts.warning} warning\n`);
141
+ }
142
+ else
143
+ io.stdout(out);
144
+ if (format === "text" && !v.output)
145
+ maybeUpgradeLine(result, io);
146
+ const threshold = failOn ?? loadConfig(repo).failOn;
147
+ return exitCodeFor(result, threshold);
148
+ }
149
+ /** Repository root plus the target path relative to it. */
150
+ function locate(fileArg, io) {
151
+ // Resolve symlinks (macOS /var -> /private/var) so paths compare with git's real root.
152
+ const real = (p) => {
153
+ try {
154
+ return realpathSync(p);
155
+ }
156
+ catch {
157
+ return p;
158
+ }
159
+ };
160
+ const given = resolve(io.cwd, fileArg);
161
+ const abs = existsSync(given) ? real(given) : join(real(dirname(given)), basename(given));
162
+ const root = real(gitRoot(existsSync(abs) && statSync(abs).isDirectory() ? abs : dirname(abs)) ?? io.cwd);
163
+ const rel = relative(root, abs).split(sep).join("/");
164
+ if (rel.startsWith(".."))
165
+ throw new UsageError(`${fileArg} is outside the repository at ${root}`);
166
+ const isDir = existsSync(abs) && statSync(abs).isDirectory();
167
+ return { repo: openRepo(root), target: { path: rel === "" ? "" : rel, isDir } };
168
+ }
169
+ function contextsFor(repo, target, toolArg, surface) {
170
+ const state = prepare(repo);
171
+ const tools = !toolArg || toolArg === "all" ? ADAPTERS : [getAdapter(toolArg) ?? fail(`unknown tool '${toolArg}'. Known: ${ADAPTERS.map((a) => a.id).join(", ")}`)];
172
+ if (surface && !["cloud-agent", "code-review", "chat"].includes(surface))
173
+ throw new UsageError("--surface must be cloud-agent, code-review or chat");
174
+ return tools.map((a) => ({
175
+ label: a.id === "copilot" && surface ? `${a.label} (${surface})` : a.label,
176
+ ctx: a.id === "copilot" && surface ? resolveCopilot(target, state.catalog, surface) : a.resolve(target, state.catalog),
177
+ }));
178
+ }
179
+ function fail(message) {
180
+ throw new UsageError(message);
181
+ }
182
+ function cmdExplain(fileArg, v, io, color) {
183
+ if (!fileArg)
184
+ throw new UsageError("usage: threadctx explain <file> [--tool <id>|all]");
185
+ const { repo, target } = locate(fileArg, io);
186
+ const contexts = contextsFor(repo, target, v.tool, v.surface);
187
+ if (v.json)
188
+ io.stdout(`${JSON.stringify(contexts.map((c) => c.ctx), null, 2)}\n`);
189
+ else
190
+ io.stdout(renderEffective(contexts, { color }));
191
+ return 0;
192
+ }
193
+ function cmdDiff(v, io, color) {
194
+ const { repo, target } = locate(v.path ?? ".", io);
195
+ const dirTarget = { path: target.path, isDir: true };
196
+ const contexts = contextsFor(repo, dirTarget, "all", undefined).filter((c) => c.ctx.layers.length > 0);
197
+ const state = prepare(repo);
198
+ const rows = new Map();
199
+ for (const { ctx } of contexts) {
200
+ for (const layer of ctx.layers) {
201
+ if (layer.loading === "agent-decides")
202
+ continue;
203
+ const a = state.catalog.get(layer.path);
204
+ for (const d of a?.directives ?? []) {
205
+ if (d.kind === "prohibition")
206
+ continue;
207
+ for (const f of d.facts) {
208
+ if (f.topicKey === "cmd.install")
209
+ continue;
210
+ const row = rows.get(f.topicKey) ?? {};
211
+ const val = f.topicKey.startsWith("cmd.") ? normalizeCommand(f.value) : f.value;
212
+ const list = row[ctx.tool] ?? [];
213
+ if (!list.includes(val))
214
+ list.push(val);
215
+ row[ctx.tool] = list;
216
+ rows.set(f.topicKey, row);
217
+ }
218
+ }
219
+ }
220
+ }
221
+ const factRows = [...rows.entries()].sort(([a], [b]) => (a < b ? -1 : 1)).map(([topic, values]) => ({ topic, values }));
222
+ if (v.json) {
223
+ io.stdout(`${JSON.stringify({ path: dirTarget.path || ".", tools: contexts.map((c) => c.ctx), facts: factRows }, null, 2)}\n`);
224
+ return 0;
225
+ }
226
+ io.stdout(`What each agent is told for ${dirTarget.path || "the repository root"}/\n\n`);
227
+ io.stdout(renderFactTable(factRows, contexts.map((c) => c.ctx.tool), { color }));
228
+ io.stdout("\n");
229
+ io.stdout(renderEffective(contexts, { color }));
230
+ return 0;
231
+ }
232
+ function cmdFix(pathArg, v, io) {
233
+ const repo = openRoot(pathArg, io);
234
+ const result = doScan(repo, v, io);
235
+ const plan = planFixes(repo, result.findings);
236
+ for (const s of plan.skipped)
237
+ io.stderr(`skipped ${s.finding.ruleId} at ${s.finding.path}:${s.finding.line ?? ""}: ${s.reason}\n`);
238
+ if (plan.files.size === 0) {
239
+ io.stderr("No safe fixes to apply.\n");
240
+ return 0;
241
+ }
242
+ if (v.apply) {
243
+ for (const [p, { after }] of plan.files)
244
+ writeFileSync(join(repo.root, p), after);
245
+ io.stderr(`Applied ${plan.applied.length} fix${plan.applied.length === 1 ? "" : "es"} to ${plan.files.size} file${plan.files.size === 1 ? "" : "s"}. Review with git diff; nothing was committed.\n`);
246
+ return 0;
247
+ }
248
+ if (v.output) {
249
+ writeFileSync(resolve(io.cwd, v.output), plan.patch);
250
+ io.stderr(`Wrote ${plan.applied.length} fix${plan.applied.length === 1 ? "" : "es"} to ${v.output}. Apply with: git apply ${v.output}\n`);
251
+ }
252
+ else {
253
+ io.stdout(plan.patch);
254
+ io.stderr(`${plan.applied.length} safe fix${plan.applied.length === 1 ? "" : "es"}. Apply with --apply, or pipe to 'git apply'.\n`);
255
+ }
256
+ return 0;
257
+ }
258
+ function cmdRules(id, v, io) {
259
+ if (id) {
260
+ const r = RULES.find((x) => x.id.toLowerCase() === id.toLowerCase());
261
+ if (!r)
262
+ throw new UsageError(`unknown rule '${id}'`);
263
+ if (v.json)
264
+ io.stdout(`${JSON.stringify(r, null, 2)}\n`);
265
+ else {
266
+ const bench = r.benchmark
267
+ ? `Benchmark: ${r.benchmark.findings} findings in ${r.benchmark.repos} public repos, ${(r.benchmark.rate * 100).toFixed(1)}% false positives${r.demotedFrom ? ` (over the 5% budget: demoted from ${r.demotedFrom})` : ""}`
268
+ : "Benchmark: no findings in the corpus yet";
269
+ io.stdout(`${r.id} ${r.title}\n\nFamily: ${r.family} · Severity: ${r.severity} · ${r.determinism} · autofix: ${r.autofix} · ${r.status} · runs: ${r.availability}\n${bench}\n\nWhy: ${r.rationale}\nFix: ${r.remediation}\nSource: ${r.citation}\nDocs: https://threadctx.dev/rules/${r.id}\n`);
270
+ }
271
+ return 0;
272
+ }
273
+ if (v.json)
274
+ io.stdout(`${JSON.stringify(RULES, null, 2)}\n`);
275
+ else
276
+ for (const r of RULES)
277
+ io.stdout(`${r.id} ${r.severity.padEnd(7)} ${r.status.padEnd(4)} ${r.availability === "local" ? "" : `[${r.availability}] `}${r.title}\n`);
278
+ return 0;
279
+ }
280
+ function cmdTools(v, io) {
281
+ const now = io.now();
282
+ const rows = ADAPTERS.map((a) => ({ id: a.id, label: a.label, status: a.status, verified: a.verifiedAgainst.date, docs: a.verifiedAgainst.docsUrl, ageDays: Math.floor((now.getTime() - Date.parse(a.verifiedAgainst.date)) / 86_400_000), summary: a.summary, caveats: a.caveats }));
283
+ if (v.json)
284
+ io.stdout(`${JSON.stringify(rows, null, 2)}\n`);
285
+ else
286
+ for (const r of rows)
287
+ io.stdout(`${r.id.padEnd(12)} ${r.status.padEnd(5)} verified ${r.verified}${r.ageDays > 60 ? " (STALE)" : ""} ${r.summary}\n`);
288
+ return 0;
289
+ }
290
+ function cmdPackValidate(file, io) {
291
+ const abs = resolve(io.cwd, file);
292
+ if (!existsSync(abs))
293
+ throw new UsageError(`file not found: ${file}`);
294
+ const pack = parsePack(readFileSync(abs, "utf8"), file);
295
+ io.stdout(`${pack.pack}: ${pack.rules.length} rule${pack.rules.length === 1 ? "" : "s"} valid\n`);
296
+ for (const r of pack.rules)
297
+ io.stdout(` ${pack.pack}/${r.id} ${r.severity} ${r.title}\n`);
298
+ return 0;
299
+ }
300
+ // --- Upgrade line (spec §8.2): interactive only, once a day, never in CI ----------------
301
+ /** Set when the paid capability exists (Phase 2). Until then no upgrade line is printed. */
302
+ export const UPGRADE_URL = undefined;
303
+ function maybeUpgradeLine(result, io) {
304
+ if (!UPGRADE_URL || !io.isTTY || io.env.CI || io.env.THREADCTX_NO_UPSELL)
305
+ return;
306
+ const stateFile = join(io.env.THREADCTX_HOME ?? join(homedir(), ".threadctx"), "state.json");
307
+ let state = {};
308
+ try {
309
+ state = JSON.parse(readFileSync(stateFile, "utf8"));
310
+ }
311
+ catch {
312
+ /* first run */
313
+ }
314
+ const today = io.now().toISOString().slice(0, 10);
315
+ if (state.lastUpsell === today)
316
+ return;
317
+ const toolsUsed = result.tools.filter((t) => t.layers > 0).length;
318
+ const msg = toolsUsed >= 2
319
+ ? `${toolsUsed} agents read this repository. Grade every pull request and keep them aligned: ${UPGRADE_URL}`
320
+ : `Track this grade on every pull request: ${UPGRADE_URL}`;
321
+ io.stderr(`\n${msg}\n`);
322
+ try {
323
+ mkdirSync(dirname(stateFile), { recursive: true });
324
+ writeFileSync(stateFile, JSON.stringify({ ...state, lastUpsell: today }));
325
+ }
326
+ catch {
327
+ /* read-only home: skip */
328
+ }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AK;QAAE,OAAO;IACvC,MAAM,SAAS,GAAG,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC;IAClE,MAAM,GAAG,GAAG,SAAS,IAAI,CAAC;QACxB,CAAC,CAAC,GAAG,SAAS,iFAAiF,WAAW,EAAE;QAC5G,CAAC,CAAC,2CAA2C,WAAW,EAAE,CAAC;IAC7D,EAAE,CAAC,MAAM,CAAC,KAAK,GAAG,IAAI,CAAC,CAAC;IACxB,IAAI,CAAC;QACH,SAAS,CAAC,OAAO,CAAC,SAAS,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QACnD,aAAa,CAAC,SAAS,EAAE,IAAI,CAAC,SAAS,CAAC,EAAE,GAAG,KAAK,EAAE,UAAU,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;IAC5E,CAAC;IAAC,MAAM,CAAC;QACP,0BAA0B;IAC5B,CAAC;AACH,CAAC"}
package/dist/fix.d.ts ADDED
@@ -0,0 +1,21 @@
1
+ import type { FsView } from "@threadctx/core";
2
+ import type { Finding } from "@threadctx/rules";
3
+ export interface FixPlan {
4
+ /** New content per path. */
5
+ files: Map<string, {
6
+ before: string;
7
+ after: string;
8
+ }>;
9
+ applied: Finding[];
10
+ skipped: {
11
+ finding: Finding;
12
+ reason: string;
13
+ }[];
14
+ patch: string;
15
+ }
16
+ /**
17
+ * Apply line-based edits from safe fixes. Edits to the same file are applied bottom-up;
18
+ * an edit overlapping one already taken is skipped and reported, never merged.
19
+ * `endLine < startLine` means insert before `startLine`.
20
+ */
21
+ export declare function planFixes(fs: FsView, findings: Finding[], kinds?: ("safe" | "suggested")[]): FixPlan;
package/dist/fix.js ADDED
@@ -0,0 +1,58 @@
1
+ import { createTwoFilesPatch } from "diff";
2
+ /**
3
+ * Apply line-based edits from safe fixes. Edits to the same file are applied bottom-up;
4
+ * an edit overlapping one already taken is skipped and reported, never merged.
5
+ * `endLine < startLine` means insert before `startLine`.
6
+ */
7
+ export function planFixes(fs, findings, kinds = ["safe"]) {
8
+ const candidates = findings.filter((f) => !f.suppressed && f.fix && kinds.includes(f.fix.kind) && f.fix.edits.length > 0);
9
+ const byPath = new Map();
10
+ const skipped = [];
11
+ for (const finding of candidates) {
12
+ for (const edit of finding.fix.edits) {
13
+ const list = byPath.get(edit.path) ?? [];
14
+ list.push({ finding, edit });
15
+ byPath.set(edit.path, list);
16
+ }
17
+ }
18
+ const files = new Map();
19
+ const applied = new Set();
20
+ for (const [path, edits] of [...byPath.entries()].sort(([a], [b]) => (a < b ? -1 : 1))) {
21
+ const before = fs.readFile(path);
22
+ if (before === undefined) {
23
+ for (const e of edits)
24
+ skipped.push({ finding: e.finding, reason: `${path} could not be read` });
25
+ continue;
26
+ }
27
+ const eol = before.includes("\r\n") ? "\r\n" : "\n";
28
+ const bom = before.startsWith("") ? "" : "";
29
+ const lines = before.replace(/^/, "").split(/\r?\n/);
30
+ const taken = [];
31
+ const sorted = [...edits].sort((a, b) => b.edit.startLine - a.edit.startLine || b.edit.endLine - a.edit.endLine);
32
+ for (const { finding, edit } of sorted) {
33
+ const insert = edit.endLine < edit.startLine;
34
+ const range = insert ? [edit.startLine - 0.5, edit.startLine - 0.5] : [edit.startLine, edit.endLine];
35
+ if (edit.startLine < 1 || (!insert && edit.endLine > lines.length)) {
36
+ skipped.push({ finding, reason: "edit is outside the file" });
37
+ continue;
38
+ }
39
+ if (taken.some(([s, e]) => range[0] <= e && range[1] >= s)) {
40
+ skipped.push({ finding, reason: "overlaps another fix; run fix again after applying" });
41
+ continue;
42
+ }
43
+ taken.push(range);
44
+ const replacement = edit.replacement.replace(/\r?\n$/, "").split(/\r?\n/);
45
+ if (insert)
46
+ lines.splice(edit.startLine - 1, 0, ...replacement);
47
+ else
48
+ lines.splice(edit.startLine - 1, edit.endLine - edit.startLine + 1, ...replacement);
49
+ applied.add(finding);
50
+ }
51
+ const after = bom + lines.join(eol);
52
+ if (after !== before)
53
+ files.set(path, { before, after });
54
+ }
55
+ const patch = [...files.entries()].map(([p, { before, after }]) => createTwoFilesPatch(`a/${p}`, `b/${p}`, before, after, "", "", { context: 3 })).join("");
56
+ return { files, applied: [...applied], skipped, patch };
57
+ }
58
+ //# sourceMappingURL=fix.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fix.js","sourceRoot":"","sources":["../src/fix.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,MAAM,CAAC;AAY3C;;;;GAIG;AACH,MAAM,UAAU,SAAS,CAAC,EAAU,EAAE,QAAmB,EAAE,QAAkC,CAAC,MAAM,CAAC;IACnG,MAAM,UAAU,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,UAAU,IAAI,CAAC,CAAC,GAAG,IAAI,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IAC1H,MAAM,MAAM,GAAG,IAAI,GAAG,EAAkD,CAAC;IACzE,MAAM,OAAO,GAAuB,EAAE,CAAC;IACvC,KAAK,MAAM,OAAO,IAAI,UAAU,EAAE,CAAC;QACjC,KAAK,MAAM,IAAI,IAAI,OAAO,CAAC,GAAI,CAAC,KAAK,EAAE,CAAC;YACtC,MAAM,IAAI,GAAG,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC;YACzC,IAAI,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;YAC7B,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;QAC9B,CAAC;IACH,CAAC;IACD,MAAM,KAAK,GAAG,IAAI,GAAG,EAA6C,CAAC;IACnE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M,CAAC,IAAI,CAAC,SAAS,GAAG,CAAC,EAAE,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,SAAS,GAAG,CAAC,EAAE,GAAG,WAAW,CAAC,CAAC;YACzF,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;QACvB,CAAC;QACD,MAAM,KAAK,GAAG,GAAG,GAAG,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QACpC,IAAI,KAAK,KAAK,MAAM;YAAE,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,CAAC;IAC3D,CAAC;IACD,MAAM,KAAK,GAAG,CAAC,GAAG,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,EAAE,EAAE,CAAC,mBAAmB,CAAC,KAAK,CAAC,EAAE,EAAE,KAAK,CAAC,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,OAAO,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IAC5J,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,GAAG,OAAO,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAC1D,CAAC"}
package/dist/git.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ import type { HistoryProvider } from "@threadctx/rules";
2
+ export declare function gitRoot(dir: string): string | undefined;
3
+ /** Git history for CTX-D006, or undefined in shallow clones and non-git directories. */
4
+ export declare function gitHistory(root: string): HistoryProvider | undefined;
package/dist/git.js ADDED
@@ -0,0 +1,28 @@
1
+ import { execFileSync } from "node:child_process";
2
+ function git(root, args) {
3
+ try {
4
+ return execFileSync("git", args, { cwd: root, stdio: ["ignore", "pipe", "ignore"], timeout: 10_000 }).toString().trim();
5
+ }
6
+ catch {
7
+ return undefined;
8
+ }
9
+ }
10
+ export function gitRoot(dir) {
11
+ return git(dir, ["rev-parse", "--show-toplevel"]);
12
+ }
13
+ /** Git history for CTX-D006, or undefined in shallow clones and non-git directories. */
14
+ export function gitHistory(root) {
15
+ if (git(root, ["rev-parse", "--is-shallow-repository"]) !== "false")
16
+ return undefined;
17
+ return {
18
+ lastCommitTime(path) {
19
+ const out = git(root, ["log", "-1", "--format=%ct", "--", path]);
20
+ return out ? Number(out) : undefined;
21
+ },
22
+ commitsSince(paths, since) {
23
+ const out = git(root, ["rev-list", "--count", `--since=@${since + 1}`, "HEAD", "--", ...paths]);
24
+ return out ? Number(out) : undefined;
25
+ },
26
+ };
27
+ }
28
+ //# sourceMappingURL=git.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"git.js","sourceRoot":"","sources":["../src/git.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAGlD,SAAS,GAAG,CAAC,IAAY,EAAE,IAAc;IACvC,IAAI,CAAC;QACH,OAAO,YAAY,CAAC,KAAK,EAAE,IAAI,EAAE,EAAE,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,CAAC;IAC1H,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC;AAED,MAAM,UAAU,OAAO,CAAC,GAAW;IACjC,OAAO,GAAG,CAAC,GAAG,EAAE,CAAC,WAAW,EAAE,iBAAiB,CAAC,CAAC,CAAC;AACpD,CAAC;AAED,wFAAwF;AACxF,MAAM,UAAU,UAAU,CAAC,IAAY;IACrC,IAAI,GAAG,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,yBAAyB,CAAC,CAAC,KAAK,OAAO;QAAE,OAAO,SAAS,CAAC;IACtF,OAAO;QACL,cAAc,CAAC,IAAI;YACjB,MAAM,GAAG,GAAG,GAAG,CAAC,IAAI,EAAE,CAAC,KAAK,EAAE,IAAI,EAAE,cAAc,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC;YACjE,OAAO,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QACvC,CAAC;QACD,YAAY,CAAC,KAAK,EAAE,KAAK;YACvB,MAAM,GAAG,GAAG,GAAG,CAAC,IAAI,EAAE,CAAC,UAAU,EAAE,SAAS,EAAE,YAAY,KAAK,GAAG,CAAC,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,KAAK,CAAC,CAAC,CAAC;YAChG,OAAO,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QACvC,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,3 @@
1
+ export { main, type Io } from "./cli.js";
2
+ export { planFixes, type FixPlan } from "./fix.js";
3
+ export { fetchRemoteRepo, githubToken, type RemoteRepo } from "./remote.js";
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { main } from "./cli.js";
2
+ export { planFixes } from "./fix.js";
3
+ export { fetchRemoteRepo, githubToken } from "./remote.js";
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAW,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,SAAS,EAAgB,MAAM,UAAU,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE,WAAW,EAAmB,MAAM,aAAa,CAAC"}
@@ -0,0 +1,13 @@
1
+ import type { FsView } from "@threadctx/core";
2
+ export interface RemoteRepo {
3
+ fullName: string;
4
+ sha: string;
5
+ view: FsView;
6
+ truncated: boolean;
7
+ fetched: number;
8
+ }
9
+ export declare function githubToken(env: NodeJS.ProcessEnv): string | undefined;
10
+ export declare function fetchRemoteRepo(fullName: string, opts?: {
11
+ ref?: string;
12
+ token?: string;
13
+ }): Promise<RemoteRepo>;
package/dist/remote.js ADDED
@@ -0,0 +1,118 @@
1
+ // Read-only view of a GitHub repository without cloning: the full file tree plus the contents
2
+ // of context files, manifests and anything they import. Used by `scan --org` and the
3
+ // benchmark corpus. Network access happens only here, never in the engine.
4
+ import { execFileSync } from "node:child_process";
5
+ import { posix } from "node:path";
6
+ import { buildCatalog, resolveImport } from "@threadctx/adapters";
7
+ const WANT = [
8
+ /(^|\/)AGENTS(\.override)?\.md$/, /(^|\/)(\.claude\/)?CLAUDE(\.local)?\.md$/, /(^|\/)\.claude\//, /^\.cursor\//, /^\.cursorrules$/,
9
+ /^\.github\/(copilot-instructions\.md|instructions\/.+\.instructions\.md|CODEOWNERS)$/, /(^|\/)GEMINI\.md$/, /^\.gemini\/settings\.json$/,
10
+ /^\.mcp\.json$/, /^\.vscode\/mcp\.json$/, /^\.codex\/config\.toml$/, /^\.threadctx\//,
11
+ /(^|\/)package\.json$/, /^pyproject\.toml$/, /^requirements[^/]*\.txt$/, /(^|\/)(GNUmakefile|[Mm]akefile(\.[\w.-]+)?|\.?justfile|[^/]+\.(mk|make|just))$/,
12
+ /^\.(nvmrc|node-version|python-version|tool-versions|gitignore)$/, /^(docs\/)?CODEOWNERS$/, /^readme(\.md|\.markdown)?$/i,
13
+ ];
14
+ const SKIP = /(^|\/)(node_modules|vendor|\.git|dist|build|third_party|fixtures?|testdata|__fixtures__|examples?)\//;
15
+ const MAX_BLOB = 1_000_000;
16
+ const MAX_PACKAGE_JSONS = 300;
17
+ export function githubToken(env) {
18
+ if (env.GH_TOKEN || env.GITHUB_TOKEN)
19
+ return env.GH_TOKEN ?? env.GITHUB_TOKEN;
20
+ try {
21
+ return execFileSync("gh", ["auth", "token"], { stdio: ["ignore", "pipe", "ignore"] }).toString().trim() || undefined;
22
+ }
23
+ catch {
24
+ return undefined;
25
+ }
26
+ }
27
+ async function api(path, token) {
28
+ const res = await fetch(`https://api.github.com${path}`, {
29
+ headers: { Accept: "application/vnd.github+json", "User-Agent": "threadctx-scanner (+https://threadctx.dev)", ...(token ? { Authorization: `Bearer ${token}` } : {}) },
30
+ });
31
+ if (!res.ok)
32
+ throw new Error(`GitHub API ${res.status} for ${path}: ${(await res.text()).slice(0, 200)}`);
33
+ return (await res.json());
34
+ }
35
+ async function pool(items, limit, fn) {
36
+ const out = new Array(items.length);
37
+ let i = 0;
38
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
39
+ while (i < items.length) {
40
+ const idx = i++;
41
+ out[idx] = await fn(items[idx]);
42
+ }
43
+ }));
44
+ return out;
45
+ }
46
+ export async function fetchRemoteRepo(fullName, opts = {}) {
47
+ const token = opts.token;
48
+ const ref = opts.ref ?? (await api(`/repos/${fullName}`, token)).default_branch;
49
+ const sha = /^[0-9a-f]{40}$/.test(ref) ? ref : (await api(`/repos/${fullName}/commits/${encodeURIComponent(ref)}`, token)).sha;
50
+ const tree = await api(`/repos/${fullName}/git/trees/${sha}?recursive=1`, token);
51
+ const blobs = tree.tree.filter((t) => t.type === "blob" && !t.path.split("/").includes("node_modules"));
52
+ const submodules = tree.tree.filter((t) => t.type === "commit").map((t) => t.path);
53
+ const files = blobs.map((b) => b.path).sort();
54
+ const modes = new Map(blobs.map((b) => [b.path, b]));
55
+ const content = new Map();
56
+ const fetchPaths = async (paths) => {
57
+ const todo = paths.filter((p) => !content.has(p) && (modes.get(p)?.size ?? 0) <= MAX_BLOB);
58
+ await pool(todo, 8, async (p) => {
59
+ const res = await fetch(`https://raw.githubusercontent.com/${fullName}/${sha}/${p.split("/").map(encodeURIComponent).join("/")}`, {
60
+ headers: token ? { Authorization: `token ${token}` } : {},
61
+ });
62
+ if (res.ok)
63
+ content.set(p, await res.text());
64
+ });
65
+ };
66
+ let packageJsons = 0;
67
+ const first = files.filter((f) => {
68
+ if (!WANT.some((re) => re.test(f)))
69
+ return false;
70
+ if (f.endsWith("package.json")) {
71
+ if (SKIP.test(f) || ++packageJsons > MAX_PACKAGE_JSONS)
72
+ return false;
73
+ }
74
+ return true;
75
+ });
76
+ await fetchPaths(first);
77
+ const fileSet = new Set(files);
78
+ const dirs = new Set([""]);
79
+ for (const f of [...files, ...submodules.map((m) => `${m}/.`)]) {
80
+ const parts = f.split("/");
81
+ for (let i = 1; i < parts.length; i++)
82
+ dirs.add(parts.slice(0, i).join("/"));
83
+ }
84
+ const view = {
85
+ root: `github:${fullName}@${sha.slice(0, 12)}`,
86
+ files,
87
+ dirs,
88
+ readFile: (p) => {
89
+ const rel = posix.normalize(p).replace(/^\.\//, "");
90
+ if (modes.get(rel)?.mode !== "120000")
91
+ return content.get(rel);
92
+ // Symlinks: raw content is the link target; read the target instead.
93
+ const target = posix.normalize(posix.join(posix.dirname(rel), content.get(rel) ?? ""));
94
+ return content.get(target);
95
+ },
96
+ exists: (p) => {
97
+ const rel = posix.normalize(p).replace(/^\.\//, "").replace(/\/$/, "");
98
+ return fileSet.has(rel) || dirs.has(rel);
99
+ },
100
+ symlinkTarget: (p) => (modes.get(p)?.mode === "120000" ? posix.normalize(posix.join(posix.dirname(p), content.get(p) ?? "")) : undefined),
101
+ };
102
+ // Imported files are context too: follow imports a few rounds.
103
+ for (let round = 0; round < 3; round++) {
104
+ const missing = new Set();
105
+ for (const a of buildCatalog(view).artifacts) {
106
+ for (const imp of a.imports) {
107
+ const r = resolveImport(a.artifact.path, imp.path);
108
+ if (r && fileSet.has(r) && !content.has(r))
109
+ missing.add(r);
110
+ }
111
+ }
112
+ if (!missing.size)
113
+ break;
114
+ await fetchPaths([...missing]);
115
+ }
116
+ return { fullName, sha, view, truncated: tree.truncated, fetched: content.size };
117
+ }
118
+ //# sourceMappingURL=remote.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"remote.js","sourceRoot":"","sources":["../src/remote.ts"],"names":[],"mappings":"AAAA,8FAA8F;AAC9F,qFAAqF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AC;YAC7D,CAAC;QACH,CAAC;QACD,IAAI,CAAC,OAAO,CAAC,IAAI;YAAE,MAAM;QACzB,MAAM,UAAU,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;IACjC,CAAC;IACD,OAAO,EAAE,QAAQ,EAAE,GAAG,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,CAAC,SAAS,EAAE,OAAO,EAAE,OAAO,CAAC,IAAI,EAAE,CAAC;AACnF,CAAC"}
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "threadctx",
3
+ "version": "0.1.0",
4
+ "license": "Apache-2.0",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "files": [
9
+ "dist",
10
+ "!dist/**/*.test.*",
11
+ "README.md",
12
+ "LICENSE",
13
+ "NOTICE"
14
+ ],
15
+ "engines": {
16
+ "node": ">=20"
17
+ },
18
+ "dependencies": {
19
+ "diff": "^9.0.0",
20
+ "@threadctx/core": "0.1.0",
21
+ "@threadctx/rules": "0.1.0",
22
+ "@threadctx/discovery": "0.1.0",
23
+ "@threadctx/adapters": "0.1.0",
24
+ "@threadctx/report": "0.1.0"
25
+ },
26
+ "bin": {
27
+ "threadctx": "dist/bin.js",
28
+ "ctx": "dist/bin.js"
29
+ },
30
+ "description": "Scan, fix and explain what every AI coding agent is told.",
31
+ "homepage": "https://threadctx.dev",
32
+ "keywords": [
33
+ "agents",
34
+ "ai",
35
+ "claude-code",
36
+ "cursor",
37
+ "copilot",
38
+ "gemini",
39
+ "agents-md",
40
+ "context",
41
+ "lint",
42
+ "mcp",
43
+ "sarif"
44
+ ],
45
+ "author": "threadctx",
46
+ "publishConfig": {
47
+ "access": "public"
48
+ },
49
+ "scripts": {
50
+ "build": "tsc -b"
51
+ }
52
+ }