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.
- package/README.md +17 -0
- package/assets/manifest/toolkit-bundle.manifest.json +147 -147
- package/assets/manifest/toolkit-bundle.sha256.txt +10 -10
- package/assets/toolkit/toolkit/AGENTS.md +219 -219
- package/assets/toolkit/toolkit/install.ps1 +156 -156
- package/assets/toolkit/toolkit/sdtk-spec.config.json +6 -6
- package/assets/toolkit/toolkit/skills/code-debug/SKILL.md +295 -295
- package/assets/toolkit/toolkit/skills/code-discover/SKILL.md +54 -54
- package/assets/toolkit/toolkit/skills/code-tdd/SKILL.md +377 -377
- package/assets/toolkit/toolkit/skills/code-worktree/SKILL.md +215 -215
- package/assets/toolkit/toolkit/templates/CODE_WORKFLOW_TEMPLATE.md +28 -0
- package/package.json +44 -44
- package/src/commands/doctor.js +52 -0
- package/src/commands/guardrails.js +215 -0
- package/src/commands/help.js +244 -220
- package/src/commands/init.js +98 -98
- package/src/commands/readiness.js +77 -0
- package/src/commands/resume.js +62 -0
- package/src/commands/sleep.js +132 -0
- package/src/commands/status.js +78 -0
- package/src/commands/update.js +11 -11
- package/src/commands/verify.js +5 -0
- package/src/index.js +108 -73
- package/src/lib/project-target-guard.js +53 -53
- package/src/lib/ship-readiness.js +281 -0
- package/src/lib/sleep-plan.js +175 -0
- package/src/lib/sleep-report.js +229 -0
- package/src/lib/trust-events.js +166 -0
- package/src/lib/trust-file-scope.js +154 -0
- package/src/lib/trust-policy.js +212 -0
- package/src/lib/trust-redact.js +35 -0
- package/src/lib/trust-trace.js +179 -0
- package/src/lib/update.js +344 -344
- package/src/lib/workflow-artifact.js +9 -2
- package/src/lib/workflow-doctor.js +84 -0
- package/src/lib/workflow-handoff.js +111 -19
- package/src/lib/workflow-review-packet.js +650 -561
- package/src/lib/workflow-state.js +439 -0
- package/src/lib/workflow-verify.js +393 -356
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const fs = require("fs");
|
|
4
|
+
const path = require("path");
|
|
5
|
+
const { ValidationError } = require("./errors");
|
|
6
|
+
const { loadScopes } = require("./trust-file-scope");
|
|
7
|
+
|
|
8
|
+
const STOP_CONDITIONS = [
|
|
9
|
+
{
|
|
10
|
+
id: "scope_lock",
|
|
11
|
+
description: "Halt if action would touch a blocked file scope.",
|
|
12
|
+
default: "on",
|
|
13
|
+
},
|
|
14
|
+
{
|
|
15
|
+
id: "destructive_deny",
|
|
16
|
+
description:
|
|
17
|
+
"Deny irreversible destructive operations (rm -rf, DROP TABLE, force-push main).",
|
|
18
|
+
default: "on",
|
|
19
|
+
},
|
|
20
|
+
{
|
|
21
|
+
id: "deploy_confirm",
|
|
22
|
+
description:
|
|
23
|
+
"Pause at deploy_confirm_points and require explicit confirmation before deployment actions.",
|
|
24
|
+
default: "on",
|
|
25
|
+
},
|
|
26
|
+
{
|
|
27
|
+
id: "secret_block",
|
|
28
|
+
description:
|
|
29
|
+
"Block any action that reads or writes secret material (.env, *.pem, credentials).",
|
|
30
|
+
default: "on",
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
id: "action_count_cap",
|
|
34
|
+
description: "Stop when action count reaches budgets.max_actions.",
|
|
35
|
+
default: "on",
|
|
36
|
+
},
|
|
37
|
+
{
|
|
38
|
+
id: "test_evidence_required",
|
|
39
|
+
description: "Do not mark a slice done without test_obligations evidence.",
|
|
40
|
+
default: "on",
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
id: "unknown_risk_stop",
|
|
44
|
+
description: "Stop and escalate when risk is unclassified or cannot be assessed.",
|
|
45
|
+
default: "on",
|
|
46
|
+
},
|
|
47
|
+
{
|
|
48
|
+
id: "three_fix_escalation",
|
|
49
|
+
description: "Escalate to controller after three failed fix attempts on the same failure.",
|
|
50
|
+
default: "on",
|
|
51
|
+
},
|
|
52
|
+
];
|
|
53
|
+
|
|
54
|
+
const CHECKPOINT_SCHEMA = {
|
|
55
|
+
phase: null,
|
|
56
|
+
files_touched: [],
|
|
57
|
+
last_green_verify: null,
|
|
58
|
+
blocker: null,
|
|
59
|
+
next_safe_action: null,
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* PURE — builds a sleep-plan.v1 object from crafted inputs; no fs calls.
|
|
64
|
+
* Defaults: max_actions=50, max_iterations=10.
|
|
65
|
+
*/
|
|
66
|
+
function buildSleepPlan(handoff, scopes, opts) {
|
|
67
|
+
const rawActions = opts.maxActions !== undefined ? Number(opts.maxActions) : 50;
|
|
68
|
+
const rawIterations = opts.maxIterations !== undefined ? Number(opts.maxIterations) : 10;
|
|
69
|
+
|
|
70
|
+
if (!Number.isInteger(rawActions) || rawActions <= 0) {
|
|
71
|
+
throw new ValidationError("--max-actions must be a positive integer.");
|
|
72
|
+
}
|
|
73
|
+
if (!Number.isInteger(rawIterations) || rawIterations <= 0) {
|
|
74
|
+
throw new ValidationError("--max-iterations must be a positive integer.");
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
return {
|
|
78
|
+
schema_version: "sdtk.sleep-plan.v1",
|
|
79
|
+
feature_key: handoff.feature_key,
|
|
80
|
+
source: {
|
|
81
|
+
code_handoff_path: handoff._handoff_path || null,
|
|
82
|
+
lane: handoff.recommended_lane || null,
|
|
83
|
+
},
|
|
84
|
+
ordered_steps: Array.isArray(handoff.implementation_slices)
|
|
85
|
+
? [...handoff.implementation_slices]
|
|
86
|
+
: [],
|
|
87
|
+
scope: {
|
|
88
|
+
allowed_file_scopes: scopes.allowed || [],
|
|
89
|
+
blocked_file_scopes: scopes.blocked || [],
|
|
90
|
+
declared: scopes.declared === true,
|
|
91
|
+
},
|
|
92
|
+
policy_profile: "sleep-preview",
|
|
93
|
+
budgets: {
|
|
94
|
+
max_actions: rawActions,
|
|
95
|
+
max_iterations: rawIterations,
|
|
96
|
+
},
|
|
97
|
+
test_obligations: Array.isArray(handoff.test_obligations)
|
|
98
|
+
? [...handoff.test_obligations]
|
|
99
|
+
: [],
|
|
100
|
+
stop_conditions: STOP_CONDITIONS,
|
|
101
|
+
deploy_confirm_points: [],
|
|
102
|
+
checkpoint_schema: CHECKPOINT_SCHEMA,
|
|
103
|
+
runtime: "agnostic",
|
|
104
|
+
generated_at: new Date().toISOString(),
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Thin fs wrapper — reads CODE_HANDOFF + loadScopes, then calls buildSleepPlan.
|
|
110
|
+
* Fail-closed: missing/invalid handoff or not READY_FOR_SDTK_CODE → ValidationError(NEEDS_HANDOFF).
|
|
111
|
+
*/
|
|
112
|
+
function assembleSleepPlan(projectPath, featureKey, opts) {
|
|
113
|
+
opts = opts || {};
|
|
114
|
+
const resolved = path.resolve(projectPath || ".");
|
|
115
|
+
const handoffPath = path.join(
|
|
116
|
+
resolved,
|
|
117
|
+
"docs",
|
|
118
|
+
"dev",
|
|
119
|
+
`CODE_HANDOFF_${featureKey}.json`
|
|
120
|
+
);
|
|
121
|
+
|
|
122
|
+
let handoff;
|
|
123
|
+
try {
|
|
124
|
+
const raw = fs.readFileSync(handoffPath, "utf8");
|
|
125
|
+
handoff = JSON.parse(raw);
|
|
126
|
+
} catch (_err) {
|
|
127
|
+
throw new ValidationError(
|
|
128
|
+
`NEEDS_HANDOFF: CODE_HANDOFF_${featureKey}.json not found or invalid at ${handoffPath}. ` +
|
|
129
|
+
"Ensure the feature has a valid READY_FOR_SDTK_CODE handoff before running sleep plan."
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
if (handoff.handoff_status !== "READY_FOR_SDTK_CODE") {
|
|
134
|
+
throw new ValidationError(
|
|
135
|
+
`NEEDS_HANDOFF: CODE_HANDOFF_${featureKey}.json status is "${handoff.handoff_status}", ` +
|
|
136
|
+
'expected "READY_FOR_SDTK_CODE". Resolve open blockers first.'
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
if (!Array.isArray(handoff.implementation_slices) || handoff.implementation_slices.length === 0) {
|
|
141
|
+
throw new ValidationError(
|
|
142
|
+
`NEEDS_HANDOFF: CODE_HANDOFF_${featureKey}.json must have at least one implementation_slices entry.`
|
|
143
|
+
);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// Attach path for source provenance in the plan (read by buildSleepPlan).
|
|
147
|
+
handoff._handoff_path = handoffPath;
|
|
148
|
+
|
|
149
|
+
const scopes = loadScopes(resolved, featureKey, opts.scopes || {});
|
|
150
|
+
|
|
151
|
+
return buildSleepPlan(handoff, scopes, {
|
|
152
|
+
maxActions: opts.maxActions,
|
|
153
|
+
maxIterations: opts.maxIterations,
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Thin fs wrapper — writes plan to .sdtk/trust/sleep-plan.json; returns output path.
|
|
159
|
+
*/
|
|
160
|
+
function writeSleepPlan(projectPath, plan) {
|
|
161
|
+
const resolved = path.resolve(projectPath || ".");
|
|
162
|
+
const trustDir = path.join(resolved, ".sdtk", "trust");
|
|
163
|
+
fs.mkdirSync(trustDir, { recursive: true });
|
|
164
|
+
const outPath = path.join(trustDir, "sleep-plan.json");
|
|
165
|
+
fs.writeFileSync(outPath, JSON.stringify(plan, null, 2), "utf8");
|
|
166
|
+
return outPath;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
module.exports = {
|
|
170
|
+
STOP_CONDITIONS,
|
|
171
|
+
CHECKPOINT_SCHEMA,
|
|
172
|
+
buildSleepPlan,
|
|
173
|
+
assembleSleepPlan,
|
|
174
|
+
writeSleepPlan,
|
|
175
|
+
};
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const fs = require("fs");
|
|
4
|
+
const path = require("path");
|
|
5
|
+
const { ValidationError } = require("./errors");
|
|
6
|
+
const { computeReadiness, gatherSignals } = require("./ship-readiness");
|
|
7
|
+
|
|
8
|
+
const REPORT_SCHEMA = "sdtk.sleep-report.v1";
|
|
9
|
+
const PLAN_SCHEMA = "sdtk.sleep-plan.v1";
|
|
10
|
+
const SCOPE_BLOCKER =
|
|
11
|
+
"Scope not declared — the agent could touch any file; `scope_lock` has nothing to enforce.";
|
|
12
|
+
const DRY_RUN_DISCLAIMER =
|
|
13
|
+
"This is a pre-flight projection of the plan — nothing was executed.";
|
|
14
|
+
|
|
15
|
+
function list(value) {
|
|
16
|
+
return Array.isArray(value) ? [...value] : [];
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function planScope(plan) {
|
|
20
|
+
return plan && plan.scope && typeof plan.scope === "object" ? plan.scope : {};
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function readinessComponentNotes(readiness) {
|
|
24
|
+
if (!readiness || !Array.isArray(readiness.components)) {
|
|
25
|
+
return [];
|
|
26
|
+
}
|
|
27
|
+
return readiness.components
|
|
28
|
+
.filter((component) => component && typeof component.note === "string" && component.note.length > 0)
|
|
29
|
+
.map((component) => `${component.name}: ${component.note}`);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function failingComponentNames(readiness) {
|
|
33
|
+
if (!readiness || !Array.isArray(readiness.components)) {
|
|
34
|
+
return [];
|
|
35
|
+
}
|
|
36
|
+
return readiness.components
|
|
37
|
+
.filter((component) => Number(component.points) < Number(component.max))
|
|
38
|
+
.map((component) => component.name)
|
|
39
|
+
.filter((name) => typeof name === "string" && name.length > 0);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function projectSleepReport(plan, signals) {
|
|
43
|
+
const readiness = computeReadiness(signals);
|
|
44
|
+
const blockers = [];
|
|
45
|
+
const notes = [];
|
|
46
|
+
const scope = planScope(plan);
|
|
47
|
+
const orderedSteps = list(plan && plan.ordered_steps);
|
|
48
|
+
const testObligations = list(plan && plan.test_obligations);
|
|
49
|
+
const deployConfirmPoints = list(plan && plan.deploy_confirm_points);
|
|
50
|
+
|
|
51
|
+
if (!plan || plan.schema_version !== PLAN_SCHEMA || orderedSteps.length === 0) {
|
|
52
|
+
blockers.push("Invalid sleep plan — expected sdtk.sleep-plan.v1 with at least one ordered step.");
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
if (scope.declared !== true) {
|
|
56
|
+
blockers.push(SCOPE_BLOCKER);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
if (readiness.verdict === "FAIL") {
|
|
60
|
+
const failing = failingComponentNames(readiness);
|
|
61
|
+
blockers.push(
|
|
62
|
+
failing.length > 0
|
|
63
|
+
? `Ship-readiness FAIL. Failing components: ${failing.join(", ")}.`
|
|
64
|
+
: "Ship-readiness FAIL."
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
if (readiness.verdict === "ENV_BLOCKED") {
|
|
69
|
+
blockers.push("Readiness signals unavailable (ENV_BLOCKED).");
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
if (testObligations.length === 0) {
|
|
73
|
+
notes.push("No test obligations carried — `test_evidence_required` has nothing to check.");
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
if (readiness.verdict === "PASS_WITH_NOTES") {
|
|
77
|
+
const warnings = Array.isArray(readiness.warnings) ? readiness.warnings : [];
|
|
78
|
+
if (warnings.length > 0) {
|
|
79
|
+
notes.push(...warnings);
|
|
80
|
+
} else {
|
|
81
|
+
notes.push("Ship-readiness PASS_WITH_NOTES.");
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const verdict = blockers.length > 0
|
|
86
|
+
? "NOT_READY"
|
|
87
|
+
: notes.length > 0
|
|
88
|
+
? "READY_WITH_NOTES"
|
|
89
|
+
: "READY_TO_SLEEP";
|
|
90
|
+
|
|
91
|
+
const reason = blockers.length > 0
|
|
92
|
+
? blockers[0]
|
|
93
|
+
: notes.length > 0
|
|
94
|
+
? notes[0]
|
|
95
|
+
: "The sleep plan is bounded, readiness is PASS, and test obligations are present.";
|
|
96
|
+
|
|
97
|
+
return {
|
|
98
|
+
schema_version: REPORT_SCHEMA,
|
|
99
|
+
feature_key: plan && plan.feature_key,
|
|
100
|
+
verdict,
|
|
101
|
+
reason,
|
|
102
|
+
readiness,
|
|
103
|
+
sections: {
|
|
104
|
+
can_i_sleep: { verdict, reason },
|
|
105
|
+
what_it_can_touch: {
|
|
106
|
+
declared: scope.declared === true,
|
|
107
|
+
allowed_file_scopes: list(scope.allowed_file_scopes),
|
|
108
|
+
blocked_file_scopes: list(scope.blocked_file_scopes),
|
|
109
|
+
warning: scope.declared === true ? null : "scope_lock cannot enforce undeclared scope.",
|
|
110
|
+
},
|
|
111
|
+
when_it_will_stop: {
|
|
112
|
+
stop_conditions: list(plan && plan.stop_conditions).map((condition) => {
|
|
113
|
+
if (condition && typeof condition === "object" && typeof condition.id === "string") {
|
|
114
|
+
return condition.id;
|
|
115
|
+
}
|
|
116
|
+
return condition;
|
|
117
|
+
}),
|
|
118
|
+
budgets: plan && plan.budgets && typeof plan.budgets === "object" ? { ...plan.budgets } : {},
|
|
119
|
+
},
|
|
120
|
+
what_proves_done: {
|
|
121
|
+
test_obligations: testObligations,
|
|
122
|
+
readiness_components: readinessComponentNotes(readiness),
|
|
123
|
+
},
|
|
124
|
+
what_needs_you: {
|
|
125
|
+
deploy_confirm_points: deployConfirmPoints,
|
|
126
|
+
blockers: [...blockers],
|
|
127
|
+
notes: [...notes],
|
|
128
|
+
},
|
|
129
|
+
},
|
|
130
|
+
blockers,
|
|
131
|
+
notes,
|
|
132
|
+
dry_run: true,
|
|
133
|
+
generated_at: new Date().toISOString(),
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function bulletList(items, fallback) {
|
|
138
|
+
if (!Array.isArray(items) || items.length === 0) {
|
|
139
|
+
return `- ${fallback}`;
|
|
140
|
+
}
|
|
141
|
+
return items.map((item) => `- ${String(item)}`).join("\n");
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function renderSleepReportMarkdown(report) {
|
|
145
|
+
const touch = report.sections.what_it_can_touch;
|
|
146
|
+
const stop = report.sections.when_it_will_stop;
|
|
147
|
+
const proves = report.sections.what_proves_done;
|
|
148
|
+
const needs = report.sections.what_needs_you;
|
|
149
|
+
|
|
150
|
+
return [
|
|
151
|
+
`# Sleep Readiness Report — ${report.feature_key}`,
|
|
152
|
+
"",
|
|
153
|
+
DRY_RUN_DISCLAIMER,
|
|
154
|
+
"",
|
|
155
|
+
"## Can I sleep?",
|
|
156
|
+
"",
|
|
157
|
+
`- Verdict: ${report.verdict}`,
|
|
158
|
+
`- Reason: ${report.reason}`,
|
|
159
|
+
`- Readiness: ${report.readiness.score}/${report.readiness.max} — ${report.readiness.verdict}`,
|
|
160
|
+
"",
|
|
161
|
+
"## What it can touch",
|
|
162
|
+
"",
|
|
163
|
+
`- Scope declared: ${touch.declared ? "yes" : "no"}`,
|
|
164
|
+
"- Allowed file scopes:",
|
|
165
|
+
bulletList(touch.allowed_file_scopes, "none declared"),
|
|
166
|
+
"- Blocked file scopes:",
|
|
167
|
+
bulletList(touch.blocked_file_scopes, "none declared"),
|
|
168
|
+
touch.warning ? `- Warning: ${touch.warning}` : "- Warning: none",
|
|
169
|
+
"",
|
|
170
|
+
"## When it will stop",
|
|
171
|
+
"",
|
|
172
|
+
"- Stop conditions:",
|
|
173
|
+
bulletList(stop.stop_conditions, "none declared"),
|
|
174
|
+
"- Budgets:",
|
|
175
|
+
`- max_actions: ${stop.budgets.max_actions !== undefined ? stop.budgets.max_actions : "not declared"}`,
|
|
176
|
+
`- max_iterations: ${stop.budgets.max_iterations !== undefined ? stop.budgets.max_iterations : "not declared"}`,
|
|
177
|
+
"",
|
|
178
|
+
"## What proves it's done",
|
|
179
|
+
"",
|
|
180
|
+
"- Test obligations:",
|
|
181
|
+
bulletList(proves.test_obligations, "none carried"),
|
|
182
|
+
"- Readiness components:",
|
|
183
|
+
bulletList(proves.readiness_components, "none"),
|
|
184
|
+
"",
|
|
185
|
+
"## What needs you",
|
|
186
|
+
"",
|
|
187
|
+
"- Deploy confirm points:",
|
|
188
|
+
bulletList(needs.deploy_confirm_points, "none declared"),
|
|
189
|
+
"- Blockers:",
|
|
190
|
+
bulletList(needs.blockers, "none"),
|
|
191
|
+
"- Notes:",
|
|
192
|
+
bulletList(needs.notes, "none"),
|
|
193
|
+
"",
|
|
194
|
+
].join("\n");
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function loadSleepPlan(projectPath) {
|
|
198
|
+
const resolved = path.resolve(projectPath || ".");
|
|
199
|
+
const planPath = path.join(resolved, ".sdtk", "trust", "sleep-plan.json");
|
|
200
|
+
try {
|
|
201
|
+
return JSON.parse(fs.readFileSync(planPath, "utf8"));
|
|
202
|
+
} catch (_error) {
|
|
203
|
+
throw new ValidationError(
|
|
204
|
+
`NEEDS_PLAN: no sleep plan found at ${planPath}; ` +
|
|
205
|
+
"run `sdtk-code sleep plan --feature-key <KEY>` first."
|
|
206
|
+
);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function gatherReportSignals(projectPath, featureKey) {
|
|
211
|
+
return gatherSignals(projectPath, featureKey);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function writeSleepReport(projectPath, featureKey, markdown) {
|
|
215
|
+
const resolved = path.resolve(projectPath || ".");
|
|
216
|
+
const outDir = path.join(resolved, "docs", "trust");
|
|
217
|
+
fs.mkdirSync(outDir, { recursive: true });
|
|
218
|
+
const outPath = path.join(outDir, `SLEEP_REPORT_${featureKey}.md`);
|
|
219
|
+
fs.writeFileSync(outPath, markdown, "utf8");
|
|
220
|
+
return outPath;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
module.exports = {
|
|
224
|
+
projectSleepReport,
|
|
225
|
+
renderSleepReportMarkdown,
|
|
226
|
+
loadSleepPlan,
|
|
227
|
+
gatherReportSignals,
|
|
228
|
+
writeSleepReport,
|
|
229
|
+
};
|
|
@@ -0,0 +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 };
|