@astrosheep/keiyaku 2.9.10 → 2.9.12
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 +86 -45
- package/build/.tsbuildinfo +1 -1
- package/build/agents/providers/claude-agent-sdk/adapter.js +15 -2
- package/build/cli/commands/contract/bind/meta.js +4 -4
- package/build/cli/commands/metadata.js +3 -2
- package/build/cli/commands/projection/kill/handler.js +4 -5
- package/build/cli/commands/shared.js +1 -1
- package/build/cli/commands/task/catalog.js +2 -0
- package/build/cli/commands/task/compose/handler.js +18 -0
- package/build/cli/commands/task/compose/meta.js +10 -0
- package/build/cli/flags.js +5 -1
- package/build/cli/index.js +11 -6
- package/build/cli/parse-flags.js +21 -21
- package/build/cli/parse-metadata.js +5 -2
- package/build/cli/parse-selectors.js +4 -4
- package/build/cli/parse.js +23 -23
- package/build/cli/projection-address.js +7 -7
- package/build/cli/render/task.js +27 -0
- package/build/cli/types.js +1 -1
- package/build/core/addressing.js +3 -3
- package/build/core/call/context.js +3 -3
- package/build/core/call/prompt.js +1 -1
- package/build/core/contract-view.js +1 -1
- package/build/core/draft.js +51 -22
- package/build/core/projection/generation/model.js +1 -1
- package/build/core/projection/generation/projection-generation-runner.js +13 -3
- package/build/core/projection/generation/transitions.js +10 -0
- package/build/core/projection/projection-history.js +1 -1
- package/build/core/projection/projection-kill.js +5 -4
- package/build/core/projection/projection-runner-lock.js +58 -229
- package/build/core/projection/projection-wait.js +2 -2
- package/build/core/projection/projection-wake.js +2 -0
- package/build/core/repository-ledger/claim-evidence.js +1 -1
- package/build/core/repository-ledger/current-state-store.js +455 -337
- package/build/core/repository-ledger/read-model.js +3 -3
- package/build/core/repository-ledger/write-transaction.js +15 -13
- package/build/core/sqlite-process-lifetime-lock.js +194 -0
- package/build/core/task/compose.js +327 -0
- package/build/core/task/index.js +1 -0
- package/build/core/task/settlement-git.js +69 -26
- package/build/core/task/task-git-store.js +1 -0
- package/build/core/task/task-store-repository.js +1 -0
- package/build/flow-error.js +6 -1
- package/build/generated/version.js +2 -2
- package/package.json +2 -2
- package/skills/keiyaku-akuma/SKILL.md +6 -1
- package/skills/keiyaku-task/SKILL.md +23 -1
- package/skills/keiyaku-workflow/SKILL.md +33 -18
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { openTaskAdmissionEvidenceReader, readTaskAdmissionEvidenceAtCommit, } from "../task/settlement-git.js";
|
|
2
2
|
import { repositoryDeliveryRef, } from "./codec.js";
|
|
3
3
|
import { observeRepositoryLedgerHead, readAcceptedRepositoryFold } from "./accepted-fold-read.js";
|
|
4
|
-
import { advanceRepositoryCurrentState,
|
|
4
|
+
import { advanceRepositoryCurrentState, publishRepositoryCurrentState, readPinnedCurrentContract, readPinnedRepositoryLifecycle, readRepositoryCurrentStateNodeIds, readRepositoryCurrentStatePin, readRepositoryCurrentStatePredecessor } from "./current-state-store.js";
|
|
5
5
|
import { IncrementalLedgerValidationError, readIncrementalRepositorySegment } from "./incremental-read.js";
|
|
6
6
|
import { RepositoryObjectError } from "./git-object-store.js";
|
|
7
7
|
/** Public lifecycle state derived only from the accepted repository-ledger fold. */
|
|
@@ -366,7 +366,8 @@ export async function readRepositoryLifecycle(cwd, options = {}) {
|
|
|
366
366
|
const pinned = await readPinnedRepositoryLifecycle(cwd, observedHead, options.signal, { includeTopology: options.includeTopology });
|
|
367
367
|
if (pinned)
|
|
368
368
|
return deepFreeze(pinned);
|
|
369
|
-
const
|
|
369
|
+
const candidatePriorHead = observedHead === null ? null : await readRepositoryCurrentStatePredecessor(cwd, observedHead, options.signal);
|
|
370
|
+
const priorHead = candidatePriorHead === null ? null : await readRepositoryCurrentStatePin(cwd, candidatePriorHead, options.signal);
|
|
370
371
|
if (priorHead && observedHead && priorHead !== observedHead) {
|
|
371
372
|
try {
|
|
372
373
|
const acceptedObjectIds = await readRepositoryCurrentStateNodeIds(cwd, priorHead, options.signal);
|
|
@@ -391,7 +392,6 @@ export async function readRepositoryLifecycle(cwd, options = {}) {
|
|
|
391
392
|
|| (error instanceof RepositoryObjectError && error.reason !== "git-failure");
|
|
392
393
|
if (!untrustedDelta)
|
|
393
394
|
throw error;
|
|
394
|
-
await discardRepositoryCurrentState(cwd, options.signal);
|
|
395
395
|
}
|
|
396
396
|
}
|
|
397
397
|
}
|
|
@@ -80,22 +80,22 @@ async function assertAuthoritativeCommitTipClosure(cwd, coordinates, operations)
|
|
|
80
80
|
checked.add(operation.newOid);
|
|
81
81
|
}
|
|
82
82
|
}
|
|
83
|
-
export async function buildLifecycleEntry(cwd, entry, expectedLedgerHead) {
|
|
84
|
-
const
|
|
83
|
+
export async function buildLifecycleEntry(cwd, entry, expectedLedgerHead, coordinates) {
|
|
84
|
+
const resolvedCoordinates = coordinates ?? await deriveHostGitCoordinates(cwd);
|
|
85
85
|
if (expectedLedgerHead !== null)
|
|
86
|
-
assertHostObjectId(
|
|
86
|
+
assertHostObjectId(resolvedCoordinates, expectedLedgerHead);
|
|
87
87
|
const evidence = evidenceObjectId(entry);
|
|
88
88
|
if (evidence !== null) {
|
|
89
|
-
assertHostObjectId(
|
|
90
|
-
await assertReadableCommit(cwd,
|
|
89
|
+
assertHostObjectId(resolvedCoordinates, evidence);
|
|
90
|
+
await assertReadableCommit(cwd, resolvedCoordinates, evidence);
|
|
91
91
|
}
|
|
92
92
|
const parents = [
|
|
93
93
|
...(expectedLedgerHead === null ? [] : [expectedLedgerHead]),
|
|
94
94
|
...(evidence === null ? [] : [evidence]),
|
|
95
95
|
];
|
|
96
|
-
const args = ["commit-tree",
|
|
96
|
+
const args = ["commit-tree", resolvedCoordinates.emptyTree, ...parents.flatMap((parent) => ["-p", parent])];
|
|
97
97
|
const result = await runGitProcess(cwd, args, {
|
|
98
|
-
input: formatLifecycleEntry(entry,
|
|
98
|
+
input: formatLifecycleEntry(entry, resolvedCoordinates.objectFormat),
|
|
99
99
|
env: {
|
|
100
100
|
GIT_AUTHOR_NAME: "Keiyaku",
|
|
101
101
|
GIT_AUTHOR_EMAIL: "keiyaku@localhost",
|
|
@@ -110,16 +110,17 @@ export async function buildLifecycleEntry(cwd, entry, expectedLedgerHead) {
|
|
|
110
110
|
throw new Error(`cannot build ${entry.kind} ledger object: ${detail}`, { cause: result.error });
|
|
111
111
|
}
|
|
112
112
|
const objectId = result.stdout.trim();
|
|
113
|
-
assertHostObjectId(
|
|
114
|
-
return { entry, objectId, expectedLedgerHead, parents, coordinates };
|
|
113
|
+
assertHostObjectId(resolvedCoordinates, objectId);
|
|
114
|
+
return { entry, objectId, expectedLedgerHead, parents, coordinates: resolvedCoordinates };
|
|
115
115
|
}
|
|
116
|
-
export async function buildLifecycleTail(cwd, entries, expectedLedgerHead) {
|
|
116
|
+
export async function buildLifecycleTail(cwd, entries, expectedLedgerHead, coordinates) {
|
|
117
117
|
if (entries.length === 0)
|
|
118
118
|
throw new Error("a lifecycle tail requires at least one entry");
|
|
119
|
+
const resolvedCoordinates = coordinates ?? await deriveHostGitCoordinates(cwd);
|
|
119
120
|
const built = [];
|
|
120
121
|
let parent = expectedLedgerHead;
|
|
121
122
|
for (const entry of entries) {
|
|
122
|
-
const next = await buildLifecycleEntry(cwd, entry, parent);
|
|
123
|
+
const next = await buildLifecycleEntry(cwd, entry, parent, resolvedCoordinates);
|
|
123
124
|
built.push(next);
|
|
124
125
|
parent = next.objectId;
|
|
125
126
|
}
|
|
@@ -199,7 +200,8 @@ async function buildTransactionTail(input) {
|
|
|
199
200
|
throw new Error(`bind transaction repeats contract ${contract}`);
|
|
200
201
|
if (input.verb !== "bind" && causalParent === null)
|
|
201
202
|
throw new Error(`${input.verb} transaction has no accepted lifecycle predecessor for ${contract}`);
|
|
202
|
-
const
|
|
203
|
+
const coordinates = await deriveHostGitCoordinates(input.cwd);
|
|
204
|
+
const tail = await buildLifecycleTail(input.cwd, input.entries, causalParent, coordinates);
|
|
203
205
|
const transaction = await buildLifecycleTransactionNode({
|
|
204
206
|
cwd: input.cwd,
|
|
205
207
|
verb: input.verb,
|
|
@@ -331,7 +333,7 @@ export async function publishAuthoritativeTransaction(cwd, transaction, options
|
|
|
331
333
|
assertAuthority(transaction.target.expectedOid === entry.data.targetHead, "claim target CAS must equal targetHead");
|
|
332
334
|
assertAuthority(transaction.delivery.ref === repositoryDeliveryRef(entry.contract), "claim delivery ref does not name its contract");
|
|
333
335
|
assertAuthority(transaction.delivery.expectedOid === entry.data.deliveryHead, "claim delivery CAS must equal deliveryHead");
|
|
334
|
-
await assertHonestClaimEvidence(cwd, entry.data);
|
|
336
|
+
await assertHonestClaimEvidence(cwd, entry.data, { coordinates: built.transaction.coordinates });
|
|
335
337
|
operations.push({ kind: "update", ref: transaction.target.ref, expectedOldOid: transaction.target.expectedOid, newOid: entry.data.mergeCommit }, { kind: "delete", ref: transaction.delivery.ref, expectedOldOid: transaction.delivery.expectedOid });
|
|
336
338
|
}
|
|
337
339
|
const write = await publishLifecycleWrite(cwd, built.transaction, final, operations, options.replayPlan, options.transactionRunner);
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import { DatabaseSync } from "node:sqlite";
|
|
3
|
+
const SQLITE_BUSY = 5;
|
|
4
|
+
const SUPPORTED_PLATFORMS = new Set(["darwin", "linux", "win32"]);
|
|
5
|
+
export class SqliteProcessLifetimeLockError extends Error {
|
|
6
|
+
reason;
|
|
7
|
+
code = "SQLITE_PROCESS_LIFETIME_LOCK_UNAVAILABLE";
|
|
8
|
+
constructor(message, reason, options) {
|
|
9
|
+
super(message, options);
|
|
10
|
+
this.reason = reason;
|
|
11
|
+
this.name = "SqliteProcessLifetimeLockError";
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
export class SqliteProcessLifetimeLockUnsupportedError extends Error {
|
|
15
|
+
code = "SQLITE_PROCESS_LIFETIME_LOCK_UNSUPPORTED";
|
|
16
|
+
constructor(platform) {
|
|
17
|
+
super(`SQLite process-lifetime locks are unsupported on platform '${platform}'`);
|
|
18
|
+
this.name = "SqliteProcessLifetimeLockUnsupportedError";
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
export function isSqliteProcessLifetimeLockPlatformSupported(platform = process.platform) {
|
|
22
|
+
return SUPPORTED_PLATFORMS.has(platform);
|
|
23
|
+
}
|
|
24
|
+
export function sqliteProcessLifetimeLockErrorDetail(error) {
|
|
25
|
+
return error instanceof Error ? error.message : String(error);
|
|
26
|
+
}
|
|
27
|
+
export function isSqliteProcessLifetimeLockContention(error) {
|
|
28
|
+
const code = typeof error === "object" && error !== null && "code" in error
|
|
29
|
+
? String(error.code)
|
|
30
|
+
: "";
|
|
31
|
+
const errcode = typeof error === "object" && error !== null && "errcode" in error
|
|
32
|
+
? error.errcode
|
|
33
|
+
: undefined;
|
|
34
|
+
const message = sqliteProcessLifetimeLockErrorDetail(error).toLowerCase();
|
|
35
|
+
return errcode === SQLITE_BUSY || code === "ERR_SQLITE_BUSY" || code === "ERR_SQLITE_LOCKED"
|
|
36
|
+
|| message.includes("database is locked") || message.includes("database is busy");
|
|
37
|
+
}
|
|
38
|
+
function assertPlatform(platform) {
|
|
39
|
+
if (!isSqliteProcessLifetimeLockPlatformSupported(platform)) {
|
|
40
|
+
throw new SqliteProcessLifetimeLockUnsupportedError(platform);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
function assertBusyTimeout(busyTimeoutMs) {
|
|
44
|
+
if (!Number.isSafeInteger(busyTimeoutMs) || busyTimeoutMs < 0) {
|
|
45
|
+
throw new SqliteProcessLifetimeLockError("SQLite process-lifetime lock busy timeout must be a non-negative safe integer", "invalid");
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
function journalMode(database) {
|
|
49
|
+
const row = database.prepare("PRAGMA journal_mode").get();
|
|
50
|
+
return typeof row?.journal_mode === "string" ? row.journal_mode.toLowerCase() : undefined;
|
|
51
|
+
}
|
|
52
|
+
function assertSchema(database) {
|
|
53
|
+
database.prepare("SELECT singleton FROM lock_anchor LIMIT 1").get();
|
|
54
|
+
}
|
|
55
|
+
function closeTransaction(database) {
|
|
56
|
+
let failure;
|
|
57
|
+
try {
|
|
58
|
+
database.exec("ROLLBACK");
|
|
59
|
+
}
|
|
60
|
+
catch (error) {
|
|
61
|
+
failure = error;
|
|
62
|
+
}
|
|
63
|
+
try {
|
|
64
|
+
database.close();
|
|
65
|
+
}
|
|
66
|
+
catch (error) {
|
|
67
|
+
failure ??= error;
|
|
68
|
+
}
|
|
69
|
+
return failure;
|
|
70
|
+
}
|
|
71
|
+
function throwLockError(prefix, error) {
|
|
72
|
+
if (error instanceof SqliteProcessLifetimeLockError || error instanceof SqliteProcessLifetimeLockUnsupportedError)
|
|
73
|
+
throw error;
|
|
74
|
+
if (isSqliteProcessLifetimeLockContention(error)) {
|
|
75
|
+
throw new SqliteProcessLifetimeLockError(`${prefix} is already held`, "busy", { cause: error });
|
|
76
|
+
}
|
|
77
|
+
throw new SqliteProcessLifetimeLockError(`${prefix} failed: ${sqliteProcessLifetimeLockErrorDetail(error)}`, "open-failed", { cause: error });
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Creates only a rollback-journal schema anchor. The empty database persists no
|
|
81
|
+
* ownership facts; an open transaction is the complete ownership signal.
|
|
82
|
+
*/
|
|
83
|
+
export function initializeSqliteProcessLifetimeLockDatabase(lockPath, platform = process.platform) {
|
|
84
|
+
assertPlatform(platform);
|
|
85
|
+
let database;
|
|
86
|
+
try {
|
|
87
|
+
database = new DatabaseSync(lockPath);
|
|
88
|
+
database.exec("PRAGMA busy_timeout=0");
|
|
89
|
+
database.exec("PRAGMA journal_mode=DELETE");
|
|
90
|
+
database.exec("CREATE TABLE IF NOT EXISTS lock_anchor (singleton INTEGER PRIMARY KEY CHECK (singleton = 1))");
|
|
91
|
+
assertSchema(database);
|
|
92
|
+
if (journalMode(database) !== "delete") {
|
|
93
|
+
throw new SqliteProcessLifetimeLockError("SQLite process-lifetime lock database does not use rollback-journal mode", "invalid");
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
catch (error) {
|
|
97
|
+
throwLockError("SQLite process-lifetime lock database initialization", error);
|
|
98
|
+
}
|
|
99
|
+
finally {
|
|
100
|
+
try {
|
|
101
|
+
database?.close();
|
|
102
|
+
}
|
|
103
|
+
catch { /* the causal initialization error is retained */ }
|
|
104
|
+
}
|
|
105
|
+
return lockPath;
|
|
106
|
+
}
|
|
107
|
+
export function openSqliteProcessLifetimeLockTransaction(input) {
|
|
108
|
+
const platform = input.platform ?? process.platform;
|
|
109
|
+
const busyTimeoutMs = input.busyTimeoutMs ?? 0;
|
|
110
|
+
assertPlatform(platform);
|
|
111
|
+
assertBusyTimeout(busyTimeoutMs);
|
|
112
|
+
if (!input.create) {
|
|
113
|
+
try {
|
|
114
|
+
if (!fs.lstatSync(input.path).isFile()) {
|
|
115
|
+
throw new SqliteProcessLifetimeLockError("SQLite process-lifetime lock database is not a regular file", "invalid");
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
catch (error) {
|
|
119
|
+
if (error instanceof SqliteProcessLifetimeLockError)
|
|
120
|
+
throw error;
|
|
121
|
+
throw new SqliteProcessLifetimeLockError(`SQLite process-lifetime lock database is not initialized: ${sqliteProcessLifetimeLockErrorDetail(error)}`, "open-failed", { cause: error });
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
let database;
|
|
125
|
+
try {
|
|
126
|
+
database = new DatabaseSync(input.path);
|
|
127
|
+
database.exec(`PRAGMA busy_timeout=${busyTimeoutMs}`);
|
|
128
|
+
if (input.create) {
|
|
129
|
+
database.exec("PRAGMA journal_mode=DELETE");
|
|
130
|
+
database.exec("CREATE TABLE IF NOT EXISTS lock_anchor (singleton INTEGER PRIMARY KEY CHECK (singleton = 1))");
|
|
131
|
+
}
|
|
132
|
+
database.exec(`BEGIN ${input.mode.toUpperCase()}`);
|
|
133
|
+
// A DEFERRED transaction becomes the projection guard only after this read
|
|
134
|
+
// acquires its SHARED lock. Keep this inside every transaction mode.
|
|
135
|
+
assertSchema(database);
|
|
136
|
+
if (journalMode(database) !== "delete") {
|
|
137
|
+
throw new SqliteProcessLifetimeLockError("SQLite process-lifetime lock database does not use rollback-journal mode", "invalid");
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
catch (error) {
|
|
141
|
+
if (database !== undefined)
|
|
142
|
+
closeTransaction(database);
|
|
143
|
+
throwLockError("SQLite process-lifetime lock acquisition", error);
|
|
144
|
+
}
|
|
145
|
+
let closed = false;
|
|
146
|
+
return {
|
|
147
|
+
path: input.path,
|
|
148
|
+
database,
|
|
149
|
+
close() {
|
|
150
|
+
if (closed)
|
|
151
|
+
return;
|
|
152
|
+
closed = true;
|
|
153
|
+
const failure = closeTransaction(database);
|
|
154
|
+
if (failure !== undefined) {
|
|
155
|
+
throw new SqliteProcessLifetimeLockError(`SQLite process-lifetime lock release failed: ${sqliteProcessLifetimeLockErrorDetail(failure)}`, "release-failed", { cause: failure });
|
|
156
|
+
}
|
|
157
|
+
},
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
function waitForRetry(milliseconds, signal) {
|
|
161
|
+
return new Promise((resolve, reject) => {
|
|
162
|
+
const abort = () => {
|
|
163
|
+
clearTimeout(timer);
|
|
164
|
+
reject(signal?.reason ?? new DOMException("operation aborted", "AbortError"));
|
|
165
|
+
};
|
|
166
|
+
const timer = setTimeout(() => {
|
|
167
|
+
signal?.removeEventListener("abort", abort);
|
|
168
|
+
resolve();
|
|
169
|
+
}, milliseconds);
|
|
170
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
/** Waits for the sole BEGIN IMMEDIATE owner. Cancellation is the only time bound. */
|
|
174
|
+
export async function acquireSqliteProcessLifetimeLock(input) {
|
|
175
|
+
const retryMs = input.retryMs ?? 25;
|
|
176
|
+
assertBusyTimeout(retryMs);
|
|
177
|
+
for (;;) {
|
|
178
|
+
input.signal?.throwIfAborted();
|
|
179
|
+
try {
|
|
180
|
+
return openSqliteProcessLifetimeLockTransaction({
|
|
181
|
+
path: input.path,
|
|
182
|
+
mode: "immediate",
|
|
183
|
+
busyTimeoutMs: 0,
|
|
184
|
+
create: true,
|
|
185
|
+
platform: input.platform,
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
catch (error) {
|
|
189
|
+
if (!(error instanceof SqliteProcessLifetimeLockError) || error.reason !== "busy")
|
|
190
|
+
throw error;
|
|
191
|
+
await waitForRetry(retryMs, input.signal);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
}
|
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
import { FlowError } from "../../flow-error.js";
|
|
2
|
+
import { taskIdentifierSlug, IdentifierSlugError } from "../identifier-slug.js";
|
|
3
|
+
import { buildTaskBoardFromDocuments, requireHealthy, resolveTaskId } from "./board.js";
|
|
4
|
+
import { formatTaskCoordinate, parseTaskCoordinate } from "./coordinate.js";
|
|
5
|
+
import { advancedTaskUpdatedAt } from "./model.js";
|
|
6
|
+
function atLine(line, message) {
|
|
7
|
+
throw new FlowError("INVALID_TARGET", `task compose line ${line}: ${message}`);
|
|
8
|
+
}
|
|
9
|
+
function parseRelationValues(line, field, value) {
|
|
10
|
+
if (value === "")
|
|
11
|
+
return [];
|
|
12
|
+
const values = value.split(",");
|
|
13
|
+
const references = values.map((entry) => {
|
|
14
|
+
if (!entry.startsWith("@"))
|
|
15
|
+
atLine(line, `${field}= accepts comma-separated @COORDINATE references or an explicit empty assignment`);
|
|
16
|
+
try {
|
|
17
|
+
return parseTaskCoordinate(entry.slice(1), `${field} coordinate`).coordinate;
|
|
18
|
+
}
|
|
19
|
+
catch (error) {
|
|
20
|
+
if (error instanceof FlowError)
|
|
21
|
+
atLine(line, `${field}= accepts comma-separated @COORDINATE references or an explicit empty assignment`);
|
|
22
|
+
throw error;
|
|
23
|
+
}
|
|
24
|
+
});
|
|
25
|
+
if (new Set(references).size !== references.length)
|
|
26
|
+
atLine(line, `${field}= cannot repeat a coordinate`);
|
|
27
|
+
return references;
|
|
28
|
+
}
|
|
29
|
+
function parseAssignments(line, tokens) {
|
|
30
|
+
let clearParent = false;
|
|
31
|
+
const relations = {};
|
|
32
|
+
const declared = new Set();
|
|
33
|
+
for (const token of tokens) {
|
|
34
|
+
const match = /^(parent|needs|supersedes|relates)=(.*)$/.exec(token);
|
|
35
|
+
if (!match)
|
|
36
|
+
atLine(line, "inline declarations must use parent=, needs=, supersedes=, or relates=");
|
|
37
|
+
const field = match[1];
|
|
38
|
+
const value = match[2];
|
|
39
|
+
if (declared.has(field))
|
|
40
|
+
atLine(line, `${field}= may appear only once`);
|
|
41
|
+
declared.add(field);
|
|
42
|
+
if (field === "parent") {
|
|
43
|
+
if (value !== "")
|
|
44
|
+
atLine(line, "parent= only clears the parent; use nesting to assign one");
|
|
45
|
+
clearParent = true;
|
|
46
|
+
}
|
|
47
|
+
else {
|
|
48
|
+
relations[field] = parseRelationValues(line, field, value);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return { clearParent, relations };
|
|
52
|
+
}
|
|
53
|
+
function declarationTokens(line, content, kind) {
|
|
54
|
+
if (/\[(?:parent|needs|supersedes|relates)=/.test(content)) {
|
|
55
|
+
atLine(line, "inline declarations use whitespace-separated field=value tokens, not brackets");
|
|
56
|
+
}
|
|
57
|
+
if (kind === "@") {
|
|
58
|
+
const [reference, ...assignments] = content.slice(1).split(/\s+/);
|
|
59
|
+
if (!reference)
|
|
60
|
+
atLine(line, "task references must be exactly @COORDINATE followed only by inline declarations");
|
|
61
|
+
return { reference, ...parseAssignments(line, assignments) };
|
|
62
|
+
}
|
|
63
|
+
const source = content.slice(1).trim();
|
|
64
|
+
if (!source)
|
|
65
|
+
atLine(line, "+ must be followed by a task title");
|
|
66
|
+
const tokens = source.split(/\s+/);
|
|
67
|
+
const assignmentStart = tokens.findIndex((token) => token.includes("="));
|
|
68
|
+
const titleTokens = assignmentStart === -1 ? tokens : tokens.slice(0, assignmentStart);
|
|
69
|
+
if (titleTokens.length === 0)
|
|
70
|
+
atLine(line, "+ must be followed by a task title");
|
|
71
|
+
const assignments = assignmentStart === -1 ? [] : tokens.slice(assignmentStart);
|
|
72
|
+
return { title: titleTokens.join(" "), ...parseAssignments(line, assignments) };
|
|
73
|
+
}
|
|
74
|
+
export function parseTaskCompositionSketch(input) {
|
|
75
|
+
if (!input.trim())
|
|
76
|
+
throw new FlowError("EMPTY_PARAM", "task compose sketch cannot be blank");
|
|
77
|
+
const nodes = [];
|
|
78
|
+
const taskAtDepth = new Map();
|
|
79
|
+
let pendingBodyBlanks;
|
|
80
|
+
let activeBody;
|
|
81
|
+
for (const [offset, raw] of input.split(/\r?\n/).entries()) {
|
|
82
|
+
const line = offset + 1;
|
|
83
|
+
if (/\t/.test(raw))
|
|
84
|
+
atLine(line, "uses spaces only; indentation is two spaces per tree level");
|
|
85
|
+
const indent = /^( *)/.exec(raw)[1].length;
|
|
86
|
+
if (indent % 2 !== 0)
|
|
87
|
+
atLine(line, "indentation must use whole two-space levels");
|
|
88
|
+
const content = raw.slice(indent).trimEnd();
|
|
89
|
+
const depth = indent / 2;
|
|
90
|
+
if (!content) {
|
|
91
|
+
if (activeBody) {
|
|
92
|
+
if (pendingBodyBlanks?.parent === activeBody)
|
|
93
|
+
pendingBodyBlanks.count += 1;
|
|
94
|
+
else
|
|
95
|
+
pendingBodyBlanks = { parent: activeBody, count: 1 };
|
|
96
|
+
}
|
|
97
|
+
else {
|
|
98
|
+
pendingBodyBlanks = undefined;
|
|
99
|
+
}
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
if (!content.startsWith("+") && !content.startsWith("@")) {
|
|
103
|
+
const parentDepth = [...taskAtDepth.keys()].filter((candidate) => candidate < depth).sort((a, b) => b - a)[0];
|
|
104
|
+
const parent = parentDepth === undefined ? undefined : taskAtDepth.get(parentDepth);
|
|
105
|
+
if (!parent?.title)
|
|
106
|
+
atLine(line, "bare prose is allowed only inside a new + task body");
|
|
107
|
+
if (pendingBodyBlanks?.parent === parent)
|
|
108
|
+
parent.body.push(...Array(pendingBodyBlanks.count).fill(""));
|
|
109
|
+
pendingBodyBlanks = undefined;
|
|
110
|
+
parent.body.push(raw.slice((parent.depth + 1) * 2));
|
|
111
|
+
activeBody = parent;
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
pendingBodyBlanks = undefined;
|
|
115
|
+
activeBody = undefined;
|
|
116
|
+
const kind = content.startsWith("+") ? "+" : "@";
|
|
117
|
+
const parsed = declarationTokens(line, content, kind);
|
|
118
|
+
for (const existingDepth of [...taskAtDepth.keys()])
|
|
119
|
+
if (existingDepth >= depth)
|
|
120
|
+
taskAtDepth.delete(existingDepth);
|
|
121
|
+
if (depth > 0 && !taskAtDepth.has(depth - 1))
|
|
122
|
+
atLine(line, "cannot indent below a missing parent task line");
|
|
123
|
+
const node = { line, depth, body: [], ...parsed };
|
|
124
|
+
nodes.push(node);
|
|
125
|
+
taskAtDepth.set(depth, node);
|
|
126
|
+
}
|
|
127
|
+
if (nodes.length === 0)
|
|
128
|
+
throw new FlowError("EMPTY_PARAM", "task compose sketch cannot be blank");
|
|
129
|
+
return nodes;
|
|
130
|
+
}
|
|
131
|
+
function requireHealthyFinalCompositionBoard(board, lines) {
|
|
132
|
+
const disease = board.diseases[0];
|
|
133
|
+
if (!disease)
|
|
134
|
+
return;
|
|
135
|
+
const coordinate = [disease.id, ...(disease.relatedIds ?? [])].find((candidate) => candidate !== undefined && lines.has(candidate));
|
|
136
|
+
if (coordinate !== undefined)
|
|
137
|
+
atLine(lines.get(coordinate), disease.message);
|
|
138
|
+
requireHealthy(board);
|
|
139
|
+
}
|
|
140
|
+
function documentFromView(task) {
|
|
141
|
+
return {
|
|
142
|
+
id: task.id, namespace: task.namespace, coordinate: task.coordinate, title: task.title,
|
|
143
|
+
state: task.state, pri: task.pri, needs: [...task.needs], parent: task.parent,
|
|
144
|
+
from: [...task.from], supersedes: [...task.supersedes], relatesTo: [...task.relatesTo],
|
|
145
|
+
createdAt: task.createdAt, ...(task.updatedAt === undefined ? {} : { updatedAt: task.updatedAt }),
|
|
146
|
+
creator: task.creator, ...(task.startedAt === undefined ? {} : { startedAt: task.startedAt }),
|
|
147
|
+
...(task.contractId === undefined ? {} : { contractId: task.contractId }), body: task.body,
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
function allocateCoordinate(title, namespace, occupied, line) {
|
|
151
|
+
for (let ordinal = 1; Number.isSafeInteger(ordinal); ordinal += 1) {
|
|
152
|
+
try {
|
|
153
|
+
const localId = taskIdentifierSlug(title, ordinal === 1 ? "" : `-${ordinal}`);
|
|
154
|
+
const coordinate = formatTaskCoordinate(namespace, localId);
|
|
155
|
+
if (!occupied.has(coordinate))
|
|
156
|
+
return coordinate;
|
|
157
|
+
}
|
|
158
|
+
catch (error) {
|
|
159
|
+
if (error instanceof IdentifierSlugError)
|
|
160
|
+
atLine(line, `task title ${error.message}`);
|
|
161
|
+
throw error;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
throw new FlowError("INTERNAL_STATE", "task compose allocation exceeded the safe integer range");
|
|
165
|
+
}
|
|
166
|
+
function same(left, right) {
|
|
167
|
+
return left.length === right.length && left.every((value, index) => value === right[index]);
|
|
168
|
+
}
|
|
169
|
+
function resolvedRelations(board, node) {
|
|
170
|
+
const result = {};
|
|
171
|
+
for (const [name, values] of Object.entries(node.relations)) {
|
|
172
|
+
try {
|
|
173
|
+
const resolved = values.map((value) => resolveTaskId(board, value));
|
|
174
|
+
if (new Set(resolved).size !== resolved.length)
|
|
175
|
+
atLine(node.line, `${name}= resolves the same coordinate more than once`);
|
|
176
|
+
result[name] = resolved;
|
|
177
|
+
}
|
|
178
|
+
catch (error) {
|
|
179
|
+
if (error instanceof FlowError)
|
|
180
|
+
atLine(node.line, error.message);
|
|
181
|
+
throw error;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
return result;
|
|
185
|
+
}
|
|
186
|
+
/** Build the composition entirely from one board observation. Persistence is caller-owned. */
|
|
187
|
+
export function planTaskComposition(board, input) {
|
|
188
|
+
requireHealthy(board);
|
|
189
|
+
const now = input.now();
|
|
190
|
+
const parsed = parseTaskCompositionSketch(input.sketch);
|
|
191
|
+
const occupied = new Set(board.byId.keys());
|
|
192
|
+
const resolved = [];
|
|
193
|
+
const declared = new Set();
|
|
194
|
+
const allocations = [];
|
|
195
|
+
const parents = new Map();
|
|
196
|
+
for (const node of parsed) {
|
|
197
|
+
if (node.depth > 0 && !parents.has(node.depth - 1))
|
|
198
|
+
atLine(node.line, "cannot indent below a missing parent line");
|
|
199
|
+
for (const depth of [...parents.keys()])
|
|
200
|
+
if (depth >= node.depth)
|
|
201
|
+
parents.delete(depth);
|
|
202
|
+
let coordinate;
|
|
203
|
+
let existing;
|
|
204
|
+
if (node.reference) {
|
|
205
|
+
try {
|
|
206
|
+
coordinate = resolveTaskId(board, node.reference);
|
|
207
|
+
}
|
|
208
|
+
catch (error) {
|
|
209
|
+
if (error instanceof FlowError)
|
|
210
|
+
atLine(node.line, error.message);
|
|
211
|
+
throw error;
|
|
212
|
+
}
|
|
213
|
+
existing = board.byId.get(coordinate);
|
|
214
|
+
}
|
|
215
|
+
else {
|
|
216
|
+
coordinate = allocateCoordinate(node.title, input.namespace, occupied, node.line);
|
|
217
|
+
occupied.add(coordinate);
|
|
218
|
+
allocations.push({ title: node.title, coordinate });
|
|
219
|
+
}
|
|
220
|
+
if (declared.has(coordinate))
|
|
221
|
+
atLine(node.line, `task ${coordinate} is declared more than once`);
|
|
222
|
+
declared.add(coordinate);
|
|
223
|
+
const parent = node.depth > 0 ? parents.get(node.depth - 1) : node.clearParent ? null : undefined;
|
|
224
|
+
if (node.depth > 0 && node.clearParent)
|
|
225
|
+
atLine(node.line, "cannot combine nesting with parent=");
|
|
226
|
+
if (parent === coordinate)
|
|
227
|
+
atLine(node.line, `task ${coordinate} cannot be its own parent`);
|
|
228
|
+
if (parent && (board.byId.get(parent)?.state === "done" || board.byId.get(parent)?.state === "drop")) {
|
|
229
|
+
atLine(node.line, `terminal task ${parent} cannot be a parent target`);
|
|
230
|
+
}
|
|
231
|
+
resolved.push({ ...node, coordinate, existing, parent });
|
|
232
|
+
parents.set(node.depth, coordinate);
|
|
233
|
+
}
|
|
234
|
+
const relationBoard = { ...board, byId: new Map(board.byId) };
|
|
235
|
+
for (const allocation of allocations) {
|
|
236
|
+
const [namespace, id] = allocation.coordinate.includes("/") ? allocation.coordinate.split("/") : [null, allocation.coordinate];
|
|
237
|
+
const node = resolved.find((entry) => entry.coordinate === allocation.coordinate);
|
|
238
|
+
const document = { id, namespace, coordinate: allocation.coordinate, title: allocation.title, state: "open", pri: 2, needs: [], parent: null, from: [], supersedes: [], relatesTo: [], createdAt: now.toISOString(), updatedAt: now.toISOString(), creator: input.creator, body: node.body.join("\n") };
|
|
239
|
+
relationBoard.byId.set(allocation.coordinate, { ...document, namespace, coordinate: allocation.coordinate, blocks: [], blocked: false, releasedNeeds: [], supersededBy: [], relatedTasks: [] });
|
|
240
|
+
}
|
|
241
|
+
const replacements = [];
|
|
242
|
+
const deltas = [];
|
|
243
|
+
for (const node of resolved) {
|
|
244
|
+
const current = node.existing;
|
|
245
|
+
const document = current ? documentFromView(current) : (() => {
|
|
246
|
+
const allocation = allocations.find((entry) => entry.coordinate === node.coordinate);
|
|
247
|
+
const [namespace, id] = node.coordinate.includes("/") ? node.coordinate.split("/") : [null, node.coordinate];
|
|
248
|
+
const timestamp = now.toISOString();
|
|
249
|
+
return { id, namespace, coordinate: node.coordinate, title: allocation.title, state: "open", pri: 2, needs: [], parent: null, from: [], supersedes: [], relatesTo: [], createdAt: timestamp, updatedAt: timestamp, creator: input.creator, body: node.body.join("\n") };
|
|
250
|
+
})();
|
|
251
|
+
if (node.parent !== undefined)
|
|
252
|
+
document.parent = node.parent;
|
|
253
|
+
const relations = resolvedRelations(relationBoard, node);
|
|
254
|
+
if (relations.needs !== undefined) {
|
|
255
|
+
for (const target of relations.needs) {
|
|
256
|
+
const targetTask = relationBoard.byId.get(target);
|
|
257
|
+
if (targetTask?.state === "done" || targetTask?.state === "drop")
|
|
258
|
+
atLine(node.line, `terminal task ${target} cannot be a needs target`);
|
|
259
|
+
}
|
|
260
|
+
if (relations.needs.includes(document.coordinate))
|
|
261
|
+
atLine(node.line, `task ${document.coordinate} needs must not reference itself`);
|
|
262
|
+
document.needs = relations.needs;
|
|
263
|
+
}
|
|
264
|
+
if (relations.supersedes !== undefined) {
|
|
265
|
+
if (relations.supersedes.includes(document.coordinate))
|
|
266
|
+
atLine(node.line, `task ${document.coordinate} supersedes must not reference itself`);
|
|
267
|
+
document.supersedes = relations.supersedes;
|
|
268
|
+
}
|
|
269
|
+
if (relations.relates !== undefined) {
|
|
270
|
+
if (relations.relates.includes(document.coordinate))
|
|
271
|
+
atLine(node.line, `task ${document.coordinate} relations must not reference itself`);
|
|
272
|
+
document.relatesTo = relations.relates;
|
|
273
|
+
}
|
|
274
|
+
if (document.relatesTo.includes(document.coordinate))
|
|
275
|
+
atLine(node.line, `task ${document.coordinate} relations must not reference itself`);
|
|
276
|
+
const before = current;
|
|
277
|
+
const delta = { coordinate: node.coordinate, allocated: !current };
|
|
278
|
+
if (!before || before.parent !== document.parent)
|
|
279
|
+
delta.parent = { before: before?.parent ?? null, after: document.parent };
|
|
280
|
+
if (!before || !same(before.needs, document.needs))
|
|
281
|
+
delta.needs = { before: before?.needs ?? [], after: document.needs };
|
|
282
|
+
if (!before || !same(before.supersedes, document.supersedes))
|
|
283
|
+
delta.supersedes = { before: before?.supersedes ?? [], after: document.supersedes };
|
|
284
|
+
if (!before || !same(before.relatesTo, document.relatesTo))
|
|
285
|
+
delta.relatesTo = { before: before?.relatesTo ?? [], after: document.relatesTo };
|
|
286
|
+
if (Object.keys(delta).length > 2) {
|
|
287
|
+
if (input.namespace !== null && current && current.namespace !== input.namespace) {
|
|
288
|
+
atLine(node.line, `task ${node.coordinate} is outside compose namespace ${input.namespace}`);
|
|
289
|
+
}
|
|
290
|
+
if (current)
|
|
291
|
+
document.updatedAt = advancedTaskUpdatedAt(current, input.now());
|
|
292
|
+
replacements.push(document);
|
|
293
|
+
deltas.push(delta);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
if (replacements.length === 0)
|
|
297
|
+
throw new FlowError("EMPTY_PARAM", "task compose sketch makes no changes");
|
|
298
|
+
const replacementByCoordinate = new Map(replacements.map((document) => [document.coordinate, document]));
|
|
299
|
+
const finalBoard = buildTaskBoardFromDocuments(board.tasks.map((task) => replacementByCoordinate.get(task.coordinate) ?? documentFromView(task)).concat(replacements.filter((document) => !board.byId.has(document.coordinate))));
|
|
300
|
+
const mentioned = new Set(resolved.map((node) => node.coordinate));
|
|
301
|
+
requireHealthyFinalCompositionBoard(finalBoard, new Map(resolved.map((node) => [node.coordinate, node.line])));
|
|
302
|
+
const warnings = [];
|
|
303
|
+
for (const task of board.tasks) {
|
|
304
|
+
if (mentioned.has(task.coordinate))
|
|
305
|
+
continue;
|
|
306
|
+
for (const target of [...task.needs, ...(task.parent ? [task.parent] : []), ...task.supersedes, ...task.relatesTo]) {
|
|
307
|
+
if (mentioned.has(target))
|
|
308
|
+
warnings.push({ kind: "external_inbound", coordinate: target, related: task.coordinate });
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
for (const node of resolved) {
|
|
312
|
+
const task = finalBoard.byId.get(node.coordinate);
|
|
313
|
+
for (const target of task.supersedes) {
|
|
314
|
+
if (finalBoard.byId.get(target)?.state === "open")
|
|
315
|
+
warnings.push({ kind: "open_superseded", coordinate: task.coordinate, related: target });
|
|
316
|
+
}
|
|
317
|
+
if (task.contractId)
|
|
318
|
+
warnings.push({ kind: "bound_task", coordinate: task.coordinate, related: task.contractId });
|
|
319
|
+
}
|
|
320
|
+
return { allocations, replacements, deltas, warnings };
|
|
321
|
+
}
|
|
322
|
+
export async function composeTasks(repository, input) {
|
|
323
|
+
return repository.mutate((board) => {
|
|
324
|
+
const plan = planTaskComposition(board, input);
|
|
325
|
+
return { replacements: plan.replacements, subject: "Compose tasks", requireCommit: true, select: () => plan };
|
|
326
|
+
});
|
|
327
|
+
}
|
package/build/core/task/index.js
CHANGED
|
@@ -10,6 +10,7 @@ export { resolveTaskCreator } from "./task-git-actor.js";
|
|
|
10
10
|
export { openTaskCommandRepository, openTaskMutationContext, readTaskDoctor, taskCommandContractId, taskCommandNamespace, } from "./task-git-runtime.js";
|
|
11
11
|
export { openTaskStore, readTaskHistory, readTaskNamespaces } from "./task-git-store.js";
|
|
12
12
|
export { taskRepositoryFromStore } from "./task-store-repository.js";
|
|
13
|
+
export { composeTasks, planTaskComposition, parseTaskCompositionSketch, } from "./compose.js";
|
|
13
14
|
export { isTaskId } from "./validation.js";
|
|
14
15
|
export { isTaskCoordinate, parseTaskCoordinate, taskCoordinateFromSourcePath } from "./coordinate.js";
|
|
15
16
|
export { buildTaskTree, createTask, doneTask, dropTask, parseTaskDocument, readTaskBoard, resolveTaskReadId, serializeTaskDocument, startTask, stopTask, holdTask, resumeTask, updateTask, updateTaskWithReceipt, deriveTaskDisplay, selectTaskList, taskUpdatedAt, advancedTaskUpdatedAt, } from "./task.js";
|