pi-crew 0.9.67 → 0.10.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/CHANGELOG.md +172 -0
- package/agents/analyst.md +1 -1
- package/agents/cold-verifier.md +3 -1
- package/agents/critic.md +1 -1
- package/agents/executor.md +1 -1
- package/agents/explorer.md +1 -1
- package/agents/planner.md +1 -1
- package/agents/reviewer.md +1 -1
- package/agents/security-reviewer.md +1 -1
- package/agents/test-engineer.md +1 -1
- package/agents/verifier.md +1 -1
- package/agents/writer.md +1 -1
- package/dist/index.mjs +65847 -60331
- package/docs/README.md +2 -0
- package/docs/actions-reference.md +31 -0
- package/docs/commands-reference.md +17 -6
- package/docs/resource-formats.md +13 -0
- package/package.json +9 -6
- package/schema.json +15 -1
- package/scripts/resource-sampler.mjs +36 -2
- package/skills/requirements-to-task-packet/SKILL.md +26 -0
- package/skills/widget-rendering/SKILL.md +7 -7
- package/src/agents/agent-config.ts +36 -14
- package/src/agents/discover-agents.ts +23 -14
- package/src/config/config-merge.ts +183 -0
- package/src/config/config-validation.ts +681 -0
- package/src/config/config.ts +22 -864
- package/src/config/defaults.ts +35 -1
- package/src/config/drift-detector.ts +1 -1
- package/src/config/env-vars.ts +691 -0
- package/src/config/role-tools.ts +8 -8
- package/src/config/sanitize-project-config.ts +172 -0
- package/src/config/types.ts +30 -0
- package/src/extension/async-notifier.ts +25 -2
- package/src/extension/crew-vibes/config.ts +2 -1
- package/src/extension/plan-orchestrate.ts +132 -0
- package/src/extension/registration/commands/dashboard.ts +158 -0
- package/src/extension/registration/commands/index.ts +35 -0
- package/src/extension/registration/commands/manage.ts +303 -0
- package/src/extension/registration/commands/run.ts +214 -0
- package/src/extension/registration/commands/shared.ts +631 -0
- package/src/extension/registration/commands/status.ts +60 -0
- package/src/extension/registration/commands.ts +13 -1224
- package/src/extension/registration/lifecycle-handlers.ts +126 -15
- package/src/extension/registration/subagent-tools.ts +218 -9
- package/src/extension/rpc-hmac.ts +5 -3
- package/src/extension/team-tool/api/heartbeat.ts +47 -10
- package/src/extension/team-tool/api/plan-approval.ts +9 -0
- package/src/extension/team-tool/api/task-claims.ts +109 -40
- package/src/extension/team-tool/cancel.ts +84 -50
- package/src/extension/team-tool/dispatch/index.ts +1 -0
- package/src/extension/team-tool/dispatch/run.ts +4 -1
- package/src/extension/team-tool/doctor.ts +103 -1
- package/src/extension/team-tool/orchestrate.ts +66 -1
- package/src/extension/team-tool/plans.ts +192 -0
- package/src/extension/team-tool/respond.ts +197 -65
- package/src/extension/team-tool/run-deadline.ts +16 -1
- package/src/extension/team-tool/run-intent.ts +63 -0
- package/src/extension/team-tool/run.ts +48 -18
- package/src/extension/team-tool/status.ts +84 -26
- package/src/extension/team-tool.ts +11 -2
- package/src/hooks/registry.ts +1 -6
- package/src/i18n.ts +9 -0
- package/src/prompt/prompt-runtime.ts +521 -2
- package/src/prompt/worker-events-channel.ts +173 -0
- package/src/runtime/README.md +8 -8
- package/src/runtime/async-runner.ts +7 -3
- package/src/runtime/background-runner.ts +42 -14
- package/src/runtime/broker/broker-issuer.ts +9 -2
- package/src/runtime/broker/crew-broker-tokens.ts +43 -6
- package/src/runtime/broker/crew-broker.ts +838 -10
- package/src/runtime/broker/wait-status-cache.ts +157 -0
- package/src/runtime/budget-enforcement.ts +281 -0
- package/src/runtime/child-pi/child-pi-spawn.ts +60 -14
- package/src/runtime/child-pi/child-pi-timers.ts +324 -0
- package/src/runtime/child-pi/child-pi.ts +97 -201
- package/src/runtime/child-pi/mock-fixtures.ts +16 -2
- package/src/runtime/crew-agent-records.ts +259 -14
- package/src/runtime/delegate-spawn.ts +148 -0
- package/src/runtime/deterministic-ast.ts +2 -1
- package/src/runtime/dispatch-batch.ts +945 -0
- package/src/runtime/finalize-run.ts +557 -0
- package/src/runtime/goal-workflow/adaptive-plan.ts +87 -13
- package/src/runtime/goal-workflow/dynamic-workflow-runner.ts +3 -2
- package/src/runtime/goal-workflow/goal-state-store.ts +1 -1
- package/src/runtime/group-join.ts +11 -125
- package/src/runtime/live-session/live-session-runtime.ts +26 -1
- package/src/runtime/merge-gate.ts +7 -1
- package/src/runtime/merge-loop.ts +130 -0
- package/src/runtime/model/model-budget-summary.ts +53 -0
- package/src/runtime/model/model-fallback.ts +32 -2
- package/src/runtime/model/pi-args.ts +10 -0
- package/src/runtime/model/provider-extensions.ts +10 -0
- package/src/runtime/orphan-worker-registry.ts +1 -1
- package/src/runtime/output/output-validator.ts +45 -0
- package/src/runtime/parent-guard.ts +3 -1
- package/src/runtime/peer-dep.ts +2 -1
- package/src/runtime/per-write-validator.ts +0 -5
- package/src/runtime/pi-spawn.ts +61 -15
- package/src/runtime/plan-approval.ts +125 -0
- package/src/runtime/plan-replan.ts +151 -0
- package/src/runtime/recovery/checkpoint.ts +0 -18
- package/src/runtime/recovery/crash-recovery.ts +95 -46
- package/src/runtime/scheduler-context.ts +98 -0
- package/src/runtime/scheduling/coalesce-tasks.ts +5 -0
- package/src/runtime/scheduling/global-worker-cap.ts +2 -1
- package/src/runtime/scheduling/nested-slots.ts +70 -0
- package/src/runtime/scheduling/run-coalesced-task-group.ts +64 -13
- package/src/runtime/scheduling/task-graph-scheduler.ts +0 -10
- package/src/runtime/scratchpad/README.md +10 -5
- package/src/runtime/scratchpad/guest.ts +103 -2
- package/src/runtime/scratchpad/protocol.ts +13 -1
- package/src/runtime/scratchpad/transform.ts +206 -12
- package/src/runtime/settings-store.ts +219 -0
- package/src/runtime/spawn-policy.ts +217 -0
- package/src/runtime/stale-reconciler.ts +87 -6
- package/src/runtime/subagent-manager.ts +25 -1
- package/src/runtime/task-output-context.ts +230 -9
- package/src/runtime/task-packet.ts +23 -1
- package/src/runtime/task-runner/child-executor.ts +106 -7
- package/src/runtime/task-runner/post-execution.ts +125 -1
- package/src/runtime/task-runner/pre-execution.ts +39 -1
- package/src/runtime/task-runner/prompt-builder.ts +51 -1
- package/src/runtime/task-runner/retrieval-orchestrator.ts +72 -18
- package/src/runtime/task-runner/spec-evidence.ts +403 -0
- package/src/runtime/task-runner/state-helpers.ts +26 -24
- package/src/runtime/task-runner.ts +11 -0
- package/src/runtime/team-runner.ts +129 -1671
- package/src/runtime/verification/spec-sandbox.ts +255 -0
- package/src/runtime/verification/verification-gates.ts +3 -2
- package/src/runtime/verification/verification-worktree.ts +2 -1
- package/src/runtime/workflow-phase-advance.ts +100 -0
- package/src/runtime/workspace-tree.ts +9 -0
- package/src/schema/config-schema.ts +65 -25
- package/src/schema/sensitive-config-paths.ts +64 -0
- package/src/schema/team-tool-schema.ts +13 -3
- package/src/state/README.md +4 -10
- package/src/state/atomic-write.ts +20 -3
- package/src/state/contracts.ts +38 -0
- package/src/state/coordination/mailbox.ts +12 -2
- package/src/state/event-log/cursor.ts +223 -0
- package/src/state/event-log/event-log-rotation.ts +12 -4
- package/src/state/event-log/event-log.ts +152 -369
- package/src/state/event-log/sequence-cache.ts +373 -0
- package/src/state/event-log/worker-atomic-writer.ts +2 -1
- package/src/state/stores/active-run-registry.ts +3 -2
- package/src/state/stores/manifest-io.ts +237 -0
- package/src/state/stores/ownership-map.ts +162 -0
- package/src/state/stores/plan-store.ts +241 -0
- package/src/state/stores/run-cache.ts +0 -90
- package/src/state/stores/spec-store.ts +189 -0
- package/src/state/stores/state-store.ts +66 -229
- package/src/state/types.ts +197 -0
- package/src/ui/dashboard-panes/plan-pane.ts +136 -0
- package/src/ui/dashboard-panes/progress-pane.ts +6 -0
- package/src/ui/dashboard-panes/transcript-pane.ts +31 -0
- package/src/ui/heartbeat-aggregator.ts +9 -1
- package/src/ui/keybinding-map.ts +54 -13
- package/src/ui/powerbar-publisher.ts +52 -1
- package/src/ui/run-dashboard.ts +31 -5
- package/src/ui/run-snapshot-cache.ts +57 -30
- package/src/ui/snapshot-types.ts +6 -1
- package/src/ui/widget/widget-renderer.ts +9 -1
- package/src/utils/file-coalescer.ts +0 -4
- package/src/utils/fs-errno.ts +66 -0
- package/src/utils/fs-watch.ts +1 -1
- package/src/utils/internal-error.ts +3 -1
- package/src/utils/paths.ts +11 -3
- package/src/utils/task-name-generator.ts +1 -8
- package/src/workflows/discover-workflows.ts +19 -2
- package/src/workflows/validate-workflow.ts +7 -1
- package/src/workflows/workflow-config.ts +10 -0
- package/src/workflows/workflow-serializer.ts +3 -0
- package/src/worktree/worktree-manager.ts +22 -0
- package/src/agents/agent-search.ts +0 -98
- package/src/benchmark/benchmark-runner.ts +0 -313
- package/src/benchmark/feedback-loop.ts +0 -73
- package/src/config/resilient-parser.ts +0 -117
- package/src/extension/crew-vibes/cat-frames.ts +0 -18
- package/src/extension/result-watcher.ts +0 -139
- package/src/observability/exporters/prometheus-exporter.ts +0 -54
- package/src/observability/metric-retention.ts +0 -64
- package/src/runtime/compaction/compaction-summary.ts +0 -278
- package/src/runtime/errors/crew-errors.ts +0 -162
- package/src/runtime/live-session/intercom-bridge.ts +0 -187
- package/src/runtime/loop-gates.ts +0 -128
- package/src/runtime/metric-parser.ts +0 -36
- package/src/runtime/output/stream-preview.ts +0 -184
- package/src/runtime/output/tool-progress.ts +0 -278
- package/src/runtime/phase-tracker.ts +0 -385
- package/src/runtime/pipeline-runner.ts +0 -523
- package/src/runtime/process/process-lifecycle.ts +0 -491
- package/src/runtime/recovery/retry-runner.ts +0 -330
- package/src/runtime/run-drift.ts +0 -219
- package/src/runtime/scratchpad/snapshot-hmac.ts +0 -167
- package/src/runtime/task-quality.ts +0 -199
- package/src/runtime/task-runner/run-projection.ts +0 -128
- package/src/runtime/verification/post-checks.ts +0 -142
- package/src/state/coordination/schedule.ts +0 -166
- package/src/state/event-log/jsonl-writer.ts +0 -115
- package/src/state/hook-instinct-bridge.ts +0 -94
- package/src/state/hook-integrations.ts +0 -51
- package/src/state/session-state-map.ts +0 -51
- package/src/state/stores/blob-store.ts +0 -308
- package/src/state/stores/instinct-store.ts +0 -275
- package/src/state/stores/observation-store.ts +0 -176
- package/src/state/tiered-eval.ts +0 -480
- package/src/state/types-eval.ts +0 -58
- package/src/tools/safe-bash-extension.ts +0 -54
- package/src/tools/safe-bash.ts +0 -505
- package/src/ui/agent-management-overlay.ts +0 -160
- package/src/ui/crew-footer.ts +0 -102
- package/src/ui/crew-select-list.ts +0 -114
- package/src/ui/dashboard-panes/capability-pane.ts +0 -77
- package/src/ui/transcript-entries.ts +0 -256
- package/src/utils/conflict-detect.ts +0 -721
- package/src/utils/fingerprint.ts +0 -180
- package/src/utils/gh-protocol.ts +0 -556
- package/src/utils/project-detector.ts +0 -160
- package/src/utils/sse-parser.ts +0 -131
- package/src/workflows/cost-estimator.ts +0 -34
- package/src/workflows/intermediate-store.ts +0 -166
|
@@ -1,308 +0,0 @@
|
|
|
1
|
-
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
-
import * as fs from "node:fs";
|
|
3
|
-
import * as path from "node:path";
|
|
4
|
-
import { resolveRealContainedPath } from "../../utils/safe-paths.ts";
|
|
5
|
-
import { atomicWriteFile, renameWithRetry } from "../atomic-write.ts";
|
|
6
|
-
import { withFileLockSync } from "../coordination/locks.ts";
|
|
7
|
-
|
|
8
|
-
const SHA256_HEX = /^[a-f0-9]{64}$/i;
|
|
9
|
-
|
|
10
|
-
function validateBlobHash(hash: string, algorithm?: string): void {
|
|
11
|
-
if (!SHA256_HEX.test(hash)) throw new Error(`Invalid blob hash: ${hash}`);
|
|
12
|
-
if (algorithm !== undefined && algorithm !== SHA256_PREFIX) {
|
|
13
|
-
throw new Error(`Invalid blob algorithm: ${algorithm} (expected ${SHA256_PREFIX})`);
|
|
14
|
-
}
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
/**
|
|
18
|
-
* Atomically write a Buffer to a file using temp-file + rename pattern.
|
|
19
|
-
* Prevents partial writes on crash and handles concurrent writes safely.
|
|
20
|
-
*/
|
|
21
|
-
function atomicWriteBuffer(filePath: string, content: Buffer): void {
|
|
22
|
-
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
23
|
-
const tempPath = `${filePath}.${randomUUID()}.tmp`;
|
|
24
|
-
const O_NOFOLLOW = typeof fs.constants.O_NOFOLLOW === "number" ? fs.constants.O_NOFOLLOW : 0;
|
|
25
|
-
const fd = fs.openSync(tempPath, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | O_NOFOLLOW, 0o600);
|
|
26
|
-
try {
|
|
27
|
-
const openedStat = fs.fstatSync(fd);
|
|
28
|
-
if (!openedStat.isFile()) {
|
|
29
|
-
throw new Error(`Refusing to write: opened path is not a regular file: ${tempPath}`);
|
|
30
|
-
}
|
|
31
|
-
fs.writeSync(fd, content, 0, content.length);
|
|
32
|
-
renameWithRetry(tempPath, filePath);
|
|
33
|
-
} catch (error) {
|
|
34
|
-
try {
|
|
35
|
-
fs.rmSync(tempPath, { force: true });
|
|
36
|
-
} catch {
|
|
37
|
-
/* best-effort */
|
|
38
|
-
}
|
|
39
|
-
throw error;
|
|
40
|
-
} finally {
|
|
41
|
-
// Always close fd; closeSync is safe to call even if fd was already closed
|
|
42
|
-
try {
|
|
43
|
-
fs.closeSync(fd);
|
|
44
|
-
} catch {
|
|
45
|
-
/* best-effort */
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
const BLOBS_DIR = "blobs";
|
|
51
|
-
const BLOB_META_DIR = "blob-metadata";
|
|
52
|
-
const SHA256_PREFIX = "sha256";
|
|
53
|
-
|
|
54
|
-
/**
|
|
55
|
-
* File-based lock for cross-process metadata write protection.
|
|
56
|
-
* Uses withFileLockSync which provides O_EXCL atomic create + token-guarded release.
|
|
57
|
-
*/
|
|
58
|
-
function withMetadataLock<T>(metadataPath: string, fn: () => T): T {
|
|
59
|
-
return withFileLockSync(metadataPath, fn);
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
export interface BlobMetadata {
|
|
63
|
-
blobHash: string;
|
|
64
|
-
blobAlgorithm: string;
|
|
65
|
-
runId: string;
|
|
66
|
-
taskId?: string;
|
|
67
|
-
mime: string;
|
|
68
|
-
producer: string;
|
|
69
|
-
originalPath: string;
|
|
70
|
-
sizeBytes: number;
|
|
71
|
-
redacted: boolean;
|
|
72
|
-
retention: "run" | "project" | "temporary";
|
|
73
|
-
createdAt: string;
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
export interface BlobWriteResult {
|
|
77
|
-
hash: string;
|
|
78
|
-
algorithm: string;
|
|
79
|
-
blobPath: string;
|
|
80
|
-
metadataPath: string;
|
|
81
|
-
sizeBytes: number;
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
function sha256Of(content: string | Buffer): string {
|
|
85
|
-
return createHash("sha256")
|
|
86
|
-
.update(typeof content === "string" ? content : content)
|
|
87
|
-
.digest("hex");
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
/**
|
|
91
|
-
* Write content-addressed blob to the blobs directory under artifactsRoot.
|
|
92
|
-
* Content is deduplicated by hash; metadata sidecar is always written.
|
|
93
|
-
* FIX: Both content and metadata writes now use atomicWriteFile to prevent
|
|
94
|
-
* partial writes on crash. The deduplication check is now advisory (the atomic
|
|
95
|
-
* write handles concurrent writes correctly via O_EXCL temp file pattern).
|
|
96
|
-
*/
|
|
97
|
-
export function writeBlob(
|
|
98
|
-
artifactsRoot: string,
|
|
99
|
-
input: {
|
|
100
|
-
content: string | Buffer;
|
|
101
|
-
runId: string;
|
|
102
|
-
taskId?: string;
|
|
103
|
-
mime?: string;
|
|
104
|
-
producer: string;
|
|
105
|
-
originalPath: string;
|
|
106
|
-
redacted?: boolean;
|
|
107
|
-
retention?: BlobMetadata["retention"];
|
|
108
|
-
},
|
|
109
|
-
): BlobWriteResult {
|
|
110
|
-
const content = input.content;
|
|
111
|
-
const hash = sha256Of(content);
|
|
112
|
-
const algorithm = SHA256_PREFIX;
|
|
113
|
-
const blobDir = path.join(artifactsRoot, BLOBS_DIR, algorithm);
|
|
114
|
-
const metaDir = path.join(artifactsRoot, BLOB_META_DIR);
|
|
115
|
-
// Issue 2 fix: Validate parent directories are not symlinks before mkdirSync.
|
|
116
|
-
// An attacker could plant a symlink before we create the directory, causing
|
|
117
|
-
// blob content to be written to an attacker-controlled location.
|
|
118
|
-
resolveRealContainedPath(artifactsRoot, blobDir);
|
|
119
|
-
resolveRealContainedPath(artifactsRoot, metaDir);
|
|
120
|
-
fs.mkdirSync(blobDir, { recursive: true });
|
|
121
|
-
fs.mkdirSync(metaDir, { recursive: true });
|
|
122
|
-
|
|
123
|
-
const blobPath = path.join(blobDir, hash);
|
|
124
|
-
// Issue 6 fix: Validate blobPath BEFORE writing to ensure the path is safe.
|
|
125
|
-
// If resolveRealContainedPath throws after the write, the blob may already
|
|
126
|
-
// exist at an unexpected location. Validate first to prevent this.
|
|
127
|
-
resolveRealContainedPath(artifactsRoot, blobPath);
|
|
128
|
-
const metadata: BlobMetadata = {
|
|
129
|
-
blobHash: hash,
|
|
130
|
-
blobAlgorithm: algorithm,
|
|
131
|
-
runId: input.runId,
|
|
132
|
-
taskId: input.taskId,
|
|
133
|
-
mime: input.mime ?? "text/plain",
|
|
134
|
-
producer: input.producer,
|
|
135
|
-
originalPath: input.originalPath,
|
|
136
|
-
sizeBytes: Buffer.isBuffer(content) ? content.length : Buffer.byteLength(content, "utf-8"),
|
|
137
|
-
redacted: input.redacted ?? false,
|
|
138
|
-
retention: input.retention ?? "run",
|
|
139
|
-
createdAt: new Date().toISOString(),
|
|
140
|
-
};
|
|
141
|
-
const metadataPath = path.join(metaDir, `${hash}.json`);
|
|
142
|
-
|
|
143
|
-
// Both content and metadata use atomic writes to prevent partial writes on crash.
|
|
144
|
-
// Content is immutable and content-addressed (same hash = same content), so
|
|
145
|
-
// concurrent writes to the same hash are safe. Metadata (mime, retention, etc.)
|
|
146
|
-
// is protected by a per-hash lock to make the check-then-write atomic, preventing
|
|
147
|
-
// concurrent writers from racing to write different metadata for the same hash.
|
|
148
|
-
// Issue 3 fix: wrap metadata check-and-write in a lock to make it atomic.
|
|
149
|
-
// Without the lock, two processes could read the same metadata concurrently,
|
|
150
|
-
// both pass the check, and the second write would silently overwrite the first.
|
|
151
|
-
// FIX: Write blob content FIRST, then metadata. If blob write fails, no orphan metadata.
|
|
152
|
-
// Previous order was metadata first, then blob - causing orphan metadata on blob failure.
|
|
153
|
-
let blobContentWritten = false;
|
|
154
|
-
// Write blob content first (immutable, content-addressed)
|
|
155
|
-
atomicWriteBuffer(blobPath, Buffer.isBuffer(content) ? content : Buffer.from(content, "utf-8"));
|
|
156
|
-
blobContentWritten = true;
|
|
157
|
-
|
|
158
|
-
// Metadata only after blob content is successfully written
|
|
159
|
-
// Issue 3 fix: Use two-phase commit for metadata - write to temp file first,
|
|
160
|
-
// then atomically rename to final location. This prevents orphan blobs if
|
|
161
|
-
// the process crashes after blob write but before metadata rename.
|
|
162
|
-
let metadataWritten = false;
|
|
163
|
-
try {
|
|
164
|
-
withMetadataLock(metadataPath, () => {
|
|
165
|
-
try {
|
|
166
|
-
const existingMeta = JSON.parse(fs.readFileSync(metadataPath, "utf-8")) as BlobMetadata;
|
|
167
|
-
// Compare fields that indicate concurrent write with different metadata.
|
|
168
|
-
// Note: taskId is intentionally NOT part of the conflict check because
|
|
169
|
-
// it represents which task produced the blob and may legitimately differ
|
|
170
|
-
// across processes (last-write-wins for taskId). If concurrent writes
|
|
171
|
-
// have identical mime/retention/producer/originalPath but different
|
|
172
|
-
// taskId, the conflict check passes and both writes succeed — the
|
|
173
|
-
// final taskId reflects whichever write completed last.
|
|
174
|
-
// Callers should not rely on taskId for correctness-critical decisions.
|
|
175
|
-
if (
|
|
176
|
-
existingMeta.mime !== metadata.mime ||
|
|
177
|
-
existingMeta.retention !== metadata.retention ||
|
|
178
|
-
existingMeta.producer !== metadata.producer ||
|
|
179
|
-
existingMeta.originalPath !== metadata.originalPath
|
|
180
|
-
) {
|
|
181
|
-
throw new Error(
|
|
182
|
-
`Concurrent metadata write conflict for blob ${hash}: different metadata values detected. Existing: ${JSON.stringify(existingMeta)}, New: ${JSON.stringify(metadata)}`,
|
|
183
|
-
);
|
|
184
|
-
}
|
|
185
|
-
} catch (err) {
|
|
186
|
-
if (err instanceof Error && err.message.includes("ENOENT")) {
|
|
187
|
-
// OK - metadata doesn't exist yet, proceed to write
|
|
188
|
-
} else {
|
|
189
|
-
// Re-throw non-ENOENT errors (e.g., permission denied, corrupt file)
|
|
190
|
-
throw err;
|
|
191
|
-
}
|
|
192
|
-
}
|
|
193
|
-
// Issue 3 fix: Two-phase commit for metadata
|
|
194
|
-
// Write to temp file first, then atomically rename to final location.
|
|
195
|
-
// Issue 1 fix: Use atomicWriteFile instead of plain writeSync for the temp file
|
|
196
|
-
// to prevent partial writes on crash. atomicWriteFile uses O_EXCL + write + rename
|
|
197
|
-
// pattern which is consistent with how blob content is written.
|
|
198
|
-
const tempMetaPath = `${metadataPath}.${randomUUID()}.tmp`;
|
|
199
|
-
atomicWriteFile(tempMetaPath, JSON.stringify(metadata, null, 2));
|
|
200
|
-
renameWithRetry(tempMetaPath, metadataPath);
|
|
201
|
-
metadataWritten = true;
|
|
202
|
-
});
|
|
203
|
-
} catch (error) {
|
|
204
|
-
// Round 24 (BUG 4 note): the catch block previously checked
|
|
205
|
-
// `if (!blobContentWritten)` — the WRONG variable (the local comment said
|
|
206
|
-
// `metadataWritten === false`). For a CONTENT-ADDRESSED store the blob path
|
|
207
|
-
// is the content hash, so the blob may be referenced by another process's
|
|
208
|
-
// metadata even when OUR metadata write failed (e.g. a concurrent conflict
|
|
209
|
-
// where the peer already wrote metadata for the same hash). Deleting it
|
|
210
|
-
// would orphan their metadata. The safe behavior is therefore to NEVER
|
|
211
|
-
// delete on a metadata write failure and let the periodic
|
|
212
|
-
// cleanupOrphanedBlobs() reclaim genuinely-orphaned blobs. The guard below
|
|
213
|
-
// only removes a blob when its CONTENT was never written (a stray/partial
|
|
214
|
-
// file from a failed content write) — which is the only unambiguously-safe
|
|
215
|
-
// case to clean up here.
|
|
216
|
-
if (!blobContentWritten) {
|
|
217
|
-
try {
|
|
218
|
-
fs.rmSync(blobPath, { force: true });
|
|
219
|
-
} catch {
|
|
220
|
-
/* best-effort */
|
|
221
|
-
}
|
|
222
|
-
}
|
|
223
|
-
throw error;
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
// Issue 2 fix: resolve paths before writes and return cached values
|
|
227
|
-
const resolvedBlobPath = resolveRealContainedPath(artifactsRoot, blobPath);
|
|
228
|
-
const resolvedMetadataPath = resolveRealContainedPath(artifactsRoot, metadataPath);
|
|
229
|
-
return {
|
|
230
|
-
hash,
|
|
231
|
-
algorithm,
|
|
232
|
-
blobPath: resolvedBlobPath,
|
|
233
|
-
metadataPath: resolvedMetadataPath,
|
|
234
|
-
sizeBytes: metadata.sizeBytes,
|
|
235
|
-
};
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
/**
|
|
239
|
-
* Read a content-addressed blob by hash.
|
|
240
|
-
* Validates hash format and enforces path containment.
|
|
241
|
-
*/
|
|
242
|
-
export function readBlob(artifactsRoot: string, hash: string): Buffer | undefined {
|
|
243
|
-
validateBlobHash(hash);
|
|
244
|
-
try {
|
|
245
|
-
const blobDir = path.join(artifactsRoot, BLOBS_DIR, SHA256_PREFIX);
|
|
246
|
-
const blobPath = resolveRealContainedPath(blobDir, hash);
|
|
247
|
-
return fs.readFileSync(blobPath);
|
|
248
|
-
} catch {
|
|
249
|
-
return undefined;
|
|
250
|
-
}
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
/**
|
|
254
|
-
* Read blob metadata by hash.
|
|
255
|
-
* Validates hash format and enforces path containment.
|
|
256
|
-
*/
|
|
257
|
-
export function readBlobMetadata(artifactsRoot: string, hash: string): BlobMetadata | undefined {
|
|
258
|
-
validateBlobHash(hash);
|
|
259
|
-
try {
|
|
260
|
-
const metaDir = path.join(artifactsRoot, BLOB_META_DIR);
|
|
261
|
-
const metaPath = resolveRealContainedPath(metaDir, `${hash}.json`);
|
|
262
|
-
return JSON.parse(fs.readFileSync(metaPath, "utf-8")) as BlobMetadata;
|
|
263
|
-
} catch {
|
|
264
|
-
return undefined;
|
|
265
|
-
}
|
|
266
|
-
}
|
|
267
|
-
/**
|
|
268
|
-
* Cleanup orphaned blobs - blobs without corresponding metadata entries.
|
|
269
|
-
* Called periodically to reclaim storage from blobs that were written but whose
|
|
270
|
-
* metadata write failed (e.g., crash between content and metadata write).
|
|
271
|
-
* Returns the number of orphaned blobs cleaned up.
|
|
272
|
-
*/
|
|
273
|
-
export function cleanupOrphanedBlobs(artifactsRoot: string): number {
|
|
274
|
-
const blobDir = path.join(artifactsRoot, BLOBS_DIR, SHA256_PREFIX);
|
|
275
|
-
const metaDir = path.join(artifactsRoot, BLOB_META_DIR);
|
|
276
|
-
|
|
277
|
-
let cleaned = 0;
|
|
278
|
-
try {
|
|
279
|
-
const blobFiles = fs.readdirSync(blobDir);
|
|
280
|
-
for (const blobFile of blobFiles) {
|
|
281
|
-
// Skip non-hash files (e.g., temp files from atomicWriteBuffer)
|
|
282
|
-
if (!SHA256_HEX.test(blobFile)) continue;
|
|
283
|
-
|
|
284
|
-
const metaPath = path.join(metaDir, `${blobFile}.json`);
|
|
285
|
-
// Issue 4 fix: Use lock to prevent race between stat and delete.
|
|
286
|
-
// A concurrent process could write metadata between stat and delete,
|
|
287
|
-
// causing valid blob to be deleted while metadata remains.
|
|
288
|
-
withMetadataLock(metaPath, () => {
|
|
289
|
-
try {
|
|
290
|
-
fs.statSync(metaPath);
|
|
291
|
-
// Metadata exists - blob is not orphaned
|
|
292
|
-
} catch {
|
|
293
|
-
// Metadata does not exist - blob is orphaned, delete it
|
|
294
|
-
const blobPath = path.join(blobDir, blobFile);
|
|
295
|
-
try {
|
|
296
|
-
fs.rmSync(blobPath, { force: true });
|
|
297
|
-
cleaned++;
|
|
298
|
-
} catch {
|
|
299
|
-
// Best-effort cleanup - continue to next blob
|
|
300
|
-
}
|
|
301
|
-
}
|
|
302
|
-
});
|
|
303
|
-
}
|
|
304
|
-
} catch {
|
|
305
|
-
// Blobs directory doesn't exist or inaccessible - nothing to clean
|
|
306
|
-
}
|
|
307
|
-
return cleaned;
|
|
308
|
-
}
|
|
@@ -1,275 +0,0 @@
|
|
|
1
|
-
import { randomUUID } from "node:crypto";
|
|
2
|
-
import * as fs from "node:fs";
|
|
3
|
-
import * as path from "node:path";
|
|
4
|
-
import { assertSafePathId } from "../../utils/safe-paths.ts";
|
|
5
|
-
import { atomicWriteFile } from "../atomic-write.ts";
|
|
6
|
-
|
|
7
|
-
/**
|
|
8
|
-
* Represents a learned instinct that guides agent behavior.
|
|
9
|
-
* Instincts can be project-scoped or global.
|
|
10
|
-
*/
|
|
11
|
-
export interface Instinct {
|
|
12
|
-
/** Unique identifier for this instinct */
|
|
13
|
-
id: string;
|
|
14
|
-
/** What triggers this instinct */
|
|
15
|
-
trigger: string;
|
|
16
|
-
/** What action to take when triggered */
|
|
17
|
-
action: string;
|
|
18
|
-
/** Confidence level: 0.3 (low), 0.6 (medium), 0.9 (high) */
|
|
19
|
-
confidence: 0.3 | 0.6 | 0.9;
|
|
20
|
-
/** Whether this instinct applies to a project or globally */
|
|
21
|
-
scope: "project" | "global";
|
|
22
|
-
/** Project identifier (undefined for global instincts) */
|
|
23
|
-
projectId?: string;
|
|
24
|
-
/** ISO timestamp of when this instinct was created */
|
|
25
|
-
createdAt: string;
|
|
26
|
-
/** Examples/evidence supporting this instinct */
|
|
27
|
-
evidence: string[];
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
/** Input type for creating a new instinct (excludes auto-generated fields) */
|
|
31
|
-
export type NewInstinct = Omit<Instinct, "id" | "createdAt">;
|
|
32
|
-
|
|
33
|
-
const INSTINCT_FILE = "instincts.jsonl";
|
|
34
|
-
|
|
35
|
-
/**
|
|
36
|
-
* InstinctStore manages persistence of learned instincts using JSONL files.
|
|
37
|
-
* - Project instincts: `.crew/instincts/projects/{projectId}/instincts.jsonl`
|
|
38
|
-
* - Global instincts: `.crew/instincts/global/instincts.jsonl`
|
|
39
|
-
*/
|
|
40
|
-
export class InstinctStore {
|
|
41
|
-
private readonly crewRoot: string;
|
|
42
|
-
|
|
43
|
-
constructor(crewRoot: string) {
|
|
44
|
-
this.crewRoot = crewRoot;
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
/**
|
|
48
|
-
* Get the file path for project instincts
|
|
49
|
-
*/
|
|
50
|
-
private getProjectInstinctPath(projectId: string): string {
|
|
51
|
-
return path.join(this.crewRoot, "instincts", "projects", projectId, INSTINCT_FILE);
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
/**
|
|
55
|
-
* Get the file path for global instincts
|
|
56
|
-
*/
|
|
57
|
-
private getGlobalInstinctPath(): string {
|
|
58
|
-
return path.join(this.crewRoot, "instincts", "global", INSTINCT_FILE);
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
/**
|
|
62
|
-
* Ensure a directory exists, creating it recursively if needed
|
|
63
|
-
*/
|
|
64
|
-
private ensureDir(dirPath: string): void {
|
|
65
|
-
fs.mkdirSync(dirPath, { recursive: true });
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
/**
|
|
69
|
-
* Parse a JSONL file and return all instincts
|
|
70
|
-
*/
|
|
71
|
-
private readInstinctsFromFile(filePath: string): Instinct[] {
|
|
72
|
-
if (!fs.existsSync(filePath)) {
|
|
73
|
-
return [];
|
|
74
|
-
}
|
|
75
|
-
try {
|
|
76
|
-
const content = fs.readFileSync(filePath, "utf-8");
|
|
77
|
-
const lines = content.split("\n").filter((line) => line.trim() !== "");
|
|
78
|
-
return lines.map((line) => JSON.parse(line) as Instinct);
|
|
79
|
-
} catch {
|
|
80
|
-
// If file is corrupted, return empty array
|
|
81
|
-
return [];
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
/**
|
|
86
|
-
* Append a single instinct to a JSONL file
|
|
87
|
-
*/
|
|
88
|
-
private appendInstinctToFile(filePath: string, instinct: Instinct): void {
|
|
89
|
-
const dir = path.dirname(filePath);
|
|
90
|
-
this.ensureDir(dir);
|
|
91
|
-
// ST-3: read existing + append + atomic rewrite. appendFileSync has no fsync and
|
|
92
|
-
// can interleave bytes on concurrent writes. Callers should wrap this in
|
|
93
|
-
// withFileLockSync(filePath) to serialize concurrent RMW on the same file.
|
|
94
|
-
const existing = fs.existsSync(filePath) ? this.readInstinctsFromFile(filePath) : [];
|
|
95
|
-
existing.push(instinct);
|
|
96
|
-
const content = existing.map((i) => JSON.stringify(i)).join("\n") + "\n";
|
|
97
|
-
atomicWriteFile(filePath, content);
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
/**
|
|
101
|
-
* Rewrite a JSONL file with the given instincts
|
|
102
|
-
*/
|
|
103
|
-
private rewriteFile(filePath: string, instincts: Instinct[]): void {
|
|
104
|
-
const dir = path.dirname(filePath);
|
|
105
|
-
this.ensureDir(dir);
|
|
106
|
-
const content = instincts.map((i) => JSON.stringify(i)).join("\n") + "\n";
|
|
107
|
-
// ST-3: atomic write (temp + rename + fsync) — crash mid-writeFileSync truncates
|
|
108
|
-
// the JSONL and readInstinctsFromFile silently returns [] (all instincts lost).
|
|
109
|
-
atomicWriteFile(filePath, content);
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
/**
|
|
113
|
-
* Save a new instinct with auto-generated id and timestamp.
|
|
114
|
-
* Direct scope is determined by the instinct's scope field.
|
|
115
|
-
*
|
|
116
|
-
* @param instinct - The instinct to save (without id and createdAt)
|
|
117
|
-
* @returns The saved instinct with generated id and createdAt
|
|
118
|
-
*/
|
|
119
|
-
saveInstinct(instinct: NewInstinct): Instinct {
|
|
120
|
-
const savedInstinct: Instinct = {
|
|
121
|
-
...instinct,
|
|
122
|
-
id: randomUUID(),
|
|
123
|
-
createdAt: new Date().toISOString(),
|
|
124
|
-
};
|
|
125
|
-
|
|
126
|
-
if (savedInstinct.scope === "global") {
|
|
127
|
-
savedInstinct.projectId = undefined;
|
|
128
|
-
this.appendInstinctToFile(this.getGlobalInstinctPath(), savedInstinct);
|
|
129
|
-
} else {
|
|
130
|
-
if (!savedInstinct.projectId) {
|
|
131
|
-
throw new Error("Project-scoped instinct requires a projectId");
|
|
132
|
-
}
|
|
133
|
-
assertSafePathId("projectId", savedInstinct.projectId);
|
|
134
|
-
this.appendInstinctToFile(this.getProjectInstinctPath(savedInstinct.projectId), savedInstinct);
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
return savedInstinct;
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
/**
|
|
141
|
-
* Get all instincts, optionally filtered by scope.
|
|
142
|
-
*
|
|
143
|
-
* @param scope - Optional filter: 'project' or 'global'
|
|
144
|
-
* @returns Array of instincts matching the filter
|
|
145
|
-
*/
|
|
146
|
-
getInstincts(scope?: "project" | "global"): Instinct[] {
|
|
147
|
-
const results: Instinct[] = [];
|
|
148
|
-
|
|
149
|
-
if (!scope || scope === "project") {
|
|
150
|
-
const projectsDir = path.join(this.crewRoot, "instincts", "projects");
|
|
151
|
-
if (fs.existsSync(projectsDir)) {
|
|
152
|
-
for (const projectId of fs
|
|
153
|
-
.readdirSync(projectsDir, { withFileTypes: true })
|
|
154
|
-
.filter((e) => e.isDirectory())
|
|
155
|
-
.map((e) => e.name)) {
|
|
156
|
-
const filePath = path.join(projectsDir, projectId, INSTINCT_FILE);
|
|
157
|
-
results.push(...this.readInstinctsFromFile(filePath));
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
if (!scope || scope === "global") {
|
|
163
|
-
results.push(...this.readInstinctsFromFile(this.getGlobalInstinctPath()));
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
return results;
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
/**
|
|
170
|
-
* Get all instincts for a specific project.
|
|
171
|
-
* Includes both project-scoped instincts and global instincts.
|
|
172
|
-
*
|
|
173
|
-
* @param projectId - The project identifier
|
|
174
|
-
* @returns Array of instincts for the project
|
|
175
|
-
*/
|
|
176
|
-
getProjectInstincts(projectId: string): Instinct[] {
|
|
177
|
-
assertSafePathId("projectId", projectId);
|
|
178
|
-
const projectInstincts = this.readInstinctsFromFile(this.getProjectInstinctPath(projectId));
|
|
179
|
-
const globalInstincts = this.readInstinctsFromFile(this.getGlobalInstinctPath());
|
|
180
|
-
return [...projectInstincts, ...globalInstincts];
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
/**
|
|
184
|
-
* Promote a project-scoped instinct to global scope.
|
|
185
|
-
* Creates a copy in global instincts and removes from project.
|
|
186
|
-
*
|
|
187
|
-
* @param instinctId - The instinct id to promote
|
|
188
|
-
* @returns The promoted instinct, or null if not found
|
|
189
|
-
*/
|
|
190
|
-
promoteInstinct(instinctId: string): Instinct | null {
|
|
191
|
-
// Search in all project instinct files
|
|
192
|
-
const projectsDir = path.join(this.crewRoot, "instincts", "projects");
|
|
193
|
-
if (fs.existsSync(projectsDir)) {
|
|
194
|
-
for (const projectId of fs
|
|
195
|
-
.readdirSync(projectsDir, { withFileTypes: true })
|
|
196
|
-
.filter((e) => e.isDirectory())
|
|
197
|
-
.map((e) => e.name)) {
|
|
198
|
-
assertSafePathId("projectId", projectId);
|
|
199
|
-
const filePath = path.join(projectsDir, projectId, INSTINCT_FILE);
|
|
200
|
-
const instincts = this.readInstinctsFromFile(filePath);
|
|
201
|
-
const index = instincts.findIndex((i) => i.id === instinctId);
|
|
202
|
-
|
|
203
|
-
if (index !== -1) {
|
|
204
|
-
const instinct = instincts[index];
|
|
205
|
-
|
|
206
|
-
// Create promoted version (global)
|
|
207
|
-
const promotedInstinct: Instinct = {
|
|
208
|
-
...instinct,
|
|
209
|
-
id: randomUUID(), // New id for promoted instinct
|
|
210
|
-
scope: "global",
|
|
211
|
-
projectId: undefined,
|
|
212
|
-
createdAt: new Date().toISOString(),
|
|
213
|
-
};
|
|
214
|
-
|
|
215
|
-
// Add to global instincts
|
|
216
|
-
this.appendInstinctToFile(this.getGlobalInstinctPath(), promotedInstinct);
|
|
217
|
-
|
|
218
|
-
// Remove from project instincts
|
|
219
|
-
const updatedInstincts = instincts.filter((i) => i.id !== instinctId);
|
|
220
|
-
this.rewriteFile(filePath, updatedInstincts);
|
|
221
|
-
|
|
222
|
-
return promotedInstinct;
|
|
223
|
-
}
|
|
224
|
-
}
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
return null;
|
|
228
|
-
}
|
|
229
|
-
|
|
230
|
-
/**
|
|
231
|
-
* Delete an instinct by id.
|
|
232
|
-
*
|
|
233
|
-
* @param instinctId - The instinct id to delete
|
|
234
|
-
* @returns true if deleted, false if not found
|
|
235
|
-
*/
|
|
236
|
-
deleteInstinct(instinctId: string): boolean {
|
|
237
|
-
// Search in global instincts first
|
|
238
|
-
const globalPath = this.getGlobalInstinctPath();
|
|
239
|
-
let instincts = this.readInstinctsFromFile(globalPath);
|
|
240
|
-
let index = instincts.findIndex((i) => i.id === instinctId);
|
|
241
|
-
|
|
242
|
-
if (index !== -1) {
|
|
243
|
-
const updatedInstincts = instincts.filter((i) => i.id !== instinctId);
|
|
244
|
-
this.rewriteFile(globalPath, updatedInstincts);
|
|
245
|
-
return true;
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
// Search in project instincts
|
|
249
|
-
const projectsDir = path.join(this.crewRoot, "instincts", "projects");
|
|
250
|
-
if (fs.existsSync(projectsDir)) {
|
|
251
|
-
for (const projectId of fs
|
|
252
|
-
.readdirSync(projectsDir, { withFileTypes: true })
|
|
253
|
-
.filter((e) => e.isDirectory())
|
|
254
|
-
.map((e) => e.name)) {
|
|
255
|
-
assertSafePathId("projectId", projectId);
|
|
256
|
-
const filePath = path.join(projectsDir, projectId, INSTINCT_FILE);
|
|
257
|
-
instincts = this.readInstinctsFromFile(filePath);
|
|
258
|
-
index = instincts.findIndex((i) => i.id === instinctId);
|
|
259
|
-
|
|
260
|
-
if (index !== -1) {
|
|
261
|
-
const updatedInstincts = instincts.filter((i) => i.id !== instinctId);
|
|
262
|
-
this.rewriteFile(filePath, updatedInstincts);
|
|
263
|
-
return true;
|
|
264
|
-
}
|
|
265
|
-
}
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
return false;
|
|
269
|
-
}
|
|
270
|
-
}
|
|
271
|
-
|
|
272
|
-
export {
|
|
273
|
-
getGlobalStorageDir,
|
|
274
|
-
getProjectStorageDir,
|
|
275
|
-
} from "../../utils/project-detector.ts";
|