sdtk-code-kit 0.2.0 → 0.2.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.
Files changed (75) hide show
  1. package/README.md +201 -201
  2. package/assets/manifest/toolkit-bundle.manifest.json +147 -147
  3. package/assets/manifest/toolkit-bundle.sha256.txt +28 -28
  4. package/assets/toolkit/toolkit/AGENTS.md +219 -219
  5. package/assets/toolkit/toolkit/install.ps1 +156 -156
  6. package/assets/toolkit/toolkit/scripts/install-claude-skills.ps1 +78 -78
  7. package/assets/toolkit/toolkit/scripts/install-codex-skills.ps1 +150 -150
  8. package/assets/toolkit/toolkit/scripts/uninstall-claude-skills.ps1 +62 -62
  9. package/assets/toolkit/toolkit/scripts/uninstall-codex-skills.ps1 +82 -82
  10. package/assets/toolkit/toolkit/sdtk-spec.config.json +6 -6
  11. package/assets/toolkit/toolkit/sdtk-spec.config.profiles.example.json +12 -12
  12. package/assets/toolkit/toolkit/skills/code-brainstorm/SKILL.md +55 -55
  13. package/assets/toolkit/toolkit/skills/code-debug/SKILL.md +296 -296
  14. package/assets/toolkit/toolkit/skills/code-debug/references/root-cause-tracing.md +68 -68
  15. package/assets/toolkit/toolkit/skills/code-discover/SKILL.md +54 -54
  16. package/assets/toolkit/toolkit/skills/code-execute/SKILL.md +74 -74
  17. package/assets/toolkit/toolkit/skills/code-finish/SKILL.md +205 -205
  18. package/assets/toolkit/toolkit/skills/code-parallel/SKILL.md +64 -64
  19. package/assets/toolkit/toolkit/skills/code-parallel/references/code-quality-reviewer-prompt.md +26 -26
  20. package/assets/toolkit/toolkit/skills/code-parallel/references/implementer-prompt.md +113 -113
  21. package/assets/toolkit/toolkit/skills/code-parallel/references/spec-reviewer-prompt.md +61 -61
  22. package/assets/toolkit/toolkit/skills/code-plan/SKILL.md +85 -85
  23. package/assets/toolkit/toolkit/skills/code-review/SKILL.md +79 -79
  24. package/assets/toolkit/toolkit/skills/code-review/references/checklist.md +125 -125
  25. package/assets/toolkit/toolkit/skills/code-review/references/code-reviewer.md +146 -146
  26. package/assets/toolkit/toolkit/skills/code-ship/SKILL.md +52 -52
  27. package/assets/toolkit/toolkit/skills/code-tdd/SKILL.md +378 -378
  28. package/assets/toolkit/toolkit/skills/code-tdd/references/testing-anti-patterns.md +299 -299
  29. package/assets/toolkit/toolkit/skills/code-verify/SKILL.md +144 -144
  30. package/assets/toolkit/toolkit/skills/code-worktree/SKILL.md +228 -228
  31. package/assets/toolkit/toolkit/templates/CODE_WORKFLOW_TEMPLATE.md +140 -140
  32. package/bin/sdtk-code.js +14 -14
  33. package/package.json +44 -44
  34. package/src/commands/build.js +53 -53
  35. package/src/commands/doctor.js +51 -51
  36. package/src/commands/generate.js +11 -11
  37. package/src/commands/guardrails.js +215 -123
  38. package/src/commands/help.js +244 -244
  39. package/src/commands/init.js +98 -98
  40. package/src/commands/plan.js +53 -53
  41. package/src/commands/readiness.js +77 -77
  42. package/src/commands/resume.js +61 -61
  43. package/src/commands/runtime.js +224 -224
  44. package/src/commands/ship.js +59 -59
  45. package/src/commands/sleep.js +132 -0
  46. package/src/commands/start.js +89 -89
  47. package/src/commands/status.js +77 -77
  48. package/src/commands/update.js +11 -11
  49. package/src/commands/verify.js +71 -71
  50. package/src/index.js +108 -104
  51. package/src/lib/args.js +107 -107
  52. package/src/lib/errors.js +41 -41
  53. package/src/lib/powershell.js +65 -65
  54. package/src/lib/project-target-guard.js +53 -53
  55. package/src/lib/scope.js +72 -72
  56. package/src/lib/ship-readiness.js +281 -281
  57. package/src/lib/sleep-plan.js +175 -0
  58. package/src/lib/sleep-report.js +229 -0
  59. package/src/lib/toolkit-payload.js +72 -72
  60. package/src/lib/trust-events.js +166 -166
  61. package/src/lib/trust-file-scope.js +154 -154
  62. package/src/lib/trust-policy.js +212 -212
  63. package/src/lib/trust-redact.js +35 -35
  64. package/src/lib/trust-trace.js +179 -179
  65. package/src/lib/update.js +344 -344
  66. package/src/lib/workflow-artifact.js +503 -503
  67. package/src/lib/workflow-build.js +127 -127
  68. package/src/lib/workflow-doctor.js +83 -83
  69. package/src/lib/workflow-handoff.js +1029 -1029
  70. package/src/lib/workflow-intake.js +101 -101
  71. package/src/lib/workflow-plan.js +193 -193
  72. package/src/lib/workflow-review-packet.js +650 -650
  73. package/src/lib/workflow-ship.js +213 -213
  74. package/src/lib/workflow-state.js +438 -438
  75. package/src/lib/workflow-verify.js +393 -393
@@ -1,166 +1,166 @@
1
- "use strict";
2
-
3
- const crypto = require("crypto");
4
- const fs = require("fs");
5
- const path = require("path");
6
- const { redact } = require("./trust-redact");
7
-
8
- const locks = new Map();
9
- const MAX_COMMAND_LENGTH = 2000;
10
-
11
- function generateId(prefix) {
12
- const ts = Date.now().toString(36);
13
- const rand = crypto.randomUUID().replace(/-/g, "").slice(0, 12);
14
- return `${prefix}_${ts}_${rand}`;
15
- }
16
-
17
- function fingerprintId(prefix, content) {
18
- const hash = crypto.createHash("sha256").update(String(content)).digest("hex");
19
- return `${prefix}_${hash.slice(0, 16)}`;
20
- }
21
-
22
- function eventsDir(projectPath) {
23
- return path.join(path.resolve(projectPath || "."), ".sdtk", "trust", "events");
24
- }
25
-
26
- function eventsFile(projectPath, date) {
27
- const day = typeof date === "string" ? date : new Date(date || Date.now()).toISOString().slice(0, 10);
28
- return path.join(eventsDir(projectPath), `${day}.jsonl`);
29
- }
30
-
31
- function nullableString(value) {
32
- return typeof value === "string" && value.length > 0 ? value : null;
33
- }
34
-
35
- function normalizeStatus(value) {
36
- return typeof value === "string" && value.length > 0 ? value : "info";
37
- }
38
-
39
- function inferEventType(raw) {
40
- if (!raw || typeof raw !== "object") {
41
- return null;
42
- }
43
- if (typeof raw.event_type === "string" && raw.event_type.length > 0) {
44
- return raw.event_type;
45
- }
46
- const hookType = typeof raw.hook_type === "string" ? raw.hook_type : "";
47
- const toolName = typeof raw.tool_name === "string" ? raw.tool_name : "";
48
- if (hookType === "post_tool_failure") {
49
- return "command_failure";
50
- }
51
- if (hookType === "post_tool" || hookType === "task_completed") {
52
- return "post_command";
53
- }
54
- if (hookType === "pre_tool" || /(?:bash|shell|exec|run)/i.test(toolName)) {
55
- return "pre_command";
56
- }
57
- return null;
58
- }
59
-
60
- function normalizeFiles(value) {
61
- if (!Array.isArray(value)) {
62
- return [];
63
- }
64
- return value.filter((entry) => typeof entry === "string").map((entry) => redact(entry));
65
- }
66
-
67
- function normalizeCommand(value) {
68
- if (typeof value !== "string") {
69
- return { command: null, truncated: false };
70
- }
71
- const redacted = redact(value);
72
- if (redacted.length > MAX_COMMAND_LENGTH) {
73
- return { command: redacted.slice(0, MAX_COMMAND_LENGTH), truncated: true };
74
- }
75
- return { command: redacted, truncated: false };
76
- }
77
-
78
- function buildEvent(raw) {
79
- const source = raw && typeof raw === "object" ? raw : {};
80
- const timestamp = typeof source.timestamp === "string" && source.timestamp.length > 0
81
- ? source.timestamp
82
- : new Date().toISOString();
83
- const { command, truncated } = normalizeCommand(source.command);
84
- const sessionId = nullableString(source.session_id);
85
- const toolkit = nullableString(source.toolkit);
86
- const eventType = inferEventType(source);
87
- const canonical = [sessionId || "", toolkit || "", eventType || "", command || "", timestamp].join("|");
88
-
89
- return {
90
- event_id: fingerprintId("evt", canonical),
91
- session_id: sessionId,
92
- toolkit,
93
- phase: nullableString(source.phase),
94
- event_type: eventType,
95
- command,
96
- status: normalizeStatus(source.status),
97
- cwd: typeof source.cwd === "string" ? redact(source.cwd) : null,
98
- files: normalizeFiles(source.files),
99
- timestamp,
100
- redaction: "applied",
101
- truncated,
102
- };
103
- }
104
-
105
- function readExistingEventIds(file) {
106
- if (!fs.existsSync(file)) {
107
- return new Set();
108
- }
109
- const ids = new Set();
110
- const content = fs.readFileSync(file, "utf8");
111
- for (const line of content.split(/\r?\n/)) {
112
- if (!line.trim()) {
113
- continue;
114
- }
115
- try {
116
- const event = JSON.parse(line);
117
- if (event && typeof event.event_id === "string") {
118
- ids.add(event.event_id);
119
- }
120
- } catch (_error) {
121
- // Append-only logs should remain writable even if one old line is malformed.
122
- }
123
- }
124
- return ids;
125
- }
126
-
127
- /**
128
- * Append a redacted trust event.
129
- *
130
- * The caller must provide a stable timestamp when retry-idempotency is desired.
131
- * If timestamp is omitted, each call receives the current ISO timestamp and is
132
- * treated as a distinct observation.
133
- */
134
- function appendEvent(projectPath, raw) {
135
- const event = buildEvent(raw);
136
- const file = eventsFile(projectPath, event.timestamp.slice(0, 10));
137
- fs.mkdirSync(path.dirname(file), { recursive: true });
138
-
139
- const existingIds = readExistingEventIds(file);
140
- if (existingIds.has(event.event_id)) {
141
- return { event, written: false };
142
- }
143
-
144
- fs.appendFileSync(file, `${JSON.stringify(event)}\n`, "utf8");
145
- return { event, written: true };
146
- }
147
-
148
- function withKeyedLock(key, fn) {
149
- const prev = locks.get(key) || Promise.resolve();
150
- const next = prev.then(fn, fn);
151
- const cleanup = next.then(
152
- () => {},
153
- () => {},
154
- );
155
- locks.set(key, cleanup);
156
- cleanup.then(() => {
157
- if (locks.get(key) === cleanup) {
158
- locks.delete(key);
159
- }
160
- });
161
- return next;
162
- }
163
-
164
- void withKeyedLock;
165
-
166
- module.exports = { generateId, fingerprintId, buildEvent, appendEvent, eventsDir, eventsFile };
1
+ "use strict";
2
+
3
+ const crypto = require("crypto");
4
+ const fs = require("fs");
5
+ const path = require("path");
6
+ const { redact } = require("./trust-redact");
7
+
8
+ const locks = new Map();
9
+ const MAX_COMMAND_LENGTH = 2000;
10
+
11
+ function generateId(prefix) {
12
+ const ts = Date.now().toString(36);
13
+ const rand = crypto.randomUUID().replace(/-/g, "").slice(0, 12);
14
+ return `${prefix}_${ts}_${rand}`;
15
+ }
16
+
17
+ function fingerprintId(prefix, content) {
18
+ const hash = crypto.createHash("sha256").update(String(content)).digest("hex");
19
+ return `${prefix}_${hash.slice(0, 16)}`;
20
+ }
21
+
22
+ function eventsDir(projectPath) {
23
+ return path.join(path.resolve(projectPath || "."), ".sdtk", "trust", "events");
24
+ }
25
+
26
+ function eventsFile(projectPath, date) {
27
+ const day = typeof date === "string" ? date : new Date(date || Date.now()).toISOString().slice(0, 10);
28
+ return path.join(eventsDir(projectPath), `${day}.jsonl`);
29
+ }
30
+
31
+ function nullableString(value) {
32
+ return typeof value === "string" && value.length > 0 ? value : null;
33
+ }
34
+
35
+ function normalizeStatus(value) {
36
+ return typeof value === "string" && value.length > 0 ? value : "info";
37
+ }
38
+
39
+ function inferEventType(raw) {
40
+ if (!raw || typeof raw !== "object") {
41
+ return null;
42
+ }
43
+ if (typeof raw.event_type === "string" && raw.event_type.length > 0) {
44
+ return raw.event_type;
45
+ }
46
+ const hookType = typeof raw.hook_type === "string" ? raw.hook_type : "";
47
+ const toolName = typeof raw.tool_name === "string" ? raw.tool_name : "";
48
+ if (hookType === "post_tool_failure") {
49
+ return "command_failure";
50
+ }
51
+ if (hookType === "post_tool" || hookType === "task_completed") {
52
+ return "post_command";
53
+ }
54
+ if (hookType === "pre_tool" || /(?:bash|shell|exec|run)/i.test(toolName)) {
55
+ return "pre_command";
56
+ }
57
+ return null;
58
+ }
59
+
60
+ function normalizeFiles(value) {
61
+ if (!Array.isArray(value)) {
62
+ return [];
63
+ }
64
+ return value.filter((entry) => typeof entry === "string").map((entry) => redact(entry));
65
+ }
66
+
67
+ function normalizeCommand(value) {
68
+ if (typeof value !== "string") {
69
+ return { command: null, truncated: false };
70
+ }
71
+ const redacted = redact(value);
72
+ if (redacted.length > MAX_COMMAND_LENGTH) {
73
+ return { command: redacted.slice(0, MAX_COMMAND_LENGTH), truncated: true };
74
+ }
75
+ return { command: redacted, truncated: false };
76
+ }
77
+
78
+ function buildEvent(raw) {
79
+ const source = raw && typeof raw === "object" ? raw : {};
80
+ const timestamp = typeof source.timestamp === "string" && source.timestamp.length > 0
81
+ ? source.timestamp
82
+ : new Date().toISOString();
83
+ const { command, truncated } = normalizeCommand(source.command);
84
+ const sessionId = nullableString(source.session_id);
85
+ const toolkit = nullableString(source.toolkit);
86
+ const eventType = inferEventType(source);
87
+ const canonical = [sessionId || "", toolkit || "", eventType || "", command || "", timestamp].join("|");
88
+
89
+ return {
90
+ event_id: fingerprintId("evt", canonical),
91
+ session_id: sessionId,
92
+ toolkit,
93
+ phase: nullableString(source.phase),
94
+ event_type: eventType,
95
+ command,
96
+ status: normalizeStatus(source.status),
97
+ cwd: typeof source.cwd === "string" ? redact(source.cwd) : null,
98
+ files: normalizeFiles(source.files),
99
+ timestamp,
100
+ redaction: "applied",
101
+ truncated,
102
+ };
103
+ }
104
+
105
+ function readExistingEventIds(file) {
106
+ if (!fs.existsSync(file)) {
107
+ return new Set();
108
+ }
109
+ const ids = new Set();
110
+ const content = fs.readFileSync(file, "utf8");
111
+ for (const line of content.split(/\r?\n/)) {
112
+ if (!line.trim()) {
113
+ continue;
114
+ }
115
+ try {
116
+ const event = JSON.parse(line);
117
+ if (event && typeof event.event_id === "string") {
118
+ ids.add(event.event_id);
119
+ }
120
+ } catch (_error) {
121
+ // Append-only logs should remain writable even if one old line is malformed.
122
+ }
123
+ }
124
+ return ids;
125
+ }
126
+
127
+ /**
128
+ * Append a redacted trust event.
129
+ *
130
+ * The caller must provide a stable timestamp when retry-idempotency is desired.
131
+ * If timestamp is omitted, each call receives the current ISO timestamp and is
132
+ * treated as a distinct observation.
133
+ */
134
+ function appendEvent(projectPath, raw) {
135
+ const event = buildEvent(raw);
136
+ const file = eventsFile(projectPath, event.timestamp.slice(0, 10));
137
+ fs.mkdirSync(path.dirname(file), { recursive: true });
138
+
139
+ const existingIds = readExistingEventIds(file);
140
+ if (existingIds.has(event.event_id)) {
141
+ return { event, written: false };
142
+ }
143
+
144
+ fs.appendFileSync(file, `${JSON.stringify(event)}\n`, "utf8");
145
+ return { event, written: true };
146
+ }
147
+
148
+ function withKeyedLock(key, fn) {
149
+ const prev = locks.get(key) || Promise.resolve();
150
+ const next = prev.then(fn, fn);
151
+ const cleanup = next.then(
152
+ () => {},
153
+ () => {},
154
+ );
155
+ locks.set(key, cleanup);
156
+ cleanup.then(() => {
157
+ if (locks.get(key) === cleanup) {
158
+ locks.delete(key);
159
+ }
160
+ });
161
+ return next;
162
+ }
163
+
164
+ void withKeyedLock;
165
+
166
+ module.exports = { generateId, fingerprintId, buildEvent, appendEvent, eventsDir, eventsFile };
@@ -1,154 +1,154 @@
1
- "use strict";
2
-
3
- const childProcess = require("child_process");
4
- const fs = require("fs");
5
- const path = require("path");
6
-
7
- function normalizePatterns(value) {
8
- if (!Array.isArray(value)) {
9
- return [];
10
- }
11
- return value.filter((entry) => typeof entry === "string" && entry.length > 0);
12
- }
13
-
14
- function loadScopes(projectPath, featureKey, opts = {}) {
15
- const optAllowed = normalizePatterns(opts.allowed);
16
- const optBlocked = normalizePatterns(opts.blocked);
17
- if (Array.isArray(opts.allowed) || Array.isArray(opts.blocked)) {
18
- return {
19
- allowed: optAllowed,
20
- blocked: optBlocked,
21
- declared: optAllowed.length > 0 || optBlocked.length > 0,
22
- source: "opts",
23
- };
24
- }
25
-
26
- const handoffPath = path.join(
27
- path.resolve(projectPath || "."),
28
- "docs",
29
- "dev",
30
- `CODE_HANDOFF_${featureKey}.json`,
31
- );
32
-
33
- try {
34
- const payload = JSON.parse(fs.readFileSync(handoffPath, "utf8"));
35
- const allowed = normalizePatterns(payload.allowed_file_scopes);
36
- const blocked = normalizePatterns(payload.blocked_file_scopes);
37
- if (Array.isArray(payload.allowed_file_scopes) || Array.isArray(payload.blocked_file_scopes)) {
38
- return {
39
- allowed,
40
- blocked,
41
- declared: allowed.length > 0 || blocked.length > 0,
42
- source: "handoff",
43
- };
44
- }
45
- } catch (_error) {
46
- // Missing or invalid optional forward-compat handoff fields fall back cleanly.
47
- }
48
-
49
- return { allowed: [], blocked: [], declared: false, source: "none" };
50
- }
51
-
52
- function escapeRegexChar(char) {
53
- return /[\\^$+?.()|[\]{}]/.test(char) ? `\\${char}` : char;
54
- }
55
-
56
- function globToRegex(pattern) {
57
- let source = "";
58
- for (let index = 0; index < pattern.length; index += 1) {
59
- const char = pattern[index];
60
- const next = pattern[index + 1];
61
- if (char === "*") {
62
- if (next === "*") {
63
- source += ".*";
64
- index += 1;
65
- } else {
66
- source += "[^/]*";
67
- }
68
- } else if (char === "?") {
69
- source += "[^/]";
70
- } else {
71
- source += escapeRegexChar(char);
72
- }
73
- }
74
- return new RegExp(`^${source}$`);
75
- }
76
-
77
- function normalizePathForMatch(file) {
78
- return String(file || "").replace(/\\/g, "/");
79
- }
80
-
81
- function matchOne(file, pattern) {
82
- if (typeof pattern !== "string" || pattern.length === 0) {
83
- return false;
84
- }
85
- const normalizedFile = normalizePathForMatch(file);
86
- if (pattern.startsWith("re:")) {
87
- return new RegExp(`^${pattern.slice(3)}$`).test(normalizedFile);
88
- }
89
- return globToRegex(normalizePathForMatch(pattern)).test(normalizedFile);
90
- }
91
-
92
- function matchScope(file, patterns) {
93
- return normalizePatterns(patterns).some((pattern) => matchOne(file, pattern));
94
- }
95
-
96
- function checkFiles(scopes, changedFiles) {
97
- const allowed = normalizePatterns(scopes && scopes.allowed);
98
- const blocked = normalizePatterns(scopes && scopes.blocked);
99
- const declared = Boolean(scopes && scopes.declared);
100
- const files = Array.isArray(changedFiles)
101
- ? changedFiles.filter((entry) => typeof entry === "string" && entry.length > 0)
102
- : [];
103
-
104
- if (!declared && allowed.length === 0 && blocked.length === 0) {
105
- return {
106
- inScope: [],
107
- outOfScope: [],
108
- blockedHits: [],
109
- verdict: "needs_human",
110
- declared: false,
111
- };
112
- }
113
-
114
- const inScope = [];
115
- const outOfScope = [];
116
- const blockedHits = [];
117
- const hasAllowed = allowed.length > 0;
118
-
119
- for (const file of files) {
120
- if (matchScope(file, blocked)) {
121
- blockedHits.push(file);
122
- continue;
123
- }
124
- if (!hasAllowed || matchScope(file, allowed)) {
125
- inScope.push(file);
126
- } else {
127
- outOfScope.push(file);
128
- }
129
- }
130
-
131
- const verdict = blockedHits.length > 0 || outOfScope.length > 0 ? "fail" : "pass";
132
- return { inScope, outOfScope, blockedHits, verdict, declared: true };
133
- }
134
-
135
- function getChangedFiles(projectPath, baseRef = "HEAD") {
136
- const result = childProcess.spawnSync(
137
- "git",
138
- ["diff", "--name-only", baseRef],
139
- {
140
- cwd: path.resolve(projectPath || "."),
141
- encoding: "utf8",
142
- errors: "replace",
143
- },
144
- );
145
- if (result.error) {
146
- throw result.error;
147
- }
148
- if (result.status !== 0) {
149
- throw new Error((result.stderr || "git diff --name-only failed").trim());
150
- }
151
- return result.stdout.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
152
- }
153
-
154
- module.exports = { loadScopes, matchScope, checkFiles, getChangedFiles };
1
+ "use strict";
2
+
3
+ const childProcess = require("child_process");
4
+ const fs = require("fs");
5
+ const path = require("path");
6
+
7
+ function normalizePatterns(value) {
8
+ if (!Array.isArray(value)) {
9
+ return [];
10
+ }
11
+ return value.filter((entry) => typeof entry === "string" && entry.length > 0);
12
+ }
13
+
14
+ function loadScopes(projectPath, featureKey, opts = {}) {
15
+ const optAllowed = normalizePatterns(opts.allowed);
16
+ const optBlocked = normalizePatterns(opts.blocked);
17
+ if (Array.isArray(opts.allowed) || Array.isArray(opts.blocked)) {
18
+ return {
19
+ allowed: optAllowed,
20
+ blocked: optBlocked,
21
+ declared: optAllowed.length > 0 || optBlocked.length > 0,
22
+ source: "opts",
23
+ };
24
+ }
25
+
26
+ const handoffPath = path.join(
27
+ path.resolve(projectPath || "."),
28
+ "docs",
29
+ "dev",
30
+ `CODE_HANDOFF_${featureKey}.json`,
31
+ );
32
+
33
+ try {
34
+ const payload = JSON.parse(fs.readFileSync(handoffPath, "utf8"));
35
+ const allowed = normalizePatterns(payload.allowed_file_scopes);
36
+ const blocked = normalizePatterns(payload.blocked_file_scopes);
37
+ if (Array.isArray(payload.allowed_file_scopes) || Array.isArray(payload.blocked_file_scopes)) {
38
+ return {
39
+ allowed,
40
+ blocked,
41
+ declared: allowed.length > 0 || blocked.length > 0,
42
+ source: "handoff",
43
+ };
44
+ }
45
+ } catch (_error) {
46
+ // Missing or invalid optional forward-compat handoff fields fall back cleanly.
47
+ }
48
+
49
+ return { allowed: [], blocked: [], declared: false, source: "none" };
50
+ }
51
+
52
+ function escapeRegexChar(char) {
53
+ return /[\\^$+?.()|[\]{}]/.test(char) ? `\\${char}` : char;
54
+ }
55
+
56
+ function globToRegex(pattern) {
57
+ let source = "";
58
+ for (let index = 0; index < pattern.length; index += 1) {
59
+ const char = pattern[index];
60
+ const next = pattern[index + 1];
61
+ if (char === "*") {
62
+ if (next === "*") {
63
+ source += ".*";
64
+ index += 1;
65
+ } else {
66
+ source += "[^/]*";
67
+ }
68
+ } else if (char === "?") {
69
+ source += "[^/]";
70
+ } else {
71
+ source += escapeRegexChar(char);
72
+ }
73
+ }
74
+ return new RegExp(`^${source}$`);
75
+ }
76
+
77
+ function normalizePathForMatch(file) {
78
+ return String(file || "").replace(/\\/g, "/");
79
+ }
80
+
81
+ function matchOne(file, pattern) {
82
+ if (typeof pattern !== "string" || pattern.length === 0) {
83
+ return false;
84
+ }
85
+ const normalizedFile = normalizePathForMatch(file);
86
+ if (pattern.startsWith("re:")) {
87
+ return new RegExp(`^${pattern.slice(3)}$`).test(normalizedFile);
88
+ }
89
+ return globToRegex(normalizePathForMatch(pattern)).test(normalizedFile);
90
+ }
91
+
92
+ function matchScope(file, patterns) {
93
+ return normalizePatterns(patterns).some((pattern) => matchOne(file, pattern));
94
+ }
95
+
96
+ function checkFiles(scopes, changedFiles) {
97
+ const allowed = normalizePatterns(scopes && scopes.allowed);
98
+ const blocked = normalizePatterns(scopes && scopes.blocked);
99
+ const declared = Boolean(scopes && scopes.declared);
100
+ const files = Array.isArray(changedFiles)
101
+ ? changedFiles.filter((entry) => typeof entry === "string" && entry.length > 0)
102
+ : [];
103
+
104
+ if (!declared && allowed.length === 0 && blocked.length === 0) {
105
+ return {
106
+ inScope: [],
107
+ outOfScope: [],
108
+ blockedHits: [],
109
+ verdict: "needs_human",
110
+ declared: false,
111
+ };
112
+ }
113
+
114
+ const inScope = [];
115
+ const outOfScope = [];
116
+ const blockedHits = [];
117
+ const hasAllowed = allowed.length > 0;
118
+
119
+ for (const file of files) {
120
+ if (matchScope(file, blocked)) {
121
+ blockedHits.push(file);
122
+ continue;
123
+ }
124
+ if (!hasAllowed || matchScope(file, allowed)) {
125
+ inScope.push(file);
126
+ } else {
127
+ outOfScope.push(file);
128
+ }
129
+ }
130
+
131
+ const verdict = blockedHits.length > 0 || outOfScope.length > 0 ? "fail" : "pass";
132
+ return { inScope, outOfScope, blockedHits, verdict, declared: true };
133
+ }
134
+
135
+ function getChangedFiles(projectPath, baseRef = "HEAD") {
136
+ const result = childProcess.spawnSync(
137
+ "git",
138
+ ["diff", "--name-only", baseRef],
139
+ {
140
+ cwd: path.resolve(projectPath || "."),
141
+ encoding: "utf8",
142
+ errors: "replace",
143
+ },
144
+ );
145
+ if (result.error) {
146
+ throw result.error;
147
+ }
148
+ if (result.status !== 0) {
149
+ throw new Error((result.stderr || "git diff --name-only failed").trim());
150
+ }
151
+ return result.stdout.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
152
+ }
153
+
154
+ module.exports = { loadScopes, matchScope, checkFiles, getChangedFiles };