sdtk-code-kit 0.1.3 → 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 (39) hide show
  1. package/README.md +17 -0
  2. package/assets/manifest/toolkit-bundle.manifest.json +147 -147
  3. package/assets/manifest/toolkit-bundle.sha256.txt +10 -10
  4. package/assets/toolkit/toolkit/AGENTS.md +219 -219
  5. package/assets/toolkit/toolkit/install.ps1 +156 -156
  6. package/assets/toolkit/toolkit/sdtk-spec.config.json +6 -6
  7. package/assets/toolkit/toolkit/skills/code-debug/SKILL.md +295 -295
  8. package/assets/toolkit/toolkit/skills/code-discover/SKILL.md +54 -54
  9. package/assets/toolkit/toolkit/skills/code-tdd/SKILL.md +377 -377
  10. package/assets/toolkit/toolkit/skills/code-worktree/SKILL.md +215 -215
  11. package/assets/toolkit/toolkit/templates/CODE_WORKFLOW_TEMPLATE.md +28 -0
  12. package/package.json +44 -44
  13. package/src/commands/doctor.js +52 -0
  14. package/src/commands/guardrails.js +215 -0
  15. package/src/commands/help.js +244 -220
  16. package/src/commands/init.js +98 -98
  17. package/src/commands/readiness.js +77 -0
  18. package/src/commands/resume.js +62 -0
  19. package/src/commands/sleep.js +132 -0
  20. package/src/commands/status.js +78 -0
  21. package/src/commands/update.js +11 -11
  22. package/src/commands/verify.js +5 -0
  23. package/src/index.js +108 -73
  24. package/src/lib/project-target-guard.js +53 -53
  25. package/src/lib/ship-readiness.js +281 -0
  26. package/src/lib/sleep-plan.js +175 -0
  27. package/src/lib/sleep-report.js +229 -0
  28. package/src/lib/trust-events.js +166 -0
  29. package/src/lib/trust-file-scope.js +154 -0
  30. package/src/lib/trust-policy.js +212 -0
  31. package/src/lib/trust-redact.js +35 -0
  32. package/src/lib/trust-trace.js +179 -0
  33. package/src/lib/update.js +344 -344
  34. package/src/lib/workflow-artifact.js +9 -2
  35. package/src/lib/workflow-doctor.js +84 -0
  36. package/src/lib/workflow-handoff.js +111 -19
  37. package/src/lib/workflow-review-packet.js +650 -561
  38. package/src/lib/workflow-state.js +439 -0
  39. package/src/lib/workflow-verify.js +393 -356
@@ -0,0 +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 };
@@ -0,0 +1,212 @@
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const { ValidationError } = require("./errors");
6
+
7
+ // Default allow/ask/deny pack (BK-240 §5), derived from the reference harness
8
+ // settings.json command classes. Patterns starting with "^" are treated as
9
+ // anchored regular expressions; all other patterns are case-sensitive
10
+ // substring matches against the command string. NO shell execution: this is
11
+ // advisory classification only.
12
+ const DEFAULT_POLICY = {
13
+ deny: [
14
+ "^rm -rf",
15
+ "^rm -fr",
16
+ "^sudo ",
17
+ "git reset --hard",
18
+ "git push --force",
19
+ "git push -f",
20
+ "mkfs",
21
+ "^dd ",
22
+ ".env",
23
+ ".pem",
24
+ "secrets/",
25
+ "^psql",
26
+ "^mysql",
27
+ "^mongod",
28
+ ],
29
+ ask: [
30
+ "npm install",
31
+ "npm publish",
32
+ "npm exec",
33
+ "npx",
34
+ "git merge",
35
+ "git rebase",
36
+ "git clean -fd",
37
+ "git clean -fx",
38
+ "git clean -fdx",
39
+ ],
40
+ allow: [
41
+ "git status",
42
+ "git diff",
43
+ "git log",
44
+ "git branch",
45
+ "git show",
46
+ "npm test",
47
+ "npm run test",
48
+ "npm run lint",
49
+ "npm run build",
50
+ "pytest",
51
+ "python -m unittest",
52
+ "rg ",
53
+ "ls ",
54
+ "node --check",
55
+ ],
56
+ // limits.max_actions is omitted by default; callers may add it (and supply
57
+ // --action-count) to enable the action-count cap.
58
+ limits: {},
59
+ };
60
+
61
+ function assertPatternArray(value, label) {
62
+ if (!Array.isArray(value)) {
63
+ throw new ValidationError(
64
+ `Invalid trust policy: "${label}" must be an array of string patterns.`
65
+ );
66
+ }
67
+ value.forEach((entry, index) => {
68
+ if (typeof entry !== "string") {
69
+ throw new ValidationError(
70
+ `Invalid trust policy: "${label}[${index}]" must be a string pattern.`
71
+ );
72
+ }
73
+ });
74
+ }
75
+
76
+ function validatePolicy(obj) {
77
+ if (!obj || typeof obj !== "object" || Array.isArray(obj)) {
78
+ throw new ValidationError("Invalid trust policy: expected a JSON object.");
79
+ }
80
+ assertPatternArray(obj.deny, "deny");
81
+ assertPatternArray(obj.ask, "ask");
82
+ assertPatternArray(obj.allow, "allow");
83
+
84
+ if (obj.limits !== undefined && obj.limits !== null) {
85
+ if (typeof obj.limits !== "object" || Array.isArray(obj.limits)) {
86
+ throw new ValidationError('Invalid trust policy: "limits" must be an object.');
87
+ }
88
+ if (
89
+ obj.limits.max_actions !== undefined &&
90
+ typeof obj.limits.max_actions !== "number"
91
+ ) {
92
+ throw new ValidationError(
93
+ 'Invalid trust policy: "limits.max_actions" must be a number.'
94
+ );
95
+ }
96
+ }
97
+ return obj;
98
+ }
99
+
100
+ function policyFile(projectPath) {
101
+ return path.join(path.resolve(projectPath || "."), ".sdtk", "trust", "policy.json");
102
+ }
103
+
104
+ function loadPolicy(projectPath) {
105
+ const file = policyFile(projectPath);
106
+ if (!fs.existsSync(file)) {
107
+ return DEFAULT_POLICY;
108
+ }
109
+ let parsed;
110
+ try {
111
+ parsed = JSON.parse(fs.readFileSync(file, "utf8"));
112
+ } catch (error) {
113
+ throw new ValidationError(
114
+ `Invalid trust policy: ${file} is not valid JSON (${error.message}).`
115
+ );
116
+ }
117
+ return validatePolicy(parsed);
118
+ }
119
+
120
+ // Match a single pattern against the command string. "^"-prefixed patterns are
121
+ // anchored regexes; everything else is a case-sensitive substring match. A
122
+ // malformed regex pattern is treated as a non-match so classify never crashes.
123
+ function matchesPattern(pattern, command) {
124
+ if (typeof pattern !== "string" || pattern.length === 0) {
125
+ return false;
126
+ }
127
+ if (pattern.startsWith("^")) {
128
+ try {
129
+ return new RegExp(pattern).test(command);
130
+ } catch (_error) {
131
+ return false;
132
+ }
133
+ }
134
+ return command.includes(pattern);
135
+ }
136
+
137
+ function firstMatch(patterns, command) {
138
+ if (!Array.isArray(patterns)) {
139
+ return null;
140
+ }
141
+ for (const pattern of patterns) {
142
+ if (matchesPattern(pattern, command)) {
143
+ return pattern;
144
+ }
145
+ }
146
+ return null;
147
+ }
148
+
149
+ // Classify a command as allow/ask/deny against a policy. Most-restrictive-wins,
150
+ // deterministic. Stateless: the caller supplies opts.actionCount; trust-policy
151
+ // performs no session counting. Never executes the command.
152
+ function classifyCommand(policy, command, opts) {
153
+ const cmd = typeof command === "string" ? command : "";
154
+ const options = opts && typeof opts === "object" ? opts : {};
155
+ const limits = policy && policy.limits && typeof policy.limits === "object" ? policy.limits : {};
156
+
157
+ // 1. action-count cap.
158
+ if (
159
+ typeof options.actionCount === "number" &&
160
+ typeof limits.max_actions === "number" &&
161
+ options.actionCount >= limits.max_actions
162
+ ) {
163
+ return {
164
+ verdict: "deny",
165
+ reason: `action-count cap reached (${options.actionCount}/${limits.max_actions})`,
166
+ matchedRule: { bucket: "limit", pattern: "limits.max_actions" },
167
+ };
168
+ }
169
+
170
+ // 2. deny → 3. ask → 4. allow (first match wins per bucket).
171
+ const denyHit = firstMatch(policy && policy.deny, cmd);
172
+ if (denyHit) {
173
+ return {
174
+ verdict: "deny",
175
+ reason: `denied by policy rule: ${denyHit}`,
176
+ matchedRule: { bucket: "deny", pattern: denyHit },
177
+ };
178
+ }
179
+
180
+ const askHit = firstMatch(policy && policy.ask, cmd);
181
+ if (askHit) {
182
+ return {
183
+ verdict: "ask",
184
+ reason: `requires confirmation by policy rule: ${askHit}`,
185
+ matchedRule: { bucket: "ask", pattern: askHit },
186
+ };
187
+ }
188
+
189
+ const allowHit = firstMatch(policy && policy.allow, cmd);
190
+ if (allowHit) {
191
+ return {
192
+ verdict: "allow",
193
+ reason: `allowed by policy rule: ${allowHit}`,
194
+ matchedRule: { bucket: "allow", pattern: allowHit },
195
+ };
196
+ }
197
+
198
+ // 5. no match → conservative ask.
199
+ return {
200
+ verdict: "ask",
201
+ reason: "no matching allow rule; defaulting to ask (conservative)",
202
+ matchedRule: null,
203
+ };
204
+ }
205
+
206
+ module.exports = {
207
+ DEFAULT_POLICY,
208
+ loadPolicy,
209
+ classifyCommand,
210
+ validatePolicy,
211
+ policyFile,
212
+ };
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+
3
+ const PRIVATE_TAG_PATTERN = /<private>[\s\S]*?<\/private>/gi;
4
+
5
+ const SECRET_PATTERNS = [
6
+ /(?:api[_-]?key|secret|token|password|credential|auth)[\s]*[=:]\s*["']?[A-Za-z0-9_\-/.+]{20,}["']?/gi,
7
+ /Bearer\s+[A-Za-z0-9._\-+/=]{20,}/gi,
8
+ /sk-proj-[A-Za-z0-9\-_]{20,}/g,
9
+ /(?:sk|pk|rk|ak)-[A-Za-z0-9][A-Za-z0-9\-_]{19,}/g,
10
+ /sk-ant-[A-Za-z0-9\-_]{20,}/g,
11
+ /gh[pus]_[A-Za-z0-9]{36,}/g,
12
+ /github_pat_[A-Za-z0-9_]{22,}/g,
13
+ /xoxb-[A-Za-z0-9\-]+/g,
14
+ /AKIA[0-9A-Z]{16}/g,
15
+ /AIza[A-Za-z0-9\-_]{35}/g,
16
+ /eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g,
17
+ /npm_[A-Za-z0-9]{36}/g,
18
+ /glpat-[A-Za-z0-9\-_]{20,}/g,
19
+ /dop_v1_[A-Za-z0-9]{64}/g,
20
+ ];
21
+
22
+ function redact(input) {
23
+ if (typeof input !== "string") {
24
+ return "";
25
+ }
26
+
27
+ let result = input.replace(PRIVATE_TAG_PATTERN, "[REDACTED]");
28
+ for (const source of SECRET_PATTERNS) {
29
+ const pattern = new RegExp(source.source, source.flags);
30
+ result = result.replace(pattern, "[REDACTED_SECRET]");
31
+ }
32
+ return result;
33
+ }
34
+
35
+ module.exports = { redact, SECRET_PATTERNS };
@@ -0,0 +1,179 @@
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const { eventsDir } = require("./trust-events");
6
+
7
+ function compareTimestamp(left, right) {
8
+ return String(left.timestamp || "").localeCompare(String(right.timestamp || ""));
9
+ }
10
+
11
+ function normalizeEvent(event) {
12
+ return event && typeof event === "object" ? event : {};
13
+ }
14
+
15
+ function phaseName(event) {
16
+ return typeof event.phase === "string" && event.phase.length > 0 ? event.phase : "ungrouped";
17
+ }
18
+
19
+ function isFailure(event) {
20
+ return event.status === "fail";
21
+ }
22
+
23
+ function isBlocked(event) {
24
+ return event.status === "blocked";
25
+ }
26
+
27
+ function isDecisionGate(event) {
28
+ if (event.event_type === "file_scope_check" && event.status === "fail") {
29
+ return true;
30
+ }
31
+ if (event.event_type === "guardrail_check" && (event.status === "fail" || event.status === "blocked" || event.decision === "deny")) {
32
+ return true;
33
+ }
34
+ return false;
35
+ }
36
+
37
+ function loadEvents(projectPath, opts = {}) {
38
+ const dir = eventsDir(projectPath);
39
+ if (!fs.existsSync(dir)) {
40
+ return [];
41
+ }
42
+
43
+ const files = fs.readdirSync(dir)
44
+ .filter((name) => name.endsWith(".jsonl"))
45
+ .filter((name) => !opts.date || name === `${opts.date}.jsonl`)
46
+ .sort();
47
+
48
+ const events = [];
49
+ for (const fileName of files) {
50
+ const filePath = path.join(dir, fileName);
51
+ const content = fs.readFileSync(filePath, "utf8");
52
+ for (const line of content.split(/\r?\n/)) {
53
+ if (!line.trim()) {
54
+ continue;
55
+ }
56
+ try {
57
+ const event = JSON.parse(line);
58
+ if (event && typeof event === "object") {
59
+ events.push(event);
60
+ }
61
+ } catch (_error) {
62
+ // Trust trace replay is resilient: malformed JSONL lines are skipped.
63
+ }
64
+ }
65
+ }
66
+ return events.sort(compareTimestamp);
67
+ }
68
+
69
+ function buildTrace(events) {
70
+ const sorted = Array.isArray(events) ? events.map(normalizeEvent).slice().sort(compareTimestamp) : [];
71
+ const phaseMap = new Map();
72
+ const sourceEventIds = [];
73
+ let failures = 0;
74
+ let blocked = 0;
75
+ let decisionGates = 0;
76
+
77
+ for (const event of sorted) {
78
+ const phase = phaseName(event);
79
+ if (!phaseMap.has(phase)) {
80
+ phaseMap.set(phase, { phase, events: [], failures: 0, blocked: 0, decisionGates: 0 });
81
+ }
82
+
83
+ const group = phaseMap.get(phase);
84
+ group.events.push(Object.assign({}, event));
85
+ if (typeof event.event_id === "string") {
86
+ sourceEventIds.push(event.event_id);
87
+ }
88
+ if (isFailure(event)) {
89
+ failures += 1;
90
+ group.failures += 1;
91
+ }
92
+ if (isBlocked(event)) {
93
+ blocked += 1;
94
+ group.blocked += 1;
95
+ }
96
+ if (isDecisionGate(event)) {
97
+ decisionGates += 1;
98
+ group.decisionGates += 1;
99
+ }
100
+ }
101
+
102
+ return {
103
+ phases: Array.from(phaseMap.values()),
104
+ totals: {
105
+ events: sorted.length,
106
+ failures,
107
+ blocked,
108
+ decisionGates,
109
+ },
110
+ sourceEventIds,
111
+ };
112
+ }
113
+
114
+ function commandText(event) {
115
+ if (typeof event.command === "string" && event.command.length > 0) {
116
+ return event.command;
117
+ }
118
+ return "(no command recorded)";
119
+ }
120
+
121
+ function renderTraceMarkdown(trace, meta = {}) {
122
+ const title = meta.title || `Trust Trace ${meta.featureKey || ""}`.trim() || "Trust Trace";
123
+ const lines = [
124
+ `# ${title}`,
125
+ "",
126
+ "Replay mode: reconstruction only. This report does not re-run commands and does not mutate events.",
127
+ "",
128
+ "## Summary",
129
+ "",
130
+ `- Events: ${trace.totals.events}`,
131
+ `- Failures: ${trace.totals.failures}`,
132
+ `- Blocked: ${trace.totals.blocked}`,
133
+ `- Decision gates: ${trace.totals.decisionGates}`,
134
+ "",
135
+ "## Source Event IDs",
136
+ "",
137
+ ];
138
+
139
+ if (trace.sourceEventIds.length === 0) {
140
+ lines.push("- None");
141
+ } else {
142
+ for (const id of trace.sourceEventIds) {
143
+ lines.push(`- \`${id}\``);
144
+ }
145
+ }
146
+
147
+ for (const phase of trace.phases) {
148
+ lines.push("", `## Phase: ${phase.phase}`, "", `- Events: ${phase.events.length}`, `- Failures: ${phase.failures}`, `- Blocked: ${phase.blocked}`, `- Decision gates: ${phase.decisionGates}`, "");
149
+
150
+ for (const event of phase.events) {
151
+ const gate = isDecisionGate(event) ? " Decision Gate" : "";
152
+ const eventId = event.event_id || "missing-event-id";
153
+ const timestamp = event.timestamp || "unknown-time";
154
+ const type = event.event_type || "unknown";
155
+ const status = event.status || "info";
156
+ lines.push(`- ${timestamp} - ${status} - ${type}${gate} - \`${eventId}\``);
157
+ lines.push(` - Command: ${commandText(event)}`);
158
+ if (Array.isArray(event.files) && event.files.length > 0) {
159
+ lines.push(` - Files: ${event.files.join(", ")}`);
160
+ }
161
+ }
162
+ }
163
+
164
+ return `${lines.join("\n")}\n`;
165
+ }
166
+
167
+ function writeTraceReport(projectPath, featureKey) {
168
+ const project = path.resolve(projectPath || ".");
169
+ const events = loadEvents(project);
170
+ const trace = buildTrace(events);
171
+ const markdown = renderTraceMarkdown(trace, { featureKey, title: `Trust Trace ${featureKey}` });
172
+ const reportDir = path.join(project, "docs", "trust");
173
+ const reportPath = path.join(reportDir, `TRUST_TRACE_${featureKey}.md`);
174
+ fs.mkdirSync(reportDir, { recursive: true });
175
+ fs.writeFileSync(reportPath, markdown, "utf8");
176
+ return { path: reportPath, events: trace.totals.events, trace };
177
+ }
178
+
179
+ module.exports = { loadEvents, buildTrace, renderTraceMarkdown, writeTraceReport };