geloforge 0.0.0-stage → 0.7.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 +21 -0
- package/README.md +72 -2
- package/THIRD_PARTY_NOTICES.md +33 -0
- package/VERSION +1 -0
- package/adapters/n8n/staging-audit-error-workflow.json +132 -0
- package/core/adopt-project.mjs +458 -0
- package/core/audit-learning.mjs +68 -0
- package/core/audit-provider.mjs +88 -0
- package/core/autonomous-audit.mjs +214 -0
- package/core/checkpoint.mjs +448 -0
- package/core/codebase-map.mjs +886 -0
- package/core/compatibility.json +16 -0
- package/core/compatibility.mjs +123 -0
- package/core/context-cache.mjs +113 -0
- package/core/context-compiler.mjs +1315 -0
- package/core/evidence-capture.mjs +347 -0
- package/core/git-utils.mjs +167 -0
- package/core/handoff.mjs +815 -0
- package/core/json-schema-lite.mjs +119 -0
- package/core/mcp-init.mjs +251 -0
- package/core/mcp-server.mjs +915 -0
- package/core/operation-approval.mjs +102 -0
- package/core/path-safety.mjs +508 -0
- package/core/project-locator.mjs +231 -0
- package/core/project-lock.mjs +438 -0
- package/core/project-status.mjs +635 -0
- package/core/project-validator.mjs +544 -0
- package/core/promotion.mjs +90 -0
- package/core/runtime-files.mjs +40 -0
- package/core/skills-history.mjs +572 -0
- package/core/skills-lifecycle.mjs +2225 -0
- package/core/skills-lint.mjs +365 -0
- package/core/skills.mjs +1449 -0
- package/core/staging-audit.mjs +454 -0
- package/core/staging-evidence.mjs +127 -0
- package/core/task-manager.mjs +1044 -0
- package/core/template-utils.mjs +190 -0
- package/core/text-utils.mjs +48 -0
- package/core/verify-task.mjs +48 -0
- package/core/worktrees.mjs +64 -0
- package/core/yaml-subset.mjs +572 -0
- package/package.json +50 -4
- package/policies/approval-boundaries.md +42 -0
- package/policies/memory-policy.md +53 -0
- package/policies/token-efficiency.md +30 -0
- package/schemas/README.md +43 -0
- package/schemas/adr.schema.json +64 -0
- package/schemas/agent-handoff.schema.json +139 -0
- package/schemas/approval-record.schema.json +110 -0
- package/schemas/conflict-record.schema.json +60 -0
- package/schemas/context-pack-manifest.schema.json +194 -0
- package/schemas/evidence-manifest.schema.json +83 -0
- package/schemas/incident-record.schema.json +53 -0
- package/schemas/project-manifest.schema.json +90 -0
- package/schemas/project-state.schema.json +64 -0
- package/schemas/recovery-checkpoint.schema.json +49 -0
- package/schemas/research-record.schema.json +76 -0
- package/schemas/task-contract.schema.json +95 -0
- package/scripts/bootstrap-project.mjs +357 -0
- package/scripts/geloforge.mjs +2512 -0
- package/templates/profiles/README.md +19 -0
- package/templates/profiles/ai-system/brain/profile.md +21 -0
- package/templates/profiles/ai-system/gitignore.append +5 -0
- package/templates/profiles/ai-system/profile.json +6 -0
- package/templates/profiles/automation/brain/profile.md +19 -0
- package/templates/profiles/automation/gitignore.append +5 -0
- package/templates/profiles/automation/profile.json +6 -0
- package/templates/profiles/desktop/brain/profile.md +21 -0
- package/templates/profiles/desktop/gitignore.append +7 -0
- package/templates/profiles/desktop/profile.json +6 -0
- package/templates/profiles/mobile/brain/profile.md +20 -0
- package/templates/profiles/mobile/gitignore.append +8 -0
- package/templates/profiles/mobile/profile.json +6 -0
- package/templates/profiles/web/brain/profile.md +21 -0
- package/templates/profiles/web/gitignore.append +6 -0
- package/templates/profiles/web/profile.json +6 -0
- package/templates/project-starter/AGENTS.md +27 -0
- package/templates/project-starter/GEMINI.md +16 -0
- package/templates/project-starter/README.md +26 -0
- package/templates/project-starter/brain/INDEX.md +40 -0
- package/templates/project-starter/brain/architecture/overview.md +30 -0
- package/templates/project-starter/brain/decisions/.gitkeep +0 -0
- package/templates/project-starter/brain/manifest.yaml +36 -0
- package/templates/project-starter/brain/requirements/constraints.md +29 -0
- package/templates/project-starter/brain/requirements/prd.md +37 -0
- package/templates/project-starter/brain/state/current.yaml +19 -0
- package/templates/project-starter/gitignore.template +25 -0
- package/templates/project-starter/src/.gitkeep +0 -0
- package/templates/project-starter/tasks/.gitkeep +0 -0
- package/templates/project-starter/tests/.gitkeep +0 -0
|
@@ -0,0 +1,1044 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Task Contract manager (create, list, show) for GeloForge projects.
|
|
3
|
+
* Enforces strict schema validation, duplicate-ID checks, and atomic writes.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import fs from "node:fs";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
import { fileURLToPath } from "node:url";
|
|
9
|
+
import {
|
|
10
|
+
assertSafeWithinRoot,
|
|
11
|
+
atomicWriteFile,
|
|
12
|
+
deriveSlug,
|
|
13
|
+
hasSecretContent,
|
|
14
|
+
isForbiddenSecretPath,
|
|
15
|
+
validateScalarText,
|
|
16
|
+
walkNonSymlinkFiles,
|
|
17
|
+
} from "./path-safety.mjs";
|
|
18
|
+
import { parseYaml, serializeYaml } from "./yaml-subset.mjs";
|
|
19
|
+
import { validateAgainstSchema } from "./json-schema-lite.mjs";
|
|
20
|
+
import { loadProjectManifestAndState, scanAndAllocateRecordId } from "./project-locator.mjs";
|
|
21
|
+
import { runMultiFileTransaction, sleepSyncMs, withProjectLock } from "./project-lock.mjs";
|
|
22
|
+
import { validateCreatedAt } from "./template-utils.mjs";
|
|
23
|
+
|
|
24
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
25
|
+
const __dirname = path.dirname(__filename);
|
|
26
|
+
const DEFAULT_HARNESS_DIR = path.resolve(__dirname, "..");
|
|
27
|
+
|
|
28
|
+
const ALLOWED_TASK_STATUSES = new Set(["inbox", "ready", "active", "in_review", "blocked", "completed", "cancelled"]);
|
|
29
|
+
const ALLOWED_PRIORITIES = new Set(["low", "medium", "high", "critical"]);
|
|
30
|
+
const ALLOWED_ROLES = new Set([
|
|
31
|
+
"orchestrator",
|
|
32
|
+
"researcher",
|
|
33
|
+
"software-architect",
|
|
34
|
+
"developer",
|
|
35
|
+
"qa-security-reviewer",
|
|
36
|
+
]);
|
|
37
|
+
const ALLOWED_BUDGETS = new Set(["quick", "working", "deep"]);
|
|
38
|
+
|
|
39
|
+
function normalizeTextList(raw, fieldName, { allowEmpty = true } = {}) {
|
|
40
|
+
if (raw === undefined || raw === null) {
|
|
41
|
+
return [];
|
|
42
|
+
}
|
|
43
|
+
const arr = Array.isArray(raw) ? raw : [raw];
|
|
44
|
+
const out = [];
|
|
45
|
+
for (const item of arr) {
|
|
46
|
+
const clean = validateScalarText(fieldName, item);
|
|
47
|
+
if (hasSecretContent(clean)) {
|
|
48
|
+
throw new Error(`Refusing credential-like content in ${fieldName}.`);
|
|
49
|
+
}
|
|
50
|
+
out.push(clean);
|
|
51
|
+
}
|
|
52
|
+
if (!allowEmpty && out.length === 0) {
|
|
53
|
+
throw new Error(`${fieldName} must contain at least one item.`);
|
|
54
|
+
}
|
|
55
|
+
return out;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Creates a schema-valid TASK-NNNN contract in manifest.paths.tasks_dir and optionally activates it.
|
|
60
|
+
*/
|
|
61
|
+
export function createTask(options = {}) {
|
|
62
|
+
const harnessDir = path.resolve(options.harnessDir || DEFAULT_HARNESS_DIR);
|
|
63
|
+
if (typeof options.projectDir !== "string" || options.projectDir.trim().length === 0) {
|
|
64
|
+
throw new Error("Missing required project directory (--project <path>).");
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const executeCreate = () => {
|
|
68
|
+
const loaded = loadProjectManifestAndState(options.projectDir, harnessDir);
|
|
69
|
+
const { projectDir, schemasDir, manifest, state, stateSchema, stateFilePath, projectPaths } = loaded;
|
|
70
|
+
|
|
71
|
+
const title = validateScalarText("--title", options.title);
|
|
72
|
+
if (title.length < 3) {
|
|
73
|
+
throw new Error("--title must be at least 3 characters.");
|
|
74
|
+
}
|
|
75
|
+
if (hasSecretContent(title)) {
|
|
76
|
+
throw new Error("Refusing credential-like content in --title.");
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const activate = Boolean(options.activate);
|
|
80
|
+
const status = (options.status ? String(options.status).trim() : activate ? "active" : "ready").toLowerCase();
|
|
81
|
+
if (!ALLOWED_TASK_STATUSES.has(status)) {
|
|
82
|
+
throw new Error(`Invalid task status "${status}". Expected one of: ${Array.from(ALLOWED_TASK_STATUSES).join(", ")}`);
|
|
83
|
+
}
|
|
84
|
+
if (activate && (status === "completed" || status === "cancelled")) {
|
|
85
|
+
throw new Error(`Cannot --activate a task created with terminal status "${status}".`);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const priority = (options.priority || "medium").trim().toLowerCase();
|
|
89
|
+
if (!ALLOWED_PRIORITIES.has(priority)) {
|
|
90
|
+
throw new Error(`Invalid --priority "${priority}". Expected: low, medium, high, critical.`);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const assignedRole = (options.assignedRole || "developer").trim();
|
|
94
|
+
if (!ALLOWED_ROLES.has(assignedRole)) {
|
|
95
|
+
throw new Error(`Invalid --role "${assignedRole}". Expected one of: ${Array.from(ALLOWED_ROLES).join(", ")}`);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const contextBudget = (options.contextBudget || "working").trim().toLowerCase();
|
|
99
|
+
if (!ALLOWED_BUDGETS.has(contextBudget)) {
|
|
100
|
+
throw new Error(`Invalid --budget "${contextBudget}". Expected: quick, working, deep.`);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const objective = validateScalarText("--objective", options.objective ?? title);
|
|
104
|
+
if (hasSecretContent(objective)) {
|
|
105
|
+
throw new Error("Refusing credential-like content in --objective.");
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const createdBy = validateScalarText("--created-by", options.createdBy ?? manifest.owner ?? "developer");
|
|
109
|
+
const createdAt = validateCreatedAt(options.createdAt);
|
|
110
|
+
|
|
111
|
+
const scopeIn = normalizeTextList(options.scopeIn, "--scope-in");
|
|
112
|
+
const scopeOut = normalizeTextList(options.scopeOut, "--scope-out");
|
|
113
|
+
const expectedOutputs = normalizeTextList(options.expectedOutputs, "--expected-output");
|
|
114
|
+
const criteriaInput = normalizeTextList(options.acceptanceCriteria, "--criteria");
|
|
115
|
+
const acceptanceCriteria =
|
|
116
|
+
criteriaInput.length > 0
|
|
117
|
+
? criteriaInput
|
|
118
|
+
: [`Verify "${title}" with recorded command-backed evidence before handoff.`];
|
|
119
|
+
|
|
120
|
+
const dependencies = [];
|
|
121
|
+
for (const dep of normalizeTextList(options.dependencies, "--dep")) {
|
|
122
|
+
const up = dep.toUpperCase();
|
|
123
|
+
if (!/^TASK-\d{4}$/.test(up)) {
|
|
124
|
+
throw new Error(`Invalid dependency task ID "${dep}". Expected TASK-NNNN.`);
|
|
125
|
+
}
|
|
126
|
+
dependencies.push(up);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const requiredInputs = [];
|
|
130
|
+
for (const rawInput of normalizeTextList(options.requiredInputs, "--input")) {
|
|
131
|
+
const norm = rawInput.replace(/\\/g, "/");
|
|
132
|
+
if (isForbiddenSecretPath(norm)) {
|
|
133
|
+
throw new Error(`Refusing secret path in --input: "${rawInput}".`);
|
|
134
|
+
}
|
|
135
|
+
const target = assertSafeWithinRoot(projectDir, norm);
|
|
136
|
+
if (!fs.existsSync(target) || !fs.lstatSync(target).isFile()) {
|
|
137
|
+
throw new Error(`Referenced --input file does not exist or is not a regular file: "${norm}".`);
|
|
138
|
+
}
|
|
139
|
+
requiredInputs.push({ path: norm, revision: "working-tree" });
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const { id, existingIds } = scanAndAllocateRecordId({
|
|
143
|
+
projectDir,
|
|
144
|
+
searchDirs: [projectPaths.tasks_dir, projectPaths.proposals_dir],
|
|
145
|
+
prefix: "TASK",
|
|
146
|
+
explicitId: options.id ?? null,
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
for (const dep of dependencies) {
|
|
150
|
+
if (!existingIds.has(dep)) {
|
|
151
|
+
throw new Error(`Dependency task "${dep}" does not exist in ${projectPaths.tasks_dir}.`);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const slug = deriveSlug(title) || "task";
|
|
156
|
+
const relPath = `${projectPaths.tasks_dir}/${id}-${slug.slice(0, 42)}.yaml`;
|
|
157
|
+
const filePath = assertSafeWithinRoot(projectDir, relPath);
|
|
158
|
+
if (fs.existsSync(filePath)) {
|
|
159
|
+
throw new Error(`Refusing to overwrite existing task file: ${filePath}`);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const record = {
|
|
163
|
+
schema_version: "1.1",
|
|
164
|
+
id,
|
|
165
|
+
title,
|
|
166
|
+
project_id: manifest.project_id,
|
|
167
|
+
status,
|
|
168
|
+
memory_layer: "L2_OPERATIONAL",
|
|
169
|
+
authority_level: "A4",
|
|
170
|
+
priority,
|
|
171
|
+
assigned_role: assignedRole,
|
|
172
|
+
created_by: createdBy,
|
|
173
|
+
created_at: createdAt,
|
|
174
|
+
updated_at: createdAt,
|
|
175
|
+
objective,
|
|
176
|
+
scope_in: scopeIn,
|
|
177
|
+
scope_out: scopeOut,
|
|
178
|
+
required_inputs: requiredInputs,
|
|
179
|
+
expected_outputs: expectedOutputs,
|
|
180
|
+
acceptance_criteria: acceptanceCriteria,
|
|
181
|
+
dependencies,
|
|
182
|
+
approval_required: false,
|
|
183
|
+
approval_ref: null,
|
|
184
|
+
context_budget: contextBudget,
|
|
185
|
+
max_retries: 2,
|
|
186
|
+
evidence_refs: [],
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
const taskSchema = JSON.parse(fs.readFileSync(path.join(schemasDir, "task-contract.schema.json"), "utf8"));
|
|
190
|
+
const schemaCheck = validateAgainstSchema(record, taskSchema);
|
|
191
|
+
if (!schemaCheck.valid) {
|
|
192
|
+
throw new Error(`Task failed schema validation: ${schemaCheck.errors.join("; ")}`);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const yamlText = serializeYaml(record, { headerComment: `Task Contract ${id}` });
|
|
196
|
+
const tasksDirAbs = assertSafeWithinRoot(projectDir, projectPaths.tasks_dir);
|
|
197
|
+
if (fs.existsSync(tasksDirAbs) && fs.lstatSync(tasksDirAbs).isSymbolicLink()) {
|
|
198
|
+
throw new Error(`Refusing symbolic link tasks directory: ${tasksDirAbs}`);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
let updatedState = null;
|
|
202
|
+
if (activate) {
|
|
203
|
+
const activeTasks = Array.isArray(state.active_tasks) ? [...state.active_tasks] : [];
|
|
204
|
+
if (!activeTasks.includes(id)) activeTasks.push(id);
|
|
205
|
+
const blockedTasks = (state.blocked_tasks || []).filter((t) => t !== id);
|
|
206
|
+
updatedState = {
|
|
207
|
+
...state,
|
|
208
|
+
state_revision: (state.state_revision ?? 0) + 1,
|
|
209
|
+
status: state.status === "initialized" ? "active" : state.status,
|
|
210
|
+
updated_at: createdAt,
|
|
211
|
+
current_phase: state.current_phase === "initialization" || state.current_phase === "adoption" ? "implementation" : state.current_phase,
|
|
212
|
+
active_tasks: activeTasks,
|
|
213
|
+
blocked_tasks: blockedTasks,
|
|
214
|
+
};
|
|
215
|
+
const stCheck = validateAgainstSchema(updatedState, stateSchema);
|
|
216
|
+
if (!stCheck.valid) {
|
|
217
|
+
throw new Error(`Updated operational state failed schema validation: ${stCheck.errors.join("; ")}`);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
const dryRun = Boolean(options.dryRun);
|
|
222
|
+
if (!dryRun) {
|
|
223
|
+
const txSteps = [{ label: "task", filePath, content: yamlText, allowOverwrite: false }];
|
|
224
|
+
if (updatedState) {
|
|
225
|
+
const stateYaml = serializeYaml(updatedState, { headerComment: "Current Operational Project State" });
|
|
226
|
+
txSteps.push({ label: "state", filePath: stateFilePath, content: stateYaml, allowOverwrite: true });
|
|
227
|
+
}
|
|
228
|
+
runMultiFileTransaction(txSteps, { projectDir, faultHook: options._faultHook });
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
return {
|
|
232
|
+
dryRun,
|
|
233
|
+
id,
|
|
234
|
+
relPath,
|
|
235
|
+
filePath,
|
|
236
|
+
activated: activate,
|
|
237
|
+
record,
|
|
238
|
+
yaml: yamlText,
|
|
239
|
+
};
|
|
240
|
+
};
|
|
241
|
+
|
|
242
|
+
if (options.dryRun) {
|
|
243
|
+
return executeCreate();
|
|
244
|
+
}
|
|
245
|
+
return withProjectLock(options.projectDir, executeCreate, {
|
|
246
|
+
lockTimeoutMs: options.lockTimeoutMs,
|
|
247
|
+
staleLockMs: options.staleLockMs,
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* Lists schema-valid TASK-NNNN records under manifest.paths.tasks_dir.
|
|
253
|
+
*/
|
|
254
|
+
export function listTasks({ projectDir, status = null, harnessDir = DEFAULT_HARNESS_DIR }) {
|
|
255
|
+
const loaded = loadProjectManifestAndState(projectDir, harnessDir);
|
|
256
|
+
const tasksDirAbs = assertSafeWithinRoot(loaded.projectDir, loaded.projectPaths.tasks_dir);
|
|
257
|
+
const taskSchema = JSON.parse(fs.readFileSync(path.join(loaded.schemasDir, "task-contract.schema.json"), "utf8"));
|
|
258
|
+
const filterStatus = status ? status.trim().toLowerCase() : null;
|
|
259
|
+
|
|
260
|
+
if (!fs.existsSync(tasksDirAbs)) {
|
|
261
|
+
return { projectDir: loaded.projectDir, tasksDir: loaded.projectPaths.tasks_dir, tasks: [] };
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
const files = walkNonSymlinkFiles(loaded.projectDir, tasksDirAbs, (p) => /^TASK-\d{4}.*\.ya?ml$/i.test(path.basename(p)));
|
|
265
|
+
const tasks = [];
|
|
266
|
+
for (const filePath of files) {
|
|
267
|
+
const relPath = path.relative(loaded.projectDir, filePath).replace(/\\/g, "/");
|
|
268
|
+
try {
|
|
269
|
+
const data = parseYaml(fs.readFileSync(filePath, "utf8"), relPath);
|
|
270
|
+
if (data?.is_example) continue;
|
|
271
|
+
if (!validateAgainstSchema(data, taskSchema).valid) continue;
|
|
272
|
+
if (filterStatus && data.status !== filterStatus) continue;
|
|
273
|
+
tasks.push({
|
|
274
|
+
id: data.id,
|
|
275
|
+
title: data.title,
|
|
276
|
+
status: data.status,
|
|
277
|
+
priority: data.priority,
|
|
278
|
+
assignedRole: data.assigned_role,
|
|
279
|
+
contextBudget: data.context_budget,
|
|
280
|
+
evidenceCount: (data.evidence_refs || []).length,
|
|
281
|
+
relPath,
|
|
282
|
+
activeInState: (loaded.state.active_tasks || []).includes(data.id),
|
|
283
|
+
});
|
|
284
|
+
} catch {
|
|
285
|
+
// Ignore malformed non-task files during list
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
tasks.sort((a, b) => a.id.localeCompare(b.id));
|
|
290
|
+
return {
|
|
291
|
+
projectDir: loaded.projectDir,
|
|
292
|
+
tasksDir: loaded.projectPaths.tasks_dir,
|
|
293
|
+
tasks,
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* Checks whether two file-scope strings/globs overlap (exact, parent/child, or wildcard).
|
|
299
|
+
*/
|
|
300
|
+
export function scopesOverlap(scopeA, scopeB) {
|
|
301
|
+
const norm = (raw) =>
|
|
302
|
+
String(raw || "")
|
|
303
|
+
.trim()
|
|
304
|
+
.replace(/\\/g, "/")
|
|
305
|
+
.replace(/^\.\//, "")
|
|
306
|
+
.replace(/\/\*\*$/, "")
|
|
307
|
+
.replace(/\/\*$/, "")
|
|
308
|
+
.replace(/\/+$/, "");
|
|
309
|
+
const a = norm(scopeA);
|
|
310
|
+
const b = norm(scopeB);
|
|
311
|
+
if (a === "" || a === "*" || a === "." || b === "" || b === "*" || b === ".") {
|
|
312
|
+
return true;
|
|
313
|
+
}
|
|
314
|
+
return a === b || a.startsWith(`${b}/`) || b.startsWith(`${a}/`);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
export const TASK_LEASES_PATH = ".geloforge/task-leases.yaml";
|
|
318
|
+
|
|
319
|
+
function readLeasesFile(projectDir) {
|
|
320
|
+
const leasesRelPath = TASK_LEASES_PATH;
|
|
321
|
+
const leasesAbs = assertSafeWithinRoot(projectDir, leasesRelPath);
|
|
322
|
+
if (!fs.existsSync(leasesAbs)) {
|
|
323
|
+
return { leasesRelPath, leasesAbs, exists: false, leases: [] };
|
|
324
|
+
}
|
|
325
|
+
const st = fs.lstatSync(leasesAbs);
|
|
326
|
+
if (st.isSymbolicLink() || !st.isFile()) {
|
|
327
|
+
throw new Error(`Refusing symbolic link or non-regular lease registry: ${leasesRelPath}`);
|
|
328
|
+
}
|
|
329
|
+
const raw = fs.readFileSync(leasesAbs, "utf8");
|
|
330
|
+
if (hasSecretContent(raw)) {
|
|
331
|
+
throw new Error(`Blocked credential-like pattern in ${leasesRelPath}.`);
|
|
332
|
+
}
|
|
333
|
+
const parsed = parseYaml(raw, leasesRelPath);
|
|
334
|
+
const leases = Array.isArray(parsed?.leases) ? parsed.leases : [];
|
|
335
|
+
return { leasesRelPath, leasesAbs, exists: true, leases };
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* Lists active and expired cooperative task/scope leases under `.geloforge/task-leases.yaml`.
|
|
340
|
+
*/
|
|
341
|
+
export function listTaskLeases({
|
|
342
|
+
projectDir,
|
|
343
|
+
nowIso = new Date().toISOString(),
|
|
344
|
+
includeExpired = false,
|
|
345
|
+
harnessDir = DEFAULT_HARNESS_DIR,
|
|
346
|
+
} = {}) {
|
|
347
|
+
const loaded = loadProjectManifestAndState(projectDir, harnessDir);
|
|
348
|
+
const nowMs = Date.parse(validateCreatedAt(nowIso));
|
|
349
|
+
const { leasesRelPath, leases } = readLeasesFile(loaded.projectDir);
|
|
350
|
+
|
|
351
|
+
const activeLeases = [];
|
|
352
|
+
const expiredLeases = [];
|
|
353
|
+
for (const entry of leases) {
|
|
354
|
+
if (!entry || typeof entry !== "object" || typeof entry.task_id !== "string") continue;
|
|
355
|
+
const expMs = Date.parse(String(entry.expires_at || ""));
|
|
356
|
+
if (Number.isFinite(expMs) && expMs > nowMs) {
|
|
357
|
+
activeLeases.push(entry);
|
|
358
|
+
} else {
|
|
359
|
+
expiredLeases.push(entry);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
activeLeases.sort((a, b) => a.task_id.localeCompare(b.task_id));
|
|
363
|
+
expiredLeases.sort((a, b) => a.task_id.localeCompare(b.task_id));
|
|
364
|
+
|
|
365
|
+
return {
|
|
366
|
+
projectDir: loaded.projectDir,
|
|
367
|
+
leasesRelPath,
|
|
368
|
+
activeLeases,
|
|
369
|
+
expiredLeases,
|
|
370
|
+
leases: includeExpired ? [...activeLeases, ...expiredLeases] : activeLeases,
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
function indexEvidenceById(projectDir, projectPaths, schemasDir) {
|
|
375
|
+
const evidDirRel = String(projectPaths.evidence_dir || "evidence").replace(/\\/g, "/");
|
|
376
|
+
const evidDirAbs = assertSafeWithinRoot(projectDir, evidDirRel);
|
|
377
|
+
const byId = new Map();
|
|
378
|
+
if (!fs.existsSync(evidDirAbs)) {
|
|
379
|
+
return byId;
|
|
380
|
+
}
|
|
381
|
+
const evSchema = JSON.parse(fs.readFileSync(path.join(schemasDir, "evidence-manifest.schema.json"), "utf8"));
|
|
382
|
+
const files = walkNonSymlinkFiles(projectDir, evidDirAbs, (p) => /^EVID-\d{4}.*\.ya?ml$/i.test(path.basename(p)));
|
|
383
|
+
for (const absFile of files) {
|
|
384
|
+
const rel = path.relative(projectDir, absFile).replace(/\\/g, "/");
|
|
385
|
+
try {
|
|
386
|
+
const raw = fs.readFileSync(absFile, "utf8");
|
|
387
|
+
if (hasSecretContent(raw)) {
|
|
388
|
+
continue;
|
|
389
|
+
}
|
|
390
|
+
const data = parseYaml(raw, rel);
|
|
391
|
+
if (!data || typeof data.id !== "string") continue;
|
|
392
|
+
const schemaRes = validateAgainstSchema(data, evSchema);
|
|
393
|
+
const checks = Array.isArray(data.checks) ? data.checks : [];
|
|
394
|
+
const passed = checks.filter((c) => c.result === "passed").length;
|
|
395
|
+
const failedOrBlocked = checks.filter((c) => c.result === "failed" || c.result === "blocked").length;
|
|
396
|
+
const isVerified =
|
|
397
|
+
schemaRes.valid &&
|
|
398
|
+
data.is_example !== true &&
|
|
399
|
+
data.status === "verified" &&
|
|
400
|
+
checks.length > 0 &&
|
|
401
|
+
passed > 0 &&
|
|
402
|
+
failedOrBlocked === 0;
|
|
403
|
+
let reason = "verified";
|
|
404
|
+
if (!schemaRes.valid) reason = `schema invalid (${schemaRes.errors.join("; ")})`;
|
|
405
|
+
else if (data.is_example === true) reason = "is_example fixture";
|
|
406
|
+
else if (data.status !== "verified") reason = `status="${data.status}" (expected "verified")`;
|
|
407
|
+
else if (passed === 0 || failedOrBlocked > 0) reason = `checks passed=${passed}, failed/blocked=${failedOrBlocked}`;
|
|
408
|
+
byId.set(data.id.trim().toUpperCase(), { id: data.id.trim().toUpperCase(), relPath: rel, isVerified, reason });
|
|
409
|
+
} catch (err) {
|
|
410
|
+
const idMatch = path.basename(rel).match(/^(EVID-\d{4})/i);
|
|
411
|
+
if (idMatch) {
|
|
412
|
+
byId.set(idMatch[1].toUpperCase(), {
|
|
413
|
+
id: idMatch[1].toUpperCase(),
|
|
414
|
+
relPath: rel,
|
|
415
|
+
isVerified: false,
|
|
416
|
+
reason: `unreadable YAML (${err.message})`,
|
|
417
|
+
});
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
return byId;
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
export function verifyTaskEvidenceRefs({
|
|
425
|
+
projectDir,
|
|
426
|
+
projectPaths,
|
|
427
|
+
schemasDir,
|
|
428
|
+
evidenceRefs = [],
|
|
429
|
+
strictExplicit = false,
|
|
430
|
+
}) {
|
|
431
|
+
const byId = indexEvidenceById(projectDir, projectPaths, schemasDir);
|
|
432
|
+
const verifiedIds = [];
|
|
433
|
+
const unverifiedIds = [];
|
|
434
|
+
const reasons = [];
|
|
435
|
+
const seen = new Set();
|
|
436
|
+
|
|
437
|
+
for (const rawId of evidenceRefs) {
|
|
438
|
+
const clean = String(rawId || "").trim().toUpperCase();
|
|
439
|
+
if (!/^EVID-\d{4}$/.test(clean)) {
|
|
440
|
+
if (strictExplicit) {
|
|
441
|
+
throw new Error(`Invalid evidence ID "${rawId}". Expected EVID-NNNN.`);
|
|
442
|
+
}
|
|
443
|
+
continue;
|
|
444
|
+
}
|
|
445
|
+
if (seen.has(clean)) continue;
|
|
446
|
+
seen.add(clean);
|
|
447
|
+
|
|
448
|
+
const entry = byId.get(clean);
|
|
449
|
+
if (!entry) {
|
|
450
|
+
const msg = `${clean} not found under ${projectPaths.evidence_dir}/`;
|
|
451
|
+
if (strictExplicit) {
|
|
452
|
+
throw new Error(`Refusing to link unverified or missing evidence ${clean} (${msg}).`);
|
|
453
|
+
}
|
|
454
|
+
unverifiedIds.push(clean);
|
|
455
|
+
reasons.push(msg);
|
|
456
|
+
continue;
|
|
457
|
+
}
|
|
458
|
+
if (!entry.isVerified) {
|
|
459
|
+
const msg = `${clean} (${entry.relPath}): ${entry.reason}`;
|
|
460
|
+
if (strictExplicit) {
|
|
461
|
+
throw new Error(`Refusing to link unverified evidence ${msg}.`);
|
|
462
|
+
}
|
|
463
|
+
unverifiedIds.push(clean);
|
|
464
|
+
reasons.push(msg);
|
|
465
|
+
continue;
|
|
466
|
+
}
|
|
467
|
+
verifiedIds.push(clean);
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
return { verifiedIds, unverifiedIds, reasons };
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
/**
|
|
474
|
+
* Releases a cooperative lease for `taskId` from `.geloforge/task-leases.yaml` (and prunes expired leases).
|
|
475
|
+
* Requires matching advisory `--tool` or `--session` confirmation (or `--force`) when an active lease exists.
|
|
476
|
+
*/
|
|
477
|
+
export function releaseTaskLease({
|
|
478
|
+
projectDir,
|
|
479
|
+
taskId,
|
|
480
|
+
tool = null,
|
|
481
|
+
sessionId = null,
|
|
482
|
+
role = null,
|
|
483
|
+
force = false,
|
|
484
|
+
nowIso = new Date().toISOString(),
|
|
485
|
+
dryRun = false,
|
|
486
|
+
harnessDir = DEFAULT_HARNESS_DIR,
|
|
487
|
+
lockTimeoutMs,
|
|
488
|
+
staleLockMs,
|
|
489
|
+
} = {}) {
|
|
490
|
+
if (typeof projectDir !== "string" || projectDir.trim().length === 0) {
|
|
491
|
+
throw new Error("Missing required project directory (--project <path>).");
|
|
492
|
+
}
|
|
493
|
+
if (typeof taskId !== "string" || !/^TASK-\d{4}$/i.test(taskId.trim())) {
|
|
494
|
+
throw new Error(`Invalid task ID "${taskId}". Expected TASK-NNNN.`);
|
|
495
|
+
}
|
|
496
|
+
const cleanId = taskId.trim().toUpperCase();
|
|
497
|
+
|
|
498
|
+
const run = () => {
|
|
499
|
+
const loaded = loadProjectManifestAndState(projectDir, harnessDir);
|
|
500
|
+
const tsIso = validateCreatedAt(nowIso);
|
|
501
|
+
const nowMs = Date.parse(tsIso);
|
|
502
|
+
const { leasesRelPath, leasesAbs, exists, leases } = readLeasesFile(loaded.projectDir);
|
|
503
|
+
|
|
504
|
+
if (!exists) {
|
|
505
|
+
return {
|
|
506
|
+
dryRun: Boolean(dryRun),
|
|
507
|
+
released: false,
|
|
508
|
+
taskId: cleanId,
|
|
509
|
+
leasesRelPath,
|
|
510
|
+
identityModel: "advisory_self_declared",
|
|
511
|
+
releasedLease: null,
|
|
512
|
+
releasedByOverride: false,
|
|
513
|
+
activeLeases: [],
|
|
514
|
+
};
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
const callerTool = typeof tool === "string" && tool.trim() ? tool.trim() : null;
|
|
518
|
+
const callerSession = typeof sessionId === "string" && sessionId.trim() ? sessionId.trim() : null;
|
|
519
|
+
const callerRole = typeof role === "string" && role.trim() ? role.trim() : null;
|
|
520
|
+
|
|
521
|
+
let removed = false;
|
|
522
|
+
let releasedLease = null;
|
|
523
|
+
const remaining = [];
|
|
524
|
+
for (const entry of leases) {
|
|
525
|
+
if (!entry || typeof entry !== "object") continue;
|
|
526
|
+
const expMs = Date.parse(String(entry.expires_at || ""));
|
|
527
|
+
const isActive = Number.isFinite(expMs) && expMs > nowMs;
|
|
528
|
+
if (entry.task_id === cleanId) {
|
|
529
|
+
if (isActive && !force) {
|
|
530
|
+
if (!callerTool && !callerSession) {
|
|
531
|
+
throw new Error(
|
|
532
|
+
`Refusing unverified lease release on ${cleanId}: active lease is held by tool "${entry.tool}" (session "${entry.session_id}", role "${entry.role}"). Pass matching --tool or --session to confirm cooperative ownership, or pass --force.`
|
|
533
|
+
);
|
|
534
|
+
}
|
|
535
|
+
if (callerTool && callerTool !== entry.tool) {
|
|
536
|
+
throw new Error(
|
|
537
|
+
`Lease ownership mismatch on ${cleanId}: active lease is held by tool "${entry.tool}" (session "${entry.session_id}"), not tool "${callerTool}". Pass --force to override.`
|
|
538
|
+
);
|
|
539
|
+
}
|
|
540
|
+
if (callerSession && callerSession !== entry.session_id) {
|
|
541
|
+
throw new Error(
|
|
542
|
+
`Lease ownership mismatch on ${cleanId}: active lease is held by session "${entry.session_id}" (tool "${entry.tool}"), not session "${callerSession}". Pass --force to override.`
|
|
543
|
+
);
|
|
544
|
+
}
|
|
545
|
+
if (callerRole && callerRole !== entry.role) {
|
|
546
|
+
throw new Error(
|
|
547
|
+
`Lease ownership mismatch on ${cleanId}: active lease is held by role "${entry.role}" (tool "${entry.tool}"), not role "${callerRole}". Pass --force to override.`
|
|
548
|
+
);
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
removed = true;
|
|
552
|
+
releasedLease = entry;
|
|
553
|
+
continue;
|
|
554
|
+
}
|
|
555
|
+
if (isActive) {
|
|
556
|
+
remaining.push(entry);
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
if (!dryRun) {
|
|
561
|
+
const payload = {
|
|
562
|
+
schema_version: "1.0",
|
|
563
|
+
updated_at: tsIso,
|
|
564
|
+
leases: remaining,
|
|
565
|
+
};
|
|
566
|
+
atomicWriteFile(
|
|
567
|
+
leasesAbs,
|
|
568
|
+
serializeYaml(payload, { headerComment: "Cooperative multi-IDE task & scope leases (advisory collision avoidance)" }),
|
|
569
|
+
{ allowOverwrite: true }
|
|
570
|
+
);
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
return {
|
|
574
|
+
dryRun: Boolean(dryRun),
|
|
575
|
+
released: removed,
|
|
576
|
+
taskId: cleanId,
|
|
577
|
+
leasesRelPath,
|
|
578
|
+
identityModel: "advisory_self_declared",
|
|
579
|
+
releasedLease,
|
|
580
|
+
releasedByOverride: Boolean(force && releasedLease),
|
|
581
|
+
activeLeases: remaining,
|
|
582
|
+
};
|
|
583
|
+
};
|
|
584
|
+
|
|
585
|
+
if (dryRun) {
|
|
586
|
+
return run();
|
|
587
|
+
}
|
|
588
|
+
return withProjectLock(projectDir, run, { lockTimeoutMs, staleLockMs });
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
function prepareTaskUpdatePlan({
|
|
592
|
+
loaded,
|
|
593
|
+
taskInfo,
|
|
594
|
+
harnessDir,
|
|
595
|
+
status,
|
|
596
|
+
priority,
|
|
597
|
+
assignedRole,
|
|
598
|
+
activate = false,
|
|
599
|
+
evidenceRefs = [],
|
|
600
|
+
requireEvidence = false,
|
|
601
|
+
tool = null,
|
|
602
|
+
sessionId = null,
|
|
603
|
+
force = false,
|
|
604
|
+
updatedAt,
|
|
605
|
+
leaseStateOverride = null,
|
|
606
|
+
skipLeaseWrite = false,
|
|
607
|
+
}) {
|
|
608
|
+
const tStat = fs.lstatSync(taskInfo.filePath);
|
|
609
|
+
if (tStat.isSymbolicLink() || !tStat.isFile()) {
|
|
610
|
+
throw new Error(`Refusing symbolic link or non-regular task file: ${taskInfo.relPath}`);
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
const { projectDir, schemasDir, state, stateSchema, stateFilePath, projectPaths } = loaded;
|
|
614
|
+
const nextStatus = status
|
|
615
|
+
? String(status).trim().toLowerCase()
|
|
616
|
+
: activate
|
|
617
|
+
? "active"
|
|
618
|
+
: taskInfo.record.status;
|
|
619
|
+
if (!ALLOWED_TASK_STATUSES.has(nextStatus)) {
|
|
620
|
+
throw new Error(
|
|
621
|
+
`Invalid task status "${nextStatus}". Expected one of: ${Array.from(ALLOWED_TASK_STATUSES).join(", ")}`
|
|
622
|
+
);
|
|
623
|
+
}
|
|
624
|
+
if (activate && (nextStatus === "completed" || nextStatus === "cancelled")) {
|
|
625
|
+
throw new Error(`Cannot --activate a task with terminal status "${nextStatus}".`);
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
const nextPriority = priority ? String(priority).trim().toLowerCase() : taskInfo.record.priority;
|
|
629
|
+
if (!ALLOWED_PRIORITIES.has(nextPriority)) {
|
|
630
|
+
throw new Error(`Invalid --priority "${nextPriority}". Expected: low, medium, high, critical.`);
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
const nextRole = assignedRole ? String(assignedRole).trim() : taskInfo.record.assigned_role;
|
|
634
|
+
if (!ALLOWED_ROLES.has(nextRole)) {
|
|
635
|
+
throw new Error(`Invalid --role "${nextRole}". Expected one of: ${Array.from(ALLOWED_ROLES).join(", ")}`);
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
const timestamp = validateCreatedAt(updatedAt);
|
|
639
|
+
const warnings = [];
|
|
640
|
+
|
|
641
|
+
// Check active lease ownership before updating/closing task
|
|
642
|
+
const leaseState = leaseStateOverride || listTaskLeases({ projectDir, nowIso: timestamp, harnessDir });
|
|
643
|
+
const activeLease = (leaseState.activeLeases || []).find((l) => l.task_id === taskInfo.id) || null;
|
|
644
|
+
if (activeLease && !force) {
|
|
645
|
+
const callerTool = typeof tool === "string" && tool.trim() ? tool.trim() : null;
|
|
646
|
+
const callerSession = typeof sessionId === "string" && sessionId.trim() ? sessionId.trim() : null;
|
|
647
|
+
if (callerTool && callerTool !== activeLease.tool) {
|
|
648
|
+
throw new Error(
|
|
649
|
+
`Lease ownership mismatch on ${taskInfo.id}: active lease belongs to tool "${activeLease.tool}" (session "${activeLease.session_id}"), not "${callerTool}". Pass --force to override.`
|
|
650
|
+
);
|
|
651
|
+
}
|
|
652
|
+
if (callerSession && callerSession !== activeLease.session_id) {
|
|
653
|
+
throw new Error(
|
|
654
|
+
`Lease ownership mismatch on ${taskInfo.id}: active lease belongs to session "${activeLease.session_id}" (tool "${activeLease.tool}"), not "${callerSession}". Pass --force to override.`
|
|
655
|
+
);
|
|
656
|
+
}
|
|
657
|
+
if ((nextStatus === "completed" || nextStatus === "cancelled") && !callerTool && !callerSession) {
|
|
658
|
+
warnings.push(
|
|
659
|
+
`Auto-released active lease on ${taskInfo.id} (tool="${activeLease.tool}") without explicit --tool/--session confirmation.`
|
|
660
|
+
);
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
// Validate explicit evidence refs strictly, then compute overall task evidence truth
|
|
665
|
+
const explicitEvIds = normalizeTextList(evidenceRefs, "--evidence").map((s) => s.toUpperCase());
|
|
666
|
+
if (explicitEvIds.length > 0) {
|
|
667
|
+
verifyTaskEvidenceRefs({
|
|
668
|
+
projectDir,
|
|
669
|
+
projectPaths,
|
|
670
|
+
schemasDir,
|
|
671
|
+
evidenceRefs: explicitEvIds,
|
|
672
|
+
strictExplicit: true,
|
|
673
|
+
});
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
const mergedEvidenceRefs = Array.from(
|
|
677
|
+
new Set([...(Array.isArray(taskInfo.record.evidence_refs) ? taskInfo.record.evidence_refs : []), ...explicitEvIds])
|
|
678
|
+
);
|
|
679
|
+
|
|
680
|
+
const evidEval = verifyTaskEvidenceRefs({
|
|
681
|
+
projectDir,
|
|
682
|
+
projectPaths,
|
|
683
|
+
schemasDir,
|
|
684
|
+
evidenceRefs: mergedEvidenceRefs,
|
|
685
|
+
strictExplicit: false,
|
|
686
|
+
});
|
|
687
|
+
const verified = evidEval.verifiedIds.length > 0 && evidEval.unverifiedIds.length === 0;
|
|
688
|
+
const verificationStatus = verified ? "verified" : "unverified";
|
|
689
|
+
|
|
690
|
+
if (nextStatus === "completed") {
|
|
691
|
+
if (requireEvidence && !verified) {
|
|
692
|
+
throw new Error(
|
|
693
|
+
`Refusing to mark ${taskInfo.id} completed with --require-evidence: task lacks verified EVID-* evidence (${evidEval.reasons.join("; ") || "0 linked evidence records"}). Run "geloforge evidence capture --task ${taskInfo.id} -- <test-command>" first.`
|
|
694
|
+
);
|
|
695
|
+
}
|
|
696
|
+
if (!verified) {
|
|
697
|
+
warnings.push(
|
|
698
|
+
`Task ${taskInfo.id} marked completed without verified EVID-* evidence (verificationStatus="unverified"). Task completion alone is not verified test evidence.`
|
|
699
|
+
);
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
const updatedRecord = {
|
|
704
|
+
...taskInfo.record,
|
|
705
|
+
status: nextStatus,
|
|
706
|
+
priority: nextPriority,
|
|
707
|
+
assigned_role: nextRole,
|
|
708
|
+
evidence_refs: mergedEvidenceRefs,
|
|
709
|
+
updated_at: timestamp,
|
|
710
|
+
};
|
|
711
|
+
|
|
712
|
+
const taskSchema = JSON.parse(fs.readFileSync(path.join(schemasDir, "task-contract.schema.json"), "utf8"));
|
|
713
|
+
const schemaCheck = validateAgainstSchema(updatedRecord, taskSchema);
|
|
714
|
+
if (!schemaCheck.valid) {
|
|
715
|
+
throw new Error(`Updated task failed schema validation: ${schemaCheck.errors.join("; ")}`);
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
let activeTasks = Array.isArray(state.active_tasks) ? [...state.active_tasks] : [];
|
|
719
|
+
let blockedTasks = Array.isArray(state.blocked_tasks) ? [...state.blocked_tasks] : [];
|
|
720
|
+
let lastCompletedTask = state.last_completed_task ?? null;
|
|
721
|
+
|
|
722
|
+
if (nextStatus === "completed") {
|
|
723
|
+
activeTasks = activeTasks.filter((t) => t !== taskInfo.id);
|
|
724
|
+
blockedTasks = blockedTasks.filter((t) => t !== taskInfo.id);
|
|
725
|
+
lastCompletedTask = taskInfo.id;
|
|
726
|
+
} else if (nextStatus === "cancelled") {
|
|
727
|
+
activeTasks = activeTasks.filter((t) => t !== taskInfo.id);
|
|
728
|
+
blockedTasks = blockedTasks.filter((t) => t !== taskInfo.id);
|
|
729
|
+
} else if (nextStatus === "blocked") {
|
|
730
|
+
activeTasks = activeTasks.filter((t) => t !== taskInfo.id);
|
|
731
|
+
if (!blockedTasks.includes(taskInfo.id)) blockedTasks.push(taskInfo.id);
|
|
732
|
+
} else if (nextStatus === "active" || activate) {
|
|
733
|
+
if (!activeTasks.includes(taskInfo.id)) activeTasks.push(taskInfo.id);
|
|
734
|
+
blockedTasks = blockedTasks.filter((t) => t !== taskInfo.id);
|
|
735
|
+
if (lastCompletedTask === taskInfo.id) {
|
|
736
|
+
lastCompletedTask = null;
|
|
737
|
+
}
|
|
738
|
+
} else {
|
|
739
|
+
activeTasks = activeTasks.filter((t) => t !== taskInfo.id);
|
|
740
|
+
blockedTasks = blockedTasks.filter((t) => t !== taskInfo.id);
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
// Note: NEVER set state.last_verified_evidence from task done alone
|
|
744
|
+
const updatedState = {
|
|
745
|
+
...state,
|
|
746
|
+
state_revision: (state.state_revision ?? 0) + 1,
|
|
747
|
+
status: state.status === "initialized" && activeTasks.length > 0 ? "active" : state.status,
|
|
748
|
+
updated_at: timestamp,
|
|
749
|
+
active_tasks: activeTasks,
|
|
750
|
+
blocked_tasks: blockedTasks,
|
|
751
|
+
last_completed_task: lastCompletedTask,
|
|
752
|
+
};
|
|
753
|
+
const stCheck = validateAgainstSchema(updatedState, stateSchema);
|
|
754
|
+
if (!stCheck.valid) {
|
|
755
|
+
throw new Error(`Updated operational state failed schema validation: ${stCheck.errors.join("; ")}`);
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
const taskYaml = serializeYaml(updatedRecord, { headerComment: `Task Contract ${taskInfo.id}` });
|
|
759
|
+
const stateYaml = serializeYaml(updatedState, { headerComment: "Current Operational Project State" });
|
|
760
|
+
const steps = [
|
|
761
|
+
{ label: "task", filePath: taskInfo.filePath, content: taskYaml, allowOverwrite: true },
|
|
762
|
+
{ label: "state", filePath: stateFilePath, content: stateYaml, allowOverwrite: true },
|
|
763
|
+
];
|
|
764
|
+
|
|
765
|
+
if (!skipLeaseWrite && (nextStatus === "completed" || nextStatus === "cancelled")) {
|
|
766
|
+
const rawLeases = readLeasesFile(projectDir);
|
|
767
|
+
if (rawLeases.exists && rawLeases.leases.some((l) => l && l.task_id === taskInfo.id)) {
|
|
768
|
+
const remaining = (leaseState.activeLeases || []).filter((l) => l.task_id !== taskInfo.id);
|
|
769
|
+
const leaseYaml = serializeYaml(
|
|
770
|
+
{ schema_version: "1.0", updated_at: timestamp, leases: remaining },
|
|
771
|
+
{ headerComment: "Cooperative multi-IDE task & scope leases (advisory collision avoidance)" }
|
|
772
|
+
);
|
|
773
|
+
steps.push({ label: "leases", filePath: rawLeases.leasesAbs, content: leaseYaml, allowOverwrite: true });
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
return {
|
|
778
|
+
steps,
|
|
779
|
+
warnings,
|
|
780
|
+
result: {
|
|
781
|
+
id: taskInfo.id,
|
|
782
|
+
relPath: taskInfo.relPath,
|
|
783
|
+
previousStatus: taskInfo.record.status,
|
|
784
|
+
status: nextStatus,
|
|
785
|
+
record: updatedRecord,
|
|
786
|
+
stateRevision: updatedState.state_revision,
|
|
787
|
+
activeTasks,
|
|
788
|
+
blockedTasks,
|
|
789
|
+
lastCompletedTask,
|
|
790
|
+
verified,
|
|
791
|
+
verificationStatus,
|
|
792
|
+
verifiedEvidenceRefs: evidEval.verifiedIds,
|
|
793
|
+
warnings,
|
|
794
|
+
},
|
|
795
|
+
};
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
/**
|
|
799
|
+
* Claims a cooperative task & file-scope lease for an AI/IDE session under `.geloforge/.state.lock`,
|
|
800
|
+
* blocking colliding tasks or overlapping scopes unless `--force`.
|
|
801
|
+
*/
|
|
802
|
+
export function claimTaskLease({
|
|
803
|
+
projectDir,
|
|
804
|
+
taskId,
|
|
805
|
+
role = null,
|
|
806
|
+
tool = "local-agent",
|
|
807
|
+
scopes = [],
|
|
808
|
+
sessionId = null,
|
|
809
|
+
ttlMinutes = 120,
|
|
810
|
+
force = false,
|
|
811
|
+
createdAt,
|
|
812
|
+
dryRun = false,
|
|
813
|
+
harnessDir = DEFAULT_HARNESS_DIR,
|
|
814
|
+
lockTimeoutMs,
|
|
815
|
+
staleLockMs,
|
|
816
|
+
_holdLockMs = 0,
|
|
817
|
+
_faultHook = null,
|
|
818
|
+
} = {}) {
|
|
819
|
+
if (typeof projectDir !== "string" || projectDir.trim().length === 0) {
|
|
820
|
+
throw new Error("Missing required project directory (--project <path>).");
|
|
821
|
+
}
|
|
822
|
+
if (typeof taskId !== "string" || !/^TASK-\d{4}$/i.test(taskId.trim())) {
|
|
823
|
+
throw new Error(`Invalid task ID "${taskId}". Expected TASK-NNNN.`);
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
const run = () => {
|
|
827
|
+
const taskInfo = getTask({ projectDir, taskId, harnessDir });
|
|
828
|
+
const loaded = loadProjectManifestAndState(projectDir, harnessDir);
|
|
829
|
+
|
|
830
|
+
if (!force && (taskInfo.record.status === "completed" || taskInfo.record.status === "cancelled")) {
|
|
831
|
+
throw new Error(
|
|
832
|
+
`Cannot claim ${taskInfo.id} because its status is "${taskInfo.record.status}". Reactivate it or pass --force.`
|
|
833
|
+
);
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
const effectiveRole = (role ? String(role) : taskInfo.record.assigned_role).trim();
|
|
837
|
+
if (!ALLOWED_ROLES.has(effectiveRole)) {
|
|
838
|
+
throw new Error(`Invalid --role "${effectiveRole}". Expected one of: ${Array.from(ALLOWED_ROLES).join(", ")}`);
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
const cleanTool = validateScalarText("--tool", String(tool || "local-agent"));
|
|
842
|
+
if (hasSecretContent(cleanTool)) {
|
|
843
|
+
throw new Error("Refusing credential-like content in --tool.");
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
const ttl = ttlMinutes === undefined || ttlMinutes === null ? 120 : Number(ttlMinutes);
|
|
847
|
+
if (!Number.isInteger(ttl) || ttl < 1 || ttl > 1440) {
|
|
848
|
+
throw new Error(`Invalid --ttl "${ttlMinutes}". Expected integer minutes between 1 and 1440.`);
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
const nowIso = validateCreatedAt(createdAt);
|
|
852
|
+
const nowMs = Date.parse(nowIso);
|
|
853
|
+
const expiresAt = new Date(nowMs + ttl * 60 * 1000).toISOString();
|
|
854
|
+
|
|
855
|
+
const rawScopes = Array.isArray(scopes) ? scopes : scopes ? [scopes] : [];
|
|
856
|
+
const claimedScope = rawScopes.length > 0 ? normalizeTextList(rawScopes, "--scope") : [...(taskInfo.record.scope_in || [])];
|
|
857
|
+
|
|
858
|
+
const cleanSession = sessionId ? validateScalarText("--session", sessionId) : `sess-${taskInfo.id.toLowerCase()}-${deriveSlug(cleanTool) || "agent"}`;
|
|
859
|
+
if (hasSecretContent(cleanSession)) {
|
|
860
|
+
throw new Error("Refusing credential-like content in --session.");
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
const leaseState = listTaskLeases({ projectDir: loaded.projectDir, nowIso, harnessDir });
|
|
864
|
+
if (Number.isFinite(Number(_holdLockMs)) && Number(_holdLockMs) > 0) {
|
|
865
|
+
sleepSyncMs(Number(_holdLockMs));
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
for (const other of leaseState.activeLeases) {
|
|
869
|
+
if (other.task_id === taskInfo.id) {
|
|
870
|
+
if (!force) {
|
|
871
|
+
throw new Error(
|
|
872
|
+
`Task lease collision: ${taskInfo.id} is already claimed by tool "${other.tool}" (role "${other.role}") until ${other.expires_at}. Run "geloforge task release ${taskInfo.id} --tool ${other.tool}" or pass --force.`
|
|
873
|
+
);
|
|
874
|
+
}
|
|
875
|
+
continue;
|
|
876
|
+
}
|
|
877
|
+
if (!force) {
|
|
878
|
+
for (const s1 of claimedScope) {
|
|
879
|
+
for (const s2 of other.claimed_scope || []) {
|
|
880
|
+
if (scopesOverlap(s1, s2)) {
|
|
881
|
+
throw new Error(
|
|
882
|
+
`File-scope collision: scope "${s1}" on ${taskInfo.id} overlaps with active peer lease on ${other.task_id} (tool "${other.tool}", role "${other.role}", scope "${s2}"). Coordinate scopes or pass --force.`
|
|
883
|
+
);
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
const newLease = {
|
|
891
|
+
task_id: taskInfo.id,
|
|
892
|
+
title: taskInfo.record.title,
|
|
893
|
+
role: effectiveRole,
|
|
894
|
+
tool: cleanTool,
|
|
895
|
+
session_id: cleanSession,
|
|
896
|
+
identity_mode: "advisory_self_declared",
|
|
897
|
+
claimed_scope: claimedScope,
|
|
898
|
+
claimed_at: nowIso,
|
|
899
|
+
expires_at: expiresAt,
|
|
900
|
+
};
|
|
901
|
+
|
|
902
|
+
const nextLeases = [...leaseState.activeLeases.filter((l) => l.task_id !== taskInfo.id), newLease].sort((a, b) =>
|
|
903
|
+
a.task_id.localeCompare(b.task_id)
|
|
904
|
+
);
|
|
905
|
+
const leasesAbs = assertSafeWithinRoot(loaded.projectDir, leaseState.leasesRelPath);
|
|
906
|
+
|
|
907
|
+
const updatePlan = prepareTaskUpdatePlan({
|
|
908
|
+
loaded,
|
|
909
|
+
taskInfo,
|
|
910
|
+
harnessDir,
|
|
911
|
+
status: "active",
|
|
912
|
+
assignedRole: effectiveRole,
|
|
913
|
+
activate: true,
|
|
914
|
+
tool: cleanTool,
|
|
915
|
+
sessionId: cleanSession,
|
|
916
|
+
force: true,
|
|
917
|
+
updatedAt: nowIso,
|
|
918
|
+
leaseStateOverride: leaseState,
|
|
919
|
+
skipLeaseWrite: true,
|
|
920
|
+
});
|
|
921
|
+
|
|
922
|
+
if (!dryRun) {
|
|
923
|
+
const leaseYaml = serializeYaml(
|
|
924
|
+
{
|
|
925
|
+
schema_version: "1.0",
|
|
926
|
+
updated_at: nowIso,
|
|
927
|
+
leases: nextLeases,
|
|
928
|
+
},
|
|
929
|
+
{ headerComment: "Cooperative multi-IDE task & scope leases (advisory collision avoidance)" }
|
|
930
|
+
);
|
|
931
|
+
runMultiFileTransaction(
|
|
932
|
+
[{ label: "leases", filePath: leasesAbs, content: leaseYaml, allowOverwrite: true }, ...updatePlan.steps],
|
|
933
|
+
{ projectDir: loaded.projectDir, faultHook: _faultHook }
|
|
934
|
+
);
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
return {
|
|
938
|
+
dryRun: Boolean(dryRun),
|
|
939
|
+
projectDir: loaded.projectDir,
|
|
940
|
+
leasesRelPath: leaseState.leasesRelPath,
|
|
941
|
+
identityModel: "advisory_self_declared",
|
|
942
|
+
lease: newLease,
|
|
943
|
+
activeLeases: nextLeases,
|
|
944
|
+
};
|
|
945
|
+
};
|
|
946
|
+
|
|
947
|
+
if (dryRun) {
|
|
948
|
+
return run();
|
|
949
|
+
}
|
|
950
|
+
return withProjectLock(projectDir, run, { lockTimeoutMs, staleLockMs });
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
/**
|
|
954
|
+
* Updates an existing TASK-NNNN contract status/priority/role cleanly inside project lock and rollback transaction.
|
|
955
|
+
*/
|
|
956
|
+
export function updateTask(options = {}) {
|
|
957
|
+
const harnessDir = path.resolve(options.harnessDir || DEFAULT_HARNESS_DIR);
|
|
958
|
+
if (typeof options.projectDir !== "string" || options.projectDir.trim().length === 0) {
|
|
959
|
+
throw new Error("Missing required project directory (--project <path>).");
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
const run = () => {
|
|
963
|
+
const taskInfo = getTask({ projectDir: options.projectDir, taskId: options.taskId, harnessDir });
|
|
964
|
+
const loaded = loadProjectManifestAndState(options.projectDir, harnessDir);
|
|
965
|
+
const plan = prepareTaskUpdatePlan({
|
|
966
|
+
loaded,
|
|
967
|
+
taskInfo,
|
|
968
|
+
harnessDir,
|
|
969
|
+
status: options.status,
|
|
970
|
+
priority: options.priority,
|
|
971
|
+
assignedRole: options.assignedRole,
|
|
972
|
+
activate: Boolean(options.activate),
|
|
973
|
+
evidenceRefs: options.evidenceRefs,
|
|
974
|
+
requireEvidence: Boolean(options.requireEvidence),
|
|
975
|
+
tool: options.tool,
|
|
976
|
+
sessionId: options.sessionId,
|
|
977
|
+
force: Boolean(options.force),
|
|
978
|
+
updatedAt: options.updatedAt,
|
|
979
|
+
});
|
|
980
|
+
|
|
981
|
+
const dryRun = Boolean(options.dryRun);
|
|
982
|
+
if (!dryRun) {
|
|
983
|
+
runMultiFileTransaction(plan.steps, { projectDir: loaded.projectDir, faultHook: options._faultHook });
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
return {
|
|
987
|
+
dryRun,
|
|
988
|
+
...plan.result,
|
|
989
|
+
};
|
|
990
|
+
};
|
|
991
|
+
|
|
992
|
+
if (options.dryRun) {
|
|
993
|
+
return run();
|
|
994
|
+
}
|
|
995
|
+
return withProjectLock(options.projectDir, run, {
|
|
996
|
+
lockTimeoutMs: options.lockTimeoutMs,
|
|
997
|
+
staleLockMs: options.staleLockMs,
|
|
998
|
+
});
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
/**
|
|
1002
|
+
* Convenience wrapper marking a task "completed", removing it from active_tasks,
|
|
1003
|
+
* updating last_completed_task, checking evidence truth, and releasing any active lease atomically.
|
|
1004
|
+
*/
|
|
1005
|
+
export function completeTask(options = {}) {
|
|
1006
|
+
return updateTask({
|
|
1007
|
+
...options,
|
|
1008
|
+
status: "completed",
|
|
1009
|
+
activate: false,
|
|
1010
|
+
});
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
/**
|
|
1014
|
+
* Loads a single TASK-NNNN contract by exact ID.
|
|
1015
|
+
*/
|
|
1016
|
+
export function getTask({ projectDir, taskId, harnessDir = DEFAULT_HARNESS_DIR }) {
|
|
1017
|
+
if (typeof taskId !== "string" || !/^TASK-\d{4}$/i.test(taskId.trim())) {
|
|
1018
|
+
throw new Error(`Invalid task ID "${taskId}". Expected TASK-NNNN.`);
|
|
1019
|
+
}
|
|
1020
|
+
const cleanId = taskId.trim().toUpperCase();
|
|
1021
|
+
const loaded = loadProjectManifestAndState(projectDir, harnessDir);
|
|
1022
|
+
const tasksDirAbs = assertSafeWithinRoot(loaded.projectDir, loaded.projectPaths.tasks_dir);
|
|
1023
|
+
|
|
1024
|
+
if (fs.existsSync(tasksDirAbs)) {
|
|
1025
|
+
const files = walkNonSymlinkFiles(loaded.projectDir, tasksDirAbs, (p) => /^TASK-\d{4}.*\.ya?ml$/i.test(path.basename(p)));
|
|
1026
|
+
for (const filePath of files) {
|
|
1027
|
+
const relPath = path.relative(loaded.projectDir, filePath).replace(/\\/g, "/");
|
|
1028
|
+
const raw = fs.readFileSync(filePath, "utf8");
|
|
1029
|
+
const data = parseYaml(raw, relPath);
|
|
1030
|
+
if (data && data.id === cleanId) {
|
|
1031
|
+
return {
|
|
1032
|
+
projectDir: loaded.projectDir,
|
|
1033
|
+
id: cleanId,
|
|
1034
|
+
relPath,
|
|
1035
|
+
filePath,
|
|
1036
|
+
record: data,
|
|
1037
|
+
yaml: raw,
|
|
1038
|
+
activeInState: (loaded.state.active_tasks || []).includes(cleanId),
|
|
1039
|
+
};
|
|
1040
|
+
}
|
|
1041
|
+
}
|
|
1042
|
+
}
|
|
1043
|
+
throw new Error(`Task "${cleanId}" not found under ${loaded.projectPaths.tasks_dir} in ${loaded.projectDir}.`);
|
|
1044
|
+
}
|