attraverso 0.3.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -7
- package/assets/memfs2opfs-B4SpaLa4.js +399 -0
- package/assets/migrations/0015_stormy_blindfold.sql +9 -0
- package/assets/migrations/meta/0015_snapshot.json +1668 -0
- package/assets/migrations/meta/_journal.json +7 -0
- package/assets/nodefs-DEelVsw6.js +23 -0
- package/assets/opfs-ahp-CDfgZf23.js +394 -0
- package/assets/postgres-DCJiA8An.js +4649 -0
- package/initdb.wasm +0 -0
- package/lib/index.js +2214 -1301
- package/migrations/0015_stormy_blindfold.sql +9 -0
- package/migrations/meta/0015_snapshot.json +1668 -0
- package/migrations/meta/_journal.json +7 -0
- package/package.json +2 -2
- package/pglite.data +1141 -1165
- package/pglite.wasm +0 -0
- package/server.js +54196 -46987
- package/viewer/assets/favicon-BUxCK25s.svg +13 -0
- package/viewer/assets/index-BuEyBnDM.css +1 -0
- package/viewer/assets/index-CZYfyJ8d.js +45 -0
- package/viewer/index.html +3 -2
- package/assets/nodefs-MM0Ke5-7.js +0 -33
- package/assets/opfs-ahp-D4b2E8uR.js +0 -308
- package/assets/postgres-Dl17RzHj.js +0 -5466
- package/viewer/assets/index--Q2Bqrsm.css +0 -1
- package/viewer/assets/index-Dk0TlY7z.js +0 -90
package/lib/index.js
CHANGED
|
@@ -1,1021 +1,1493 @@
|
|
|
1
1
|
import { PGlite } from "@electric-sql/pglite";
|
|
2
2
|
import { drizzle } from "drizzle-orm/pglite";
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
3
|
+
import { PgDialect, PgTable, check, customType, doublePrecision, foreignKey, index, integer, pgTable, primaryKey, text, uniqueIndex } from "drizzle-orm/pg-core";
|
|
4
|
+
import { and, asc, desc, eq, getTableName, inArray, is, isNull, sql } from "drizzle-orm";
|
|
5
5
|
import { v7 } from "uuid";
|
|
6
6
|
import { z } from "zod";
|
|
7
7
|
import { parse, stringify } from "yaml";
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
8
|
+
// \0rolldown/runtime.js
|
|
9
|
+
var __defProp = Object.defineProperty;
|
|
10
|
+
var __exportAll = (all, no_symbols) => {
|
|
11
|
+
let target = {};
|
|
12
|
+
for (var name in all) __defProp(target, name, {
|
|
13
|
+
get: all[name],
|
|
14
|
+
enumerable: true
|
|
15
|
+
});
|
|
16
|
+
if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
|
|
17
|
+
return target;
|
|
18
|
+
};
|
|
19
|
+
// src/db/ids.ts
|
|
20
|
+
/**
|
|
21
|
+
* Identity and time, both generated in the application rather than the database. Application-side generation
|
|
22
|
+
* lets an id exist before its row is written (so an event can reference an entity created in the same
|
|
23
|
+
* transaction), needs no coordinating sequence when the database goes multi-user, makes tests deterministic
|
|
24
|
+
* by injecting the clock, and - for the YAML-as-source-of-truth model - lets ids and timestamps round-trip
|
|
25
|
+
* through the file verbatim rather than being re-minted or re-formatted by the database.
|
|
26
|
+
*/
|
|
27
|
+
/**
|
|
28
|
+
* A UUIDv7: a 48-bit millisecond timestamp followed by randomness, so ids sort by creation time as plain
|
|
29
|
+
* text. That ordering is the reason for v7 over v4: time-ordered keys keep index inserts local, "most recent
|
|
30
|
+
* first" needs no extra column, and it survives the move to a shared cloud database where a coordinating
|
|
31
|
+
* sequence would not. Node's `crypto.randomUUID` only produces v4 (it silently ignores a `{version:7}`
|
|
32
|
+
* option), so this delegates to the `uuid` library rather than hand-rolling the RFC 9562 bit layout.
|
|
33
|
+
*
|
|
34
|
+
* **Call `v7()` with no options unless a specific instant is wanted.** Passing `msecs` opts out of the
|
|
35
|
+
* library's monotonic counter, the thing that keeps two ids minted inside the same millisecond in order.
|
|
36
|
+
* This used to pass `msecs: Date.now()` on every call, which looked equivalent and was not: measured over
|
|
37
|
+
* 500 same-millisecond pairs, ids came out in the wrong order 254 times with an explicit `msecs` and 0 times
|
|
38
|
+
* without. That silently cost the ordering guarantee this whole file exists for - "most recent first needs no
|
|
39
|
+
* extra column" is only true if the id breaks ties correctly - and it surfaced as a rare flake in a notes
|
|
40
|
+
* ordering test, where two notes written in one millisecond tie on `created_at` and fall back to the id.
|
|
41
|
+
*
|
|
42
|
+
* `atMillis` remains injectable so a test can place ids at chosen instants; ordering within one injected
|
|
43
|
+
* millisecond is then the caller's problem, which is fine because such a caller is choosing the instants.
|
|
44
|
+
*/
|
|
45
|
+
var uuidv7 = (atMillis) => atMillis === void 0 ? v7() : v7({ msecs: atMillis });
|
|
46
|
+
/**
|
|
47
|
+
* An instant as fixed-width ISO-8601 UTC text (`2026-07-23T14:47:00.000Z`). Fixed width is the point: the
|
|
48
|
+
* timestamp columns are `text` (see `schema.ts`), compared as strings, so a variable-width format would sort
|
|
49
|
+
* wrongly; and storing the exact string we generated is what lets the YAML export round-trip it verbatim.
|
|
50
|
+
*/
|
|
51
|
+
var timestamp = (at = /* @__PURE__ */ new Date()) => at.toISOString();
|
|
52
|
+
/** Width of one numeric segment in a `sort_path`. Six digits is far past any plausible item count. */
|
|
53
|
+
var SEGMENT_WIDTH = 6;
|
|
54
|
+
/**
|
|
55
|
+
* The sortable form of a human ref's numeric components: `MCP-3.1.2` becomes `000003.000001.000002`.
|
|
56
|
+
* Zero-padding is what makes lexicographic ordering agree with numeric ordering, so "item 10 after item 2"
|
|
57
|
+
* is a plain `ORDER BY` and "the next child id" is a plain `MAX`, in either dialect and with no
|
|
58
|
+
* string parsing in SQL.
|
|
59
|
+
*/
|
|
11
60
|
function sortPath(ref) {
|
|
12
|
-
|
|
13
|
-
return numeric.split(".").map((segment) => segment.padStart(SEGMENT_WIDTH, "0")).join(".");
|
|
61
|
+
return ref.slice(ref.indexOf("-") + 1).split(".").map((segment) => segment.padStart(SEGMENT_WIDTH, "0")).join(".");
|
|
14
62
|
}
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
63
|
+
// src/db/schema.ts
|
|
64
|
+
/**
|
|
65
|
+
* The database schema, defined once in Drizzle's `pg-core`. This single definition drives both the DDL
|
|
66
|
+
* (drizzle-kit generates the migrations from it) and the row types the domain layer reads, and it runs
|
|
67
|
+
* unchanged on in-memory PGlite locally and server Postgres in the cloud - the two are the same engine.
|
|
68
|
+
*
|
|
69
|
+
* This is the model from the project's design, not a fresh one: `items` carries tickets, skills and care
|
|
70
|
+
* items in one table with no type or lifecycle column (everything closes, so the only thing that varies is
|
|
71
|
+
* whether an item has a schedule, which is a future nullable attachment). `projects.type`, `items.status`
|
|
72
|
+
* and `events.entity_type` are deliberately open sets with no CHECK/enum: a new kind is a row, never a
|
|
73
|
+
* migration. The domain layer validates the status vocabulary and legal transitions.
|
|
74
|
+
*
|
|
75
|
+
* Timestamps are `text`, not `timestamptz`, on purpose: they are generated in the application as
|
|
76
|
+
* fixed-width ISO-8601 UTC (see `ids.ts`), which orders correctly as text and - crucially for the
|
|
77
|
+
* YAML-as-source-of-truth model - round-trips verbatim, where a `timestamptz` would re-format on the way
|
|
78
|
+
* out and turn every export into a whole-file diff.
|
|
79
|
+
*/
|
|
80
|
+
var schema_exports = /* @__PURE__ */ __exportAll({
|
|
81
|
+
TEXT_SEARCH_CONFIG: () => TEXT_SEARCH_CONFIG,
|
|
82
|
+
allowedEmails: () => allowedEmails,
|
|
83
|
+
areas: () => areas,
|
|
84
|
+
attachments: () => attachments,
|
|
85
|
+
comments: () => comments,
|
|
86
|
+
contextSections: () => contextSections,
|
|
87
|
+
dependencies: () => dependencies,
|
|
88
|
+
events: () => events,
|
|
89
|
+
items: () => items,
|
|
90
|
+
layoutPositions: () => layoutPositions,
|
|
91
|
+
measurements: () => measurements,
|
|
92
|
+
projectNext: () => projectNext,
|
|
93
|
+
projects: () => projects,
|
|
94
|
+
scopedDependencies: () => scopedDependencies,
|
|
95
|
+
users: () => users
|
|
18
96
|
});
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
97
|
+
/**
|
|
98
|
+
* The text-search configuration every index and every query uses (`DATA-11`).
|
|
99
|
+
*
|
|
100
|
+
* **Hardcoded, and known debt.** It is right for this project and wrong for a Spanish one: the configuration
|
|
101
|
+
* decides stemming and stop words, so `'english'` applied to Spanish text stems nothing and strips the wrong
|
|
102
|
+
* words. The eventual shape is a `text_search_config` on `projects` defaulting to this, which is deliberately
|
|
103
|
+
* not built yet - a generated column cannot depend on another table's value, so per-project configuration
|
|
104
|
+
* means either a trigger-maintained column or one index per configuration, and that is a decision to make
|
|
105
|
+
* against a real second-language project rather than in advance of one.
|
|
106
|
+
*
|
|
107
|
+
* It lives here as one constant so that switch is a single edit rather than a hunt across four generated
|
|
108
|
+
* columns and every query. Changing it *is* a schema change: the stored vectors are part of the column
|
|
109
|
+
* definition and have to be rebuilt. Free locally, where PGlite is rebuilt from the YAML on every load.
|
|
110
|
+
*/
|
|
111
|
+
var TEXT_SEARCH_CONFIG = "english";
|
|
112
|
+
/**
|
|
113
|
+
* Postgres `tsvector`. Drizzle has no built-in for it, and this is only ever read back as an opaque string -
|
|
114
|
+
* the ranking and the snippets are computed in SQL, so nothing in the domain layer parses one.
|
|
115
|
+
*/
|
|
116
|
+
var tsvector = customType({ dataType: () => "tsvector" });
|
|
117
|
+
/**
|
|
118
|
+
* The indexed form of a row: its text columns, stemmed and weighted.
|
|
119
|
+
*
|
|
120
|
+
* `A` outranks `B`, which is what makes a title match beat a body match for the same term. `coalesce` because
|
|
121
|
+
* a null column would otherwise null the whole concatenation and silently drop the row out of the index.
|
|
122
|
+
*
|
|
123
|
+
* Built as raw DDL because it is only ever a column definition. **Postgres maintains it inside the same write
|
|
124
|
+
* as the row**, so it cannot drift and there is no trigger and no domain-layer bookkeeping to keep in step -
|
|
125
|
+
* which is the entire reason for preferring this over a separate index table (`DATA-11`).
|
|
126
|
+
*/
|
|
127
|
+
var searchVector = (...parts) => sql.raw(parts.map(([column, weight]) => `setweight(to_tsvector('${TEXT_SEARCH_CONFIG}', coalesce("${column}", '')), '${weight}')`).join(" || "));
|
|
128
|
+
/**
|
|
129
|
+
* Who owns a project (`OPS-4`), keyed by an id we generate and never by the identity provider's subject.
|
|
130
|
+
*
|
|
131
|
+
* `subject` is scoped to its issuer, so owning on it directly would orphan every project the day the auth
|
|
132
|
+
* provider changed - and a provider's `sub` is usually its own user uuid, so merely recreating the auth
|
|
133
|
+
* project would do it. Keying on `email` instead trades that for a worse problem: an email claim is only as
|
|
134
|
+
* trustworthy as the provider asserting it, and re-enabling password sign-in is a dashboard toggle, after
|
|
135
|
+
* which someone could register an address they do not own and inherit its projects. So both are attributes
|
|
136
|
+
* of a row identified by neither, and `ensureUser` resolves by `(issuer, subject)` first, falling back to a
|
|
137
|
+
* **verified** email and re-binding the new subject onto the existing row. That fallback is what makes a
|
|
138
|
+
* provider switch self-healing rather than a hand-written remap; the `email_verified` gate on it is
|
|
139
|
+
* load-bearing, because without it the fallback is the same hazard wearing a hat.
|
|
140
|
+
*
|
|
141
|
+
* `issuer` is stored rather than assumed: a subject is only unique within the issuer that minted it, and
|
|
142
|
+
* "which provider was this from" is precisely the question a provider switch asks.
|
|
143
|
+
*
|
|
144
|
+
* **Deliberately not serialised to YAML.** Identity belongs to a deployment, not to a plan: a committed
|
|
145
|
+
* `roadmap.apm.yaml` that recorded its owner would have a clone import the committer's account. File mode
|
|
146
|
+
* synthesises one local user instead (`issuer: "local"`), so the domain layer never has to ask whether a
|
|
147
|
+
* caller exists.
|
|
148
|
+
*/
|
|
149
|
+
var users = pgTable("users", {
|
|
150
|
+
id: text("id").primaryKey().$defaultFn(uuidv7),
|
|
151
|
+
issuer: text("issuer").notNull(),
|
|
152
|
+
subject: text("subject").notNull(),
|
|
153
|
+
email: text("email"),
|
|
154
|
+
createdAt: text("created_at").notNull().$defaultFn(timestamp)
|
|
155
|
+
}, (t) => [uniqueIndex("users_issuer_subject").on(t.issuer, t.subject), uniqueIndex("users_email").on(t.email)]);
|
|
156
|
+
/**
|
|
157
|
+
* Who may use this deployment at all (`OPS-4`), as distinct from `users`, which is who *has*.
|
|
158
|
+
*
|
|
159
|
+
* A table rather than `APM_ALLOWED_EMAILS`, because an access list that only changes by editing a secret
|
|
160
|
+
* changes rarely and at the wrong moments: every edit is a machine restart, it cannot be done from a phone,
|
|
161
|
+
* and it is invisible to every test. This can be read per request, edited from a console or eventually a tool
|
|
162
|
+
* call, and covered by the migration and event machinery like anything else.
|
|
163
|
+
*
|
|
164
|
+
* **An empty table means nobody**, deliberately - the opposite of the env var it replaces, where unset meant
|
|
165
|
+
* *everyone*. The difference between a list that is off and a list that is empty is exactly the failure this
|
|
166
|
+
* project lived through on 2026-08-31, when an uninvited account reached a server whose only gate was unset.
|
|
167
|
+
*
|
|
168
|
+
* Keyed on the address itself: it is the thing a person is invited by, it is what arrives in a token, and a
|
|
169
|
+
* primary key means a `INSERT` from a console cannot quietly create a duplicate that only one query finds.
|
|
170
|
+
* Stored lower-cased, matching how `verifiedEmail` normalises before comparing.
|
|
171
|
+
*/
|
|
172
|
+
var allowedEmails = pgTable("allowed_emails", {
|
|
173
|
+
email: text("email").primaryKey(),
|
|
174
|
+
note: text("note"),
|
|
175
|
+
/**
|
|
176
|
+
* The one column in this schema with a **database** default as well as an application one, and the exception
|
|
177
|
+
* is narrow enough to state exactly.
|
|
178
|
+
*
|
|
179
|
+
* Timestamps are generated in the application everywhere else so they round-trip verbatim into the plan YAML
|
|
180
|
+
* - a `timestamptz` would re-format on the way out and turn every export into a whole-file diff. This table
|
|
181
|
+
* is not serialised at all (it is who may reach a *deployment*, not part of a plan), so that reason does not
|
|
182
|
+
* reach it, and its absence has a cost the others do not have: inviting someone is meant to be one `INSERT`
|
|
183
|
+
* typed into a console from a phone, and a `NOT NULL` column with no default makes that three fields.
|
|
184
|
+
*
|
|
185
|
+
* The expression reproduces `Date.toISOString()` exactly - `YYYY-MM-DDTHH:MM:SS.mmmZ`, three-digit
|
|
186
|
+
* milliseconds, UTC - so a row written by hand is indistinguishable from one written by `allowEmail`.
|
|
187
|
+
*/
|
|
188
|
+
createdAt: text("created_at").notNull().$defaultFn(timestamp).default(sql`to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')`)
|
|
60
189
|
});
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
)
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
)
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
)
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
)
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
)
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
);
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
);
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
tag: "0010_acoustic_pixie",
|
|
453
|
-
breakpoints: true
|
|
454
|
-
},
|
|
455
|
-
{
|
|
456
|
-
idx: 11,
|
|
457
|
-
version: "7",
|
|
458
|
-
when: 1788377979673,
|
|
459
|
-
tag: "0011_orange_rawhide_kid",
|
|
460
|
-
breakpoints: true
|
|
461
|
-
},
|
|
462
|
-
{
|
|
463
|
-
idx: 12,
|
|
464
|
-
version: "7",
|
|
465
|
-
when: 1788381139129,
|
|
466
|
-
tag: "0012_smiling_butterfly",
|
|
467
|
-
breakpoints: true
|
|
468
|
-
},
|
|
469
|
-
{
|
|
470
|
-
idx: 13,
|
|
471
|
-
version: "7",
|
|
472
|
-
when: 1790032589899,
|
|
473
|
-
tag: "0013_kind_bloodscream",
|
|
474
|
-
breakpoints: true
|
|
475
|
-
},
|
|
476
|
-
{
|
|
477
|
-
idx: 14,
|
|
478
|
-
version: "7",
|
|
479
|
-
when: 1793292077069,
|
|
480
|
-
tag: "0014_past_chronomancer",
|
|
481
|
-
breakpoints: true
|
|
482
|
-
}
|
|
483
|
-
];
|
|
484
|
-
const journal = {
|
|
485
|
-
entries
|
|
190
|
+
var projects = pgTable("projects", {
|
|
191
|
+
id: text("id").primaryKey().$defaultFn(uuidv7),
|
|
192
|
+
key: text("key").notNull(),
|
|
193
|
+
ownerId: text("owner_id").notNull().references(() => users.id),
|
|
194
|
+
name: text("name").notNull(),
|
|
195
|
+
type: text("type").notNull(),
|
|
196
|
+
direction: text("direction"),
|
|
197
|
+
status: text("status").notNull(),
|
|
198
|
+
createdAt: text("created_at").notNull().$defaultFn(timestamp),
|
|
199
|
+
updatedAt: text("updated_at").notNull().$defaultFn(timestamp),
|
|
200
|
+
archivedAt: text("archived_at")
|
|
201
|
+
}, (t) => [uniqueIndex("projects_owner_key").on(t.ownerId, t.key)]);
|
|
202
|
+
var areas = pgTable("areas", {
|
|
203
|
+
id: text("id").primaryKey().$defaultFn(uuidv7),
|
|
204
|
+
projectId: text("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
|
|
205
|
+
key: text("key").notNull(),
|
|
206
|
+
name: text("name").notNull(),
|
|
207
|
+
description: text("description"),
|
|
208
|
+
colour: text("colour"),
|
|
209
|
+
sortOrder: integer("sort_order").notNull().default(0),
|
|
210
|
+
createdAt: text("created_at").notNull().$defaultFn(timestamp)
|
|
211
|
+
}, (t) => [uniqueIndex("areas_project_key").on(t.projectId, t.key)]);
|
|
212
|
+
var items = pgTable("items", {
|
|
213
|
+
id: text("id").primaryKey().$defaultFn(uuidv7),
|
|
214
|
+
projectId: text("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
|
|
215
|
+
ref: text("ref").notNull(),
|
|
216
|
+
areaKey: text("area_key").notNull(),
|
|
217
|
+
sortPath: text("sort_path").notNull(),
|
|
218
|
+
parentId: text("parent_id"),
|
|
219
|
+
title: text("title").notNull(),
|
|
220
|
+
body: text("body"),
|
|
221
|
+
status: text("status").notNull(),
|
|
222
|
+
createdAt: text("created_at").notNull().$defaultFn(timestamp),
|
|
223
|
+
updatedAt: text("updated_at").notNull().$defaultFn(timestamp),
|
|
224
|
+
closedAt: text("closed_at"),
|
|
225
|
+
deletedAt: text("deleted_at"),
|
|
226
|
+
startOn: text("start_on"),
|
|
227
|
+
dueOn: text("due_on"),
|
|
228
|
+
tsv: tsvector("tsv").generatedAlwaysAs(() => searchVector(["title", "A"], ["body", "B"]))
|
|
229
|
+
}, (t) => [
|
|
230
|
+
uniqueIndex("items_project_ref").on(t.projectId, t.ref),
|
|
231
|
+
foreignKey({
|
|
232
|
+
columns: [t.parentId],
|
|
233
|
+
foreignColumns: [t.id]
|
|
234
|
+
}).onDelete("cascade"),
|
|
235
|
+
index("items_project_status").on(t.projectId, t.status),
|
|
236
|
+
index("items_project_area").on(t.projectId, t.areaKey),
|
|
237
|
+
index("items_project_sort").on(t.projectId, t.sortPath),
|
|
238
|
+
index("items_parent").on(t.parentId),
|
|
239
|
+
index("items_project_due").on(t.projectId, t.dueOn),
|
|
240
|
+
index("items_tsv").using("gin", t.tsv)
|
|
241
|
+
]);
|
|
242
|
+
var dependencies = pgTable("dependencies", {
|
|
243
|
+
itemId: text("item_id").notNull().references(() => items.id, { onDelete: "cascade" }),
|
|
244
|
+
dependsOnId: text("depends_on_id").notNull().references(() => items.id, { onDelete: "cascade" }),
|
|
245
|
+
createdAt: text("created_at").notNull().$defaultFn(timestamp)
|
|
246
|
+
}, (t) => [primaryKey({ columns: [t.itemId, t.dependsOnId] }), index("dependencies_depends_on").on(t.dependsOnId)]);
|
|
247
|
+
/**
|
|
248
|
+
* A dependency that names another project: `apm-cloud:OPS-1` depends on `apm:DIST-1` (`PROJ-11`).
|
|
249
|
+
*
|
|
250
|
+
* **A separate table because the target is text, not a row.** Once a plan spans several store files
|
|
251
|
+
* (`IMP-17`) an edge can point into a project that is not loaded - a clone of the public repo has one store
|
|
252
|
+
* by construction - and there is no id to reference. Widening `dependencies` with a nullable
|
|
253
|
+
* `depends_on_id` would make every existing query on it filter for the real rows; a second table leaves all
|
|
254
|
+
* of them correct untouched.
|
|
255
|
+
*
|
|
256
|
+
* **Every scoped dependency lives here, including the ones that currently resolve.** The tempting
|
|
257
|
+
* optimisation is to store a resolvable one as an ordinary `dependencies` row, but then the same YAML builds
|
|
258
|
+
* a different database depending on which *other* file happened to be loaded, and the export stops round
|
|
259
|
+
* -tripping. Resolution is a read-time join, never a storage decision.
|
|
260
|
+
*
|
|
261
|
+
* A scope naming the item's own project is normalised away on write, so there is exactly one representation
|
|
262
|
+
* of a within-project edge and `dependencies` stays the whole of the graph that cycles and blocking run over.
|
|
263
|
+
*/
|
|
264
|
+
var scopedDependencies = pgTable("scoped_dependencies", {
|
|
265
|
+
itemId: text("item_id").notNull().references(() => items.id, { onDelete: "cascade" }),
|
|
266
|
+
/** The other project's key, as written. Not a foreign key: the point of the row is that the project it
|
|
267
|
+
* names may not be loaded, and a constraint would make the unresolved case unstorable. */
|
|
268
|
+
targetProject: text("target_project").notNull(),
|
|
269
|
+
targetRef: text("target_ref").notNull(),
|
|
270
|
+
createdAt: text("created_at").notNull().$defaultFn(timestamp)
|
|
271
|
+
}, (t) => [primaryKey({ columns: [
|
|
272
|
+
t.itemId,
|
|
273
|
+
t.targetProject,
|
|
274
|
+
t.targetRef
|
|
275
|
+
] })]);
|
|
276
|
+
/**
|
|
277
|
+
* A numeric or categorical reading, taken at a time (`METRIC-1`).
|
|
278
|
+
*
|
|
279
|
+
* The primitive the memory layer lacked: `observations` hold durable revisable *facts*, and forcing a weight
|
|
280
|
+
* or a rep count into prose loses the ability to trend it. `CTX-15` found a live health-tracking project
|
|
281
|
+
* hand-rolling exactly this as ~750-character daily comments, which is what brought the work forward.
|
|
282
|
+
*
|
|
283
|
+
* **These rows do not live in the plan file.** Every other table here is low-volatility, and the whole of
|
|
284
|
+
* `roadmap.apm.yaml` is rewritten on each change - affordable at tens of kilobytes. Measurements break both
|
|
285
|
+
* properties: append-heavy by nature (a daily weigh-in, a meal, every set of every lift) and larger in a year
|
|
286
|
+
* than the plan they hang off. They follow `IMP-7`'s split-by-volatility rule to
|
|
287
|
+
* `.apm/measurements/YYYY-MM.yaml`, appended rather than rewritten (`METRIC-2` implements that; `IMP-8`'s
|
|
288
|
+
* coverage manifest already records where they go).
|
|
289
|
+
*
|
|
290
|
+
* **Placement resolves at the root.** A root row carries its subject - `item_id` for a reading about an item
|
|
291
|
+
* ("this lift's working weight"), null for one about the project ("body weight", "daily calories"), following
|
|
292
|
+
* the nullable-FK precedent `attachments` set. A child carries `parent_id` and *inherits* placement, with
|
|
293
|
+
* `item_id` denormalised onto it. That is stored derived state, which this model normally refuses, and it is
|
|
294
|
+
* the same exception `due_at` is: aggregation is the hot path, and it is safe only because the call that
|
|
295
|
+
* writes a tree writes it, and nothing hand-edits it.
|
|
296
|
+
*
|
|
297
|
+
* **Measurements nest, exactly as items do.** A workout is one occurrence holding `bench_press_weight` and
|
|
298
|
+
* `bench_press_reps`; a meal holds `kcal` and `protein_g`. One nesting idea in the product rather than two.
|
|
299
|
+
* Depth is uncapped, matching items, because any cap would be arbitrary - and it is safe to allow because
|
|
300
|
+
* **aggregation never traverses the tree**: "all calories on 14 Aug" is `metric` and `at`, whichever shape the
|
|
301
|
+
* rows were written in. A badly shaped tree costs display quality, never correctness.
|
|
302
|
+
*
|
|
303
|
+
* A parent node with no reading is an **occurrence** - it happened, at a time - which is what this table is
|
|
304
|
+
* for. A *definition* ("sleep_duration is measured in hours") is undated, revisable and one per name, so it
|
|
305
|
+
* belongs in the plan file beside `areas` if it is ever needed, never among the readings.
|
|
306
|
+
*/
|
|
307
|
+
var measurements = pgTable("measurements", {
|
|
308
|
+
id: text("id").primaryKey().$defaultFn(uuidv7),
|
|
309
|
+
projectId: text("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
|
|
310
|
+
itemId: text("item_id").references(() => items.id, { onDelete: "cascade" }),
|
|
311
|
+
parentId: text("parent_id"),
|
|
312
|
+
metric: text("metric").notNull(),
|
|
313
|
+
/**
|
|
314
|
+
* The reading, when it is a number.
|
|
315
|
+
*
|
|
316
|
+
* `double precision` rather than `numeric`: it maps to a JS number, where Postgres `numeric` comes back
|
|
317
|
+
* as a string that every consumer has to parse, buying an exactness nobody logging a body weight needs.
|
|
318
|
+
* Integers stay exact to 2^53, which covers every count this will hold.
|
|
319
|
+
*/
|
|
320
|
+
value: doublePrecision("value"),
|
|
321
|
+
/**
|
|
322
|
+
* The reading, when it is categorical ("restless"). A separate column rather than widening `value` to
|
|
323
|
+
* text, because a text column cannot be SUMmed, AVGed or ordered without a cast on every query - and the
|
|
324
|
+
* moment one row holds "restless" the whole series stops trending.
|
|
325
|
+
*/
|
|
326
|
+
textValue: text("text_value"),
|
|
327
|
+
unit: text("unit"),
|
|
328
|
+
/**
|
|
329
|
+
* Display metadata, and it must stay that way: the human-readable name of what a reading is of
|
|
330
|
+
* ("overnight oats"). **Never aggregated** - the test is that wanting `GROUP BY label` means it should
|
|
331
|
+
* have been a node. `CTX-2` measured what happens when the cheap path beats the correct one (`add_note`
|
|
332
|
+
* ignored 64 times out of 64), so writing a tree has to be as cheap as labelling at the tool boundary.
|
|
333
|
+
*/
|
|
334
|
+
label: text("label"),
|
|
335
|
+
at: text("at").notNull(),
|
|
336
|
+
source: text("source"),
|
|
337
|
+
actor: text("actor").notNull(),
|
|
338
|
+
createdAt: text("created_at").notNull().$defaultFn(timestamp)
|
|
339
|
+
}, (t) => [
|
|
340
|
+
foreignKey({
|
|
341
|
+
columns: [t.parentId],
|
|
342
|
+
foreignColumns: [t.id]
|
|
343
|
+
}).onDelete("cascade"),
|
|
344
|
+
index("measurements_project_metric_at").on(t.projectId, t.metric, t.at),
|
|
345
|
+
index("measurements_item").on(t.itemId),
|
|
346
|
+
index("measurements_parent").on(t.parentId),
|
|
347
|
+
check("measurements_one_reading", sql`NOT (${t.value} IS NOT NULL AND ${t.textValue} IS NOT NULL)`)
|
|
348
|
+
]);
|
|
349
|
+
/**
|
|
350
|
+
* The order we agreed to work in (`PROJ-8`): a short ordered list of items, held on the project beside
|
|
351
|
+
* `direction`.
|
|
352
|
+
*
|
|
353
|
+
* **A join table rather than a `text[]` on `projects`**, because Postgres cannot put a foreign key on array
|
|
354
|
+
* elements, and an unenforced reference would be the only one in this schema - `dependencies` is a real join
|
|
355
|
+
* table, `parent_id` is an FK, and `apm:check` validates every dep and parent ref on top. The YAML is
|
|
356
|
+
* unaffected: it exports as `next: [PROJ-8, METRIC-1]`, exactly as `dependencies` exports as `deps:`.
|
|
357
|
+
*
|
|
358
|
+
* `position` is rewritten wholesale on every write. Ten rows and one call, so there is no fractional-index
|
|
359
|
+
* scheme to maintain, and the unique index is what stops two items claiming the same slot.
|
|
360
|
+
*
|
|
361
|
+
* The cascade is real but will rarely fire: items are soft-deleted (`deleted_at`, no hard-delete path), so a
|
|
362
|
+
* deleted item stays in this table and is **filtered on read** instead. That is deliberate - dropping it on
|
|
363
|
+
* write would be mutating stored state from derived state, and it keeps the row recoverable if the item is
|
|
364
|
+
* undeleted.
|
|
365
|
+
*/
|
|
366
|
+
var projectNext = pgTable("project_next", {
|
|
367
|
+
projectId: text("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
|
|
368
|
+
itemId: text("item_id").notNull().references(() => items.id, { onDelete: "cascade" }),
|
|
369
|
+
position: integer("position").notNull()
|
|
370
|
+
}, (t) => [primaryKey({ columns: [t.projectId, t.itemId] }), uniqueIndex("project_next_position").on(t.projectId, t.position)]);
|
|
371
|
+
var layoutPositions = pgTable("layout_positions", {
|
|
372
|
+
projectId: text("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
|
|
373
|
+
node: text("node").notNull(),
|
|
374
|
+
x: integer("x").notNull(),
|
|
375
|
+
y: integer("y").notNull()
|
|
376
|
+
}, (t) => [primaryKey({ columns: [t.projectId, t.node] })]);
|
|
377
|
+
var events = pgTable("events", {
|
|
378
|
+
id: text("id").primaryKey().$defaultFn(uuidv7),
|
|
379
|
+
projectId: text("project_id").references(() => projects.id, { onDelete: "cascade" }),
|
|
380
|
+
entityType: text("entity_type").notNull(),
|
|
381
|
+
entityId: text("entity_id").notNull(),
|
|
382
|
+
at: text("at").notNull().$defaultFn(timestamp),
|
|
383
|
+
actor: text("actor").notNull(),
|
|
384
|
+
kind: text("kind").notNull(),
|
|
385
|
+
correlationId: text("correlation_id"),
|
|
386
|
+
before: text("before"),
|
|
387
|
+
after: text("after")
|
|
388
|
+
}, (t) => [index("events_entity").on(t.entityType, t.entityId), index("events_project_at").on(t.projectId, t.at)]);
|
|
389
|
+
var contextSections = pgTable("context_sections", {
|
|
390
|
+
id: text("id").primaryKey().$defaultFn(uuidv7),
|
|
391
|
+
projectId: text("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
|
|
392
|
+
heading: text("heading").notNull(),
|
|
393
|
+
content: text("content").notNull(),
|
|
394
|
+
sortOrder: integer("sort_order").notNull().default(0),
|
|
395
|
+
createdAt: text("created_at").notNull().$defaultFn(timestamp),
|
|
396
|
+
updatedAt: text("updated_at").notNull().$defaultFn(timestamp),
|
|
397
|
+
tsv: tsvector("tsv").generatedAlwaysAs(() => searchVector(["heading", "A"], ["content", "B"]))
|
|
398
|
+
}, (t) => [
|
|
399
|
+
uniqueIndex("context_sections_project_heading").on(t.projectId, t.heading),
|
|
400
|
+
index("context_sections_project_order").on(t.projectId, t.sortOrder),
|
|
401
|
+
index("context_sections_tsv").using("gin", t.tsv)
|
|
402
|
+
]);
|
|
403
|
+
var comments = pgTable("comments", {
|
|
404
|
+
id: text("id").primaryKey().$defaultFn(uuidv7),
|
|
405
|
+
projectId: text("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
|
|
406
|
+
itemId: text("item_id").references(() => items.id, { onDelete: "cascade" }),
|
|
407
|
+
body: text("body").notNull(),
|
|
408
|
+
audience: text("audience").notNull().default("user"),
|
|
409
|
+
actor: text("actor").notNull(),
|
|
410
|
+
createdAt: text("created_at").notNull().$defaultFn(timestamp),
|
|
411
|
+
tsv: tsvector("tsv").generatedAlwaysAs(() => searchVector(["body", "A"]))
|
|
412
|
+
}, (t) => [
|
|
413
|
+
index("comments_project_created").on(t.projectId, t.createdAt),
|
|
414
|
+
index("comments_item").on(t.itemId),
|
|
415
|
+
index("comments_tsv").using("gin", t.tsv)
|
|
416
|
+
]);
|
|
417
|
+
var attachments = pgTable("attachments", {
|
|
418
|
+
id: text("id").primaryKey().$defaultFn(uuidv7),
|
|
419
|
+
projectId: text("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
|
|
420
|
+
itemId: text("item_id").references(() => items.id, { onDelete: "cascade" }),
|
|
421
|
+
hash: text("hash").notNull(),
|
|
422
|
+
mime: text("mime").notNull(),
|
|
423
|
+
bytes: integer("bytes").notNull(),
|
|
424
|
+
caption: text("caption"),
|
|
425
|
+
actor: text("actor").notNull(),
|
|
426
|
+
createdAt: text("created_at").notNull().$defaultFn(timestamp)
|
|
427
|
+
}, (t) => [
|
|
428
|
+
index("attachments_project_item").on(t.projectId, t.itemId),
|
|
429
|
+
index("attachments_hash").on(t.hash),
|
|
430
|
+
uniqueIndex("attachments_item_hash").on(t.projectId, t.itemId, t.hash)
|
|
431
|
+
]);
|
|
432
|
+
// src/db/migrations/0000_burly_firestar.sql?raw
|
|
433
|
+
var _0000_burly_firestar_default = "CREATE TABLE \"areas\" (\n \"id\" text PRIMARY KEY NOT NULL,\n \"project_id\" text NOT NULL,\n \"key\" text NOT NULL,\n \"name\" text NOT NULL,\n \"description\" text,\n \"colour\" text,\n \"sort_order\" integer DEFAULT 0 NOT NULL,\n \"created_at\" text NOT NULL\n);\n--> statement-breakpoint\nCREATE TABLE \"dependencies\" (\n \"item_id\" text NOT NULL,\n \"depends_on_id\" text NOT NULL,\n \"created_at\" text NOT NULL,\n CONSTRAINT \"dependencies_item_id_depends_on_id_pk\" PRIMARY KEY(\"item_id\",\"depends_on_id\")\n);\n--> statement-breakpoint\nCREATE TABLE \"events\" (\n \"id\" text PRIMARY KEY NOT NULL,\n \"project_id\" text,\n \"entity_type\" text NOT NULL,\n \"entity_id\" text NOT NULL,\n \"at\" text NOT NULL,\n \"actor\" text NOT NULL,\n \"kind\" text NOT NULL,\n \"correlation_id\" text,\n \"before\" text,\n \"after\" text\n);\n--> statement-breakpoint\nCREATE TABLE \"items\" (\n \"id\" text PRIMARY KEY NOT NULL,\n \"project_id\" text NOT NULL,\n \"ref\" text NOT NULL,\n \"area_key\" text NOT NULL,\n \"sort_path\" text NOT NULL,\n \"parent_id\" text,\n \"title\" text NOT NULL,\n \"body\" text,\n \"status\" text NOT NULL,\n \"priority\" integer DEFAULT 0 NOT NULL,\n \"created_at\" text NOT NULL,\n \"updated_at\" text NOT NULL,\n \"closed_at\" text,\n \"deleted_at\" text\n);\n--> statement-breakpoint\nCREATE TABLE \"projects\" (\n \"id\" text PRIMARY KEY NOT NULL,\n \"key\" text NOT NULL,\n \"name\" text NOT NULL,\n \"type\" text NOT NULL,\n \"direction\" text,\n \"status\" text NOT NULL,\n \"created_at\" text NOT NULL,\n \"updated_at\" text NOT NULL,\n \"archived_at\" text,\n CONSTRAINT \"projects_key_unique\" UNIQUE(\"key\")\n);\n--> statement-breakpoint\nALTER TABLE \"areas\" ADD CONSTRAINT \"areas_project_id_projects_id_fk\" FOREIGN KEY (\"project_id\") REFERENCES \"public\".\"projects\"(\"id\") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint\nALTER TABLE \"dependencies\" ADD CONSTRAINT \"dependencies_item_id_items_id_fk\" FOREIGN KEY (\"item_id\") REFERENCES \"public\".\"items\"(\"id\") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint\nALTER TABLE \"dependencies\" ADD CONSTRAINT \"dependencies_depends_on_id_items_id_fk\" FOREIGN KEY (\"depends_on_id\") REFERENCES \"public\".\"items\"(\"id\") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint\nALTER TABLE \"events\" ADD CONSTRAINT \"events_project_id_projects_id_fk\" FOREIGN KEY (\"project_id\") REFERENCES \"public\".\"projects\"(\"id\") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint\nALTER TABLE \"items\" ADD CONSTRAINT \"items_project_id_projects_id_fk\" FOREIGN KEY (\"project_id\") REFERENCES \"public\".\"projects\"(\"id\") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint\nALTER TABLE \"items\" ADD CONSTRAINT \"items_parent_id_items_id_fk\" FOREIGN KEY (\"parent_id\") REFERENCES \"public\".\"items\"(\"id\") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint\nCREATE UNIQUE INDEX \"areas_project_key\" ON \"areas\" USING btree (\"project_id\",\"key\");--> statement-breakpoint\nCREATE INDEX \"dependencies_depends_on\" ON \"dependencies\" USING btree (\"depends_on_id\");--> statement-breakpoint\nCREATE INDEX \"events_entity\" ON \"events\" USING btree (\"entity_type\",\"entity_id\");--> statement-breakpoint\nCREATE INDEX \"events_project_at\" ON \"events\" USING btree (\"project_id\",\"at\");--> statement-breakpoint\nCREATE UNIQUE INDEX \"items_project_ref\" ON \"items\" USING btree (\"project_id\",\"ref\");--> statement-breakpoint\nCREATE INDEX \"items_project_status\" ON \"items\" USING btree (\"project_id\",\"status\");--> statement-breakpoint\nCREATE INDEX \"items_project_area\" ON \"items\" USING btree (\"project_id\",\"area_key\");--> statement-breakpoint\nCREATE INDEX \"items_project_sort\" ON \"items\" USING btree (\"project_id\",\"sort_path\");--> statement-breakpoint\nCREATE INDEX \"items_parent\" ON \"items\" USING btree (\"parent_id\");";
|
|
434
|
+
// src/db/migrations/0001_sleepy_gorilla_man.sql?raw
|
|
435
|
+
var _0001_sleepy_gorilla_man_default = "CREATE TABLE \"context_sections\" (\n \"id\" text PRIMARY KEY NOT NULL,\n \"project_id\" text NOT NULL,\n \"heading\" text NOT NULL,\n \"content\" text NOT NULL,\n \"sort_order\" integer DEFAULT 0 NOT NULL,\n \"created_at\" text NOT NULL,\n \"updated_at\" text NOT NULL\n);\n--> statement-breakpoint\nCREATE TABLE \"sessions\" (\n \"id\" text PRIMARY KEY NOT NULL,\n \"project_id\" text NOT NULL,\n \"started_at\" text NOT NULL,\n \"ended_at\" text,\n \"summary\" text,\n \"actor\" text NOT NULL,\n \"compacted_into\" text,\n \"created_at\" text NOT NULL\n);\n--> statement-breakpoint\nALTER TABLE \"context_sections\" ADD CONSTRAINT \"context_sections_project_id_projects_id_fk\" FOREIGN KEY (\"project_id\") REFERENCES \"public\".\"projects\"(\"id\") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint\nALTER TABLE \"sessions\" ADD CONSTRAINT \"sessions_project_id_projects_id_fk\" FOREIGN KEY (\"project_id\") REFERENCES \"public\".\"projects\"(\"id\") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint\nALTER TABLE \"sessions\" ADD CONSTRAINT \"sessions_compacted_into_sessions_id_fk\" FOREIGN KEY (\"compacted_into\") REFERENCES \"public\".\"sessions\"(\"id\") ON DELETE set null ON UPDATE no action;--> statement-breakpoint\nCREATE UNIQUE INDEX \"context_sections_project_heading\" ON \"context_sections\" USING btree (\"project_id\",\"heading\");--> statement-breakpoint\nCREATE INDEX \"context_sections_project_order\" ON \"context_sections\" USING btree (\"project_id\",\"sort_order\");--> statement-breakpoint\nCREATE INDEX \"sessions_project_started\" ON \"sessions\" USING btree (\"project_id\",\"started_at\");";
|
|
436
|
+
// src/db/migrations/0002_smart_ikaris.sql?raw
|
|
437
|
+
var _0002_smart_ikaris_default = "CREATE TABLE \"notes\" (\n \"id\" text PRIMARY KEY NOT NULL,\n \"project_id\" text NOT NULL,\n \"item_id\" text,\n \"body\" text NOT NULL,\n \"audience\" text DEFAULT 'user' NOT NULL,\n \"actor\" text NOT NULL,\n \"created_at\" text NOT NULL\n);\n--> statement-breakpoint\nALTER TABLE \"notes\" ADD CONSTRAINT \"notes_project_id_projects_id_fk\" FOREIGN KEY (\"project_id\") REFERENCES \"public\".\"projects\"(\"id\") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint\nALTER TABLE \"notes\" ADD CONSTRAINT \"notes_item_id_items_id_fk\" FOREIGN KEY (\"item_id\") REFERENCES \"public\".\"items\"(\"id\") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint\nCREATE INDEX \"notes_project_created\" ON \"notes\" USING btree (\"project_id\",\"created_at\");--> statement-breakpoint\nCREATE INDEX \"notes_item\" ON \"notes\" USING btree (\"item_id\");";
|
|
438
|
+
// src/db/migrations/0003_pink_zodiak.sql?raw
|
|
439
|
+
var _0003_pink_zodiak_default = "CREATE TABLE \"attachments\" (\n \"id\" text PRIMARY KEY NOT NULL,\n \"project_id\" text NOT NULL,\n \"item_id\" text,\n \"hash\" text NOT NULL,\n \"mime\" text NOT NULL,\n \"bytes\" integer NOT NULL,\n \"caption\" text,\n \"actor\" text NOT NULL,\n \"created_at\" text NOT NULL\n);\n--> statement-breakpoint\nALTER TABLE \"attachments\" ADD CONSTRAINT \"attachments_project_id_projects_id_fk\" FOREIGN KEY (\"project_id\") REFERENCES \"public\".\"projects\"(\"id\") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint\nALTER TABLE \"attachments\" ADD CONSTRAINT \"attachments_item_id_items_id_fk\" FOREIGN KEY (\"item_id\") REFERENCES \"public\".\"items\"(\"id\") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint\nCREATE INDEX \"attachments_project_item\" ON \"attachments\" USING btree (\"project_id\",\"item_id\");--> statement-breakpoint\nCREATE INDEX \"attachments_hash\" ON \"attachments\" USING btree (\"hash\");--> statement-breakpoint\nCREATE UNIQUE INDEX \"attachments_item_hash\" ON \"attachments\" USING btree (\"project_id\",\"item_id\",\"hash\");";
|
|
440
|
+
// src/db/migrations/0004_loose_hitman.sql?raw
|
|
441
|
+
var _0004_loose_hitman_default = "CREATE TABLE \"users\" (\n \"id\" text PRIMARY KEY NOT NULL,\n \"issuer\" text NOT NULL,\n \"subject\" text NOT NULL,\n \"email\" text,\n \"created_at\" text NOT NULL\n);\n--> statement-breakpoint\nALTER TABLE \"projects\" DROP CONSTRAINT \"projects_key_unique\";--> statement-breakpoint\nALTER TABLE \"projects\" ADD COLUMN \"owner_id\" text NOT NULL;--> statement-breakpoint\nCREATE UNIQUE INDEX \"users_issuer_subject\" ON \"users\" USING btree (\"issuer\",\"subject\");--> statement-breakpoint\nCREATE UNIQUE INDEX \"users_email\" ON \"users\" USING btree (\"email\");--> statement-breakpoint\nALTER TABLE \"projects\" ADD CONSTRAINT \"projects_owner_id_users_id_fk\" FOREIGN KEY (\"owner_id\") REFERENCES \"public\".\"users\"(\"id\") ON DELETE no action ON UPDATE no action;--> statement-breakpoint\nCREATE UNIQUE INDEX \"projects_owner_key\" ON \"projects\" USING btree (\"owner_id\",\"key\");";
|
|
442
|
+
// src/db/migrations/0005_glamorous_typhoid_mary.sql?raw
|
|
443
|
+
var _0005_glamorous_typhoid_mary_default = "CREATE TABLE \"allowed_emails\" (\n \"email\" text PRIMARY KEY NOT NULL,\n \"note\" text,\n \"created_at\" text NOT NULL\n);\n";
|
|
444
|
+
// src/db/migrations/0006_slow_deadpool.sql?raw
|
|
445
|
+
var _0006_slow_deadpool_default = "ALTER TABLE \"allowed_emails\" ALTER COLUMN \"created_at\" SET DEFAULT to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"');";
|
|
446
|
+
// src/db/migrations/0007_jittery_tag.sql?raw
|
|
447
|
+
var _0007_jittery_tag_default = "ALTER TABLE \"context_sections\" ADD COLUMN \"tsv\" \"tsvector\" GENERATED ALWAYS AS (setweight(to_tsvector('english', coalesce(\"heading\", '')), 'A') || setweight(to_tsvector('english', coalesce(\"content\", '')), 'B')) STORED;--> statement-breakpoint\nALTER TABLE \"items\" ADD COLUMN \"tsv\" \"tsvector\" GENERATED ALWAYS AS (setweight(to_tsvector('english', coalesce(\"title\", '')), 'A') || setweight(to_tsvector('english', coalesce(\"body\", '')), 'B')) STORED;--> statement-breakpoint\nALTER TABLE \"notes\" ADD COLUMN \"tsv\" \"tsvector\" GENERATED ALWAYS AS (setweight(to_tsvector('english', coalesce(\"body\", '')), 'A')) STORED;--> statement-breakpoint\nALTER TABLE \"sessions\" ADD COLUMN \"tsv\" \"tsvector\" GENERATED ALWAYS AS (setweight(to_tsvector('english', coalesce(\"summary\", '')), 'A')) STORED;--> statement-breakpoint\nCREATE INDEX \"context_sections_tsv\" ON \"context_sections\" USING gin (\"tsv\");--> statement-breakpoint\nCREATE INDEX \"items_tsv\" ON \"items\" USING gin (\"tsv\");--> statement-breakpoint\nCREATE INDEX \"notes_tsv\" ON \"notes\" USING gin (\"tsv\");--> statement-breakpoint\nCREATE INDEX \"sessions_tsv\" ON \"sessions\" USING gin (\"tsv\");";
|
|
448
|
+
// src/db/migrations/0008_daily_firestar.sql?raw
|
|
449
|
+
var _0008_daily_firestar_default = "DROP TABLE \"sessions\" CASCADE;";
|
|
450
|
+
// src/db/migrations/0009_cute_marvex.sql?raw
|
|
451
|
+
var _0009_cute_marvex_default = "ALTER TABLE \"notes\" RENAME TO \"comments\";--> statement-breakpoint\nALTER TABLE \"comments\" DROP CONSTRAINT \"notes_project_id_projects_id_fk\";\n--> statement-breakpoint\nALTER TABLE \"comments\" DROP CONSTRAINT \"notes_item_id_items_id_fk\";\n--> statement-breakpoint\nDROP INDEX \"notes_project_created\";--> statement-breakpoint\nDROP INDEX \"notes_item\";--> statement-breakpoint\nDROP INDEX \"notes_tsv\";--> statement-breakpoint\nALTER TABLE \"comments\" ADD CONSTRAINT \"comments_project_id_projects_id_fk\" FOREIGN KEY (\"project_id\") REFERENCES \"public\".\"projects\"(\"id\") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint\nALTER TABLE \"comments\" ADD CONSTRAINT \"comments_item_id_items_id_fk\" FOREIGN KEY (\"item_id\") REFERENCES \"public\".\"items\"(\"id\") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint\nCREATE INDEX \"comments_project_created\" ON \"comments\" USING btree (\"project_id\",\"created_at\");--> statement-breakpoint\nCREATE INDEX \"comments_item\" ON \"comments\" USING btree (\"item_id\");--> statement-breakpoint\nCREATE INDEX \"comments_tsv\" ON \"comments\" USING gin (\"tsv\");";
|
|
452
|
+
// src/db/migrations/0010_acoustic_pixie.sql?raw
|
|
453
|
+
var _0010_acoustic_pixie_default = "CREATE TABLE \"project_next\" (\n \"project_id\" text NOT NULL,\n \"item_id\" text NOT NULL,\n \"position\" integer NOT NULL,\n CONSTRAINT \"project_next_project_id_item_id_pk\" PRIMARY KEY(\"project_id\",\"item_id\")\n);\n--> statement-breakpoint\nALTER TABLE \"project_next\" ADD CONSTRAINT \"project_next_project_id_projects_id_fk\" FOREIGN KEY (\"project_id\") REFERENCES \"public\".\"projects\"(\"id\") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint\nALTER TABLE \"project_next\" ADD CONSTRAINT \"project_next_item_id_items_id_fk\" FOREIGN KEY (\"item_id\") REFERENCES \"public\".\"items\"(\"id\") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint\nCREATE UNIQUE INDEX \"project_next_position\" ON \"project_next\" USING btree (\"project_id\",\"position\");";
|
|
454
|
+
// src/db/migrations/0011_orange_rawhide_kid.sql?raw
|
|
455
|
+
var _0011_orange_rawhide_kid_default = "ALTER TABLE \"items\" DROP COLUMN \"priority\";";
|
|
456
|
+
// src/db/migrations/0012_smiling_butterfly.sql?raw
|
|
457
|
+
var _0012_smiling_butterfly_default = "CREATE TABLE \"measurements\" (\n \"id\" text PRIMARY KEY NOT NULL,\n \"project_id\" text NOT NULL,\n \"item_id\" text,\n \"parent_id\" text,\n \"metric\" text NOT NULL,\n \"value\" double precision,\n \"text_value\" text,\n \"unit\" text,\n \"label\" text,\n \"at\" text NOT NULL,\n \"source\" text,\n \"actor\" text NOT NULL,\n \"created_at\" text NOT NULL,\n CONSTRAINT \"measurements_one_reading\" CHECK (NOT (\"measurements\".\"value\" IS NOT NULL AND \"measurements\".\"text_value\" IS NOT NULL))\n);\n--> statement-breakpoint\nALTER TABLE \"measurements\" ADD CONSTRAINT \"measurements_project_id_projects_id_fk\" FOREIGN KEY (\"project_id\") REFERENCES \"public\".\"projects\"(\"id\") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint\nALTER TABLE \"measurements\" ADD CONSTRAINT \"measurements_item_id_items_id_fk\" FOREIGN KEY (\"item_id\") REFERENCES \"public\".\"items\"(\"id\") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint\nALTER TABLE \"measurements\" ADD CONSTRAINT \"measurements_parent_id_measurements_id_fk\" FOREIGN KEY (\"parent_id\") REFERENCES \"public\".\"measurements\"(\"id\") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint\nCREATE INDEX \"measurements_project_metric_at\" ON \"measurements\" USING btree (\"project_id\",\"metric\",\"at\");--> statement-breakpoint\nCREATE INDEX \"measurements_item\" ON \"measurements\" USING btree (\"item_id\");--> statement-breakpoint\nCREATE INDEX \"measurements_parent\" ON \"measurements\" USING btree (\"parent_id\");";
|
|
458
|
+
// src/db/migrations/0013_kind_bloodscream.sql?raw
|
|
459
|
+
var _0013_kind_bloodscream_default = "CREATE TABLE \"scoped_dependencies\" (\n \"item_id\" text NOT NULL,\n \"target_project\" text NOT NULL,\n \"target_ref\" text NOT NULL,\n \"created_at\" text NOT NULL,\n CONSTRAINT \"scoped_dependencies_item_id_target_project_target_ref_pk\" PRIMARY KEY(\"item_id\",\"target_project\",\"target_ref\")\n);\n--> statement-breakpoint\nALTER TABLE \"scoped_dependencies\" ADD CONSTRAINT \"scoped_dependencies_item_id_items_id_fk\" FOREIGN KEY (\"item_id\") REFERENCES \"public\".\"items\"(\"id\") ON DELETE cascade ON UPDATE no action;";
|
|
460
|
+
// src/db/migrations/0014_past_chronomancer.sql?raw
|
|
461
|
+
var _0014_past_chronomancer_default = "ALTER TABLE \"items\" ADD COLUMN \"start_on\" text;--> statement-breakpoint\nALTER TABLE \"items\" ADD COLUMN \"due_on\" text;--> statement-breakpoint\nCREATE INDEX \"items_project_due\" ON \"items\" USING btree (\"project_id\",\"due_on\");";
|
|
462
|
+
// src/db/migrations/0015_stormy_blindfold.sql?raw
|
|
463
|
+
var _0015_stormy_blindfold_default = "CREATE TABLE \"layout_positions\" (\n \"project_id\" text NOT NULL,\n \"node\" text NOT NULL,\n \"x\" integer NOT NULL,\n \"y\" integer NOT NULL,\n CONSTRAINT \"layout_positions_project_id_node_pk\" PRIMARY KEY(\"project_id\",\"node\")\n);\n--> statement-breakpoint\nALTER TABLE \"layout_positions\" ADD CONSTRAINT \"layout_positions_project_id_projects_id_fk\" FOREIGN KEY (\"project_id\") REFERENCES \"public\".\"projects\"(\"id\") ON DELETE cascade ON UPDATE no action;";
|
|
464
|
+
var _journal_default = {
|
|
465
|
+
version: "7",
|
|
466
|
+
dialect: "postgresql",
|
|
467
|
+
entries: [
|
|
468
|
+
{
|
|
469
|
+
"idx": 0,
|
|
470
|
+
"version": "7",
|
|
471
|
+
"when": 1784899598232,
|
|
472
|
+
"tag": "0000_burly_firestar",
|
|
473
|
+
"breakpoints": true
|
|
474
|
+
},
|
|
475
|
+
{
|
|
476
|
+
"idx": 1,
|
|
477
|
+
"version": "7",
|
|
478
|
+
"when": 1784913815072,
|
|
479
|
+
"tag": "0001_sleepy_gorilla_man",
|
|
480
|
+
"breakpoints": true
|
|
481
|
+
},
|
|
482
|
+
{
|
|
483
|
+
"idx": 2,
|
|
484
|
+
"version": "7",
|
|
485
|
+
"when": 1785248894876,
|
|
486
|
+
"tag": "0002_smart_ikaris",
|
|
487
|
+
"breakpoints": true
|
|
488
|
+
},
|
|
489
|
+
{
|
|
490
|
+
"idx": 3,
|
|
491
|
+
"version": "7",
|
|
492
|
+
"when": 1785494222282,
|
|
493
|
+
"tag": "0003_pink_zodiak",
|
|
494
|
+
"breakpoints": true
|
|
495
|
+
},
|
|
496
|
+
{
|
|
497
|
+
"idx": 4,
|
|
498
|
+
"version": "7",
|
|
499
|
+
"when": 1788127474688,
|
|
500
|
+
"tag": "0004_loose_hitman",
|
|
501
|
+
"breakpoints": true
|
|
502
|
+
},
|
|
503
|
+
{
|
|
504
|
+
"idx": 5,
|
|
505
|
+
"version": "7",
|
|
506
|
+
"when": 1788191498092,
|
|
507
|
+
"tag": "0005_glamorous_typhoid_mary",
|
|
508
|
+
"breakpoints": true
|
|
509
|
+
},
|
|
510
|
+
{
|
|
511
|
+
"idx": 6,
|
|
512
|
+
"version": "7",
|
|
513
|
+
"when": 1788192487724,
|
|
514
|
+
"tag": "0006_slow_deadpool",
|
|
515
|
+
"breakpoints": true
|
|
516
|
+
},
|
|
517
|
+
{
|
|
518
|
+
"idx": 7,
|
|
519
|
+
"version": "7",
|
|
520
|
+
"when": 1788275809877,
|
|
521
|
+
"tag": "0007_jittery_tag",
|
|
522
|
+
"breakpoints": true
|
|
523
|
+
},
|
|
524
|
+
{
|
|
525
|
+
"idx": 8,
|
|
526
|
+
"version": "7",
|
|
527
|
+
"when": 1788298194195,
|
|
528
|
+
"tag": "0008_daily_firestar",
|
|
529
|
+
"breakpoints": true
|
|
530
|
+
},
|
|
531
|
+
{
|
|
532
|
+
"idx": 9,
|
|
533
|
+
"version": "7",
|
|
534
|
+
"when": 1788299093758,
|
|
535
|
+
"tag": "0009_cute_marvex",
|
|
536
|
+
"breakpoints": true
|
|
537
|
+
},
|
|
538
|
+
{
|
|
539
|
+
"idx": 10,
|
|
540
|
+
"version": "7",
|
|
541
|
+
"when": 1788375271316,
|
|
542
|
+
"tag": "0010_acoustic_pixie",
|
|
543
|
+
"breakpoints": true
|
|
544
|
+
},
|
|
545
|
+
{
|
|
546
|
+
"idx": 11,
|
|
547
|
+
"version": "7",
|
|
548
|
+
"when": 1788377979673,
|
|
549
|
+
"tag": "0011_orange_rawhide_kid",
|
|
550
|
+
"breakpoints": true
|
|
551
|
+
},
|
|
552
|
+
{
|
|
553
|
+
"idx": 12,
|
|
554
|
+
"version": "7",
|
|
555
|
+
"when": 1788381139129,
|
|
556
|
+
"tag": "0012_smiling_butterfly",
|
|
557
|
+
"breakpoints": true
|
|
558
|
+
},
|
|
559
|
+
{
|
|
560
|
+
"idx": 13,
|
|
561
|
+
"version": "7",
|
|
562
|
+
"when": 1790032589899,
|
|
563
|
+
"tag": "0013_kind_bloodscream",
|
|
564
|
+
"breakpoints": true
|
|
565
|
+
},
|
|
566
|
+
{
|
|
567
|
+
"idx": 14,
|
|
568
|
+
"version": "7",
|
|
569
|
+
"when": 1793292077069,
|
|
570
|
+
"tag": "0014_past_chronomancer",
|
|
571
|
+
"breakpoints": true
|
|
572
|
+
},
|
|
573
|
+
{
|
|
574
|
+
"idx": 15,
|
|
575
|
+
"version": "7",
|
|
576
|
+
"when": 1794545387434,
|
|
577
|
+
"tag": "0015_stormy_blindfold",
|
|
578
|
+
"breakpoints": true
|
|
579
|
+
}
|
|
580
|
+
]
|
|
486
581
|
};
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
582
|
+
// src/db/bundledMigrations.ts
|
|
583
|
+
/** Each `.sql` file's text, keyed by its path relative to this module (`./migrations/0000_burly_firestar.sql`). */
|
|
584
|
+
var files = /* #__PURE__ */ Object.assign({
|
|
585
|
+
"./migrations/0000_burly_firestar.sql": _0000_burly_firestar_default,
|
|
586
|
+
"./migrations/0001_sleepy_gorilla_man.sql": _0001_sleepy_gorilla_man_default,
|
|
587
|
+
"./migrations/0002_smart_ikaris.sql": _0002_smart_ikaris_default,
|
|
588
|
+
"./migrations/0003_pink_zodiak.sql": _0003_pink_zodiak_default,
|
|
589
|
+
"./migrations/0004_loose_hitman.sql": _0004_loose_hitman_default,
|
|
590
|
+
"./migrations/0005_glamorous_typhoid_mary.sql": _0005_glamorous_typhoid_mary_default,
|
|
591
|
+
"./migrations/0006_slow_deadpool.sql": _0006_slow_deadpool_default,
|
|
592
|
+
"./migrations/0007_jittery_tag.sql": _0007_jittery_tag_default,
|
|
593
|
+
"./migrations/0008_daily_firestar.sql": _0008_daily_firestar_default,
|
|
594
|
+
"./migrations/0009_cute_marvex.sql": _0009_cute_marvex_default,
|
|
595
|
+
"./migrations/0010_acoustic_pixie.sql": _0010_acoustic_pixie_default,
|
|
596
|
+
"./migrations/0011_orange_rawhide_kid.sql": _0011_orange_rawhide_kid_default,
|
|
597
|
+
"./migrations/0012_smiling_butterfly.sql": _0012_smiling_butterfly_default,
|
|
598
|
+
"./migrations/0013_kind_bloodscream.sql": _0013_kind_bloodscream_default,
|
|
599
|
+
"./migrations/0014_past_chronomancer.sql": _0014_past_chronomancer_default,
|
|
600
|
+
"./migrations/0015_stormy_blindfold.sql": _0015_stormy_blindfold_default
|
|
601
|
+
});
|
|
602
|
+
/** The breakpoint drizzle-kit writes between statements, and that drizzle's reader splits on. */
|
|
603
|
+
var BREAKPOINT = "--> statement-breakpoint";
|
|
604
|
+
/** Hex sha256 through Web Crypto, which both Node 22 and a browser have, where `node:crypto` is only the first. */
|
|
605
|
+
async function sha256(text) {
|
|
606
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
|
|
607
|
+
return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
492
608
|
}
|
|
609
|
+
/** The journal's migrations in order, ready for `PgDialect.migrate`. Throws if the journal names a file the build
|
|
610
|
+
* does not hold, which is the bundled form of drizzle's "No file ... found" and just as fatal. */
|
|
493
611
|
async function bundledMigrations() {
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
612
|
+
return Promise.all(_journal_default.entries.map(async (entry) => {
|
|
613
|
+
const text = files[`./migrations/${entry.tag}.sql`];
|
|
614
|
+
if (text === void 0) throw new Error(`migration ${entry.tag} is in the journal but not in the build`);
|
|
615
|
+
return {
|
|
616
|
+
sql: text.split(BREAKPOINT),
|
|
617
|
+
bps: entry.breakpoints,
|
|
618
|
+
folderMillis: entry.when,
|
|
619
|
+
hash: await sha256(text)
|
|
620
|
+
};
|
|
621
|
+
}));
|
|
501
622
|
}
|
|
623
|
+
// src/db/memory.ts
|
|
624
|
+
/**
|
|
625
|
+
* A fresh in-memory PGlite database with the schema built: the disposable query engine of `client.ts`'s header,
|
|
626
|
+
* which the plan YAML is rebuilt into on load.
|
|
627
|
+
*
|
|
628
|
+
* Its own module, apart from `client.ts`, because it compiles the migrations in (`bundledMigrations.ts`, so it
|
|
629
|
+
* runs in a browser, `DIST-6`) and that uses `import.meta.glob`, which exists only under vite's transform. The
|
|
630
|
+
* viewer's `vite.config.ts` reaches `client.ts` through `serialise/store.ts`, and esbuild loads that config
|
|
631
|
+
* without vite's transform, so the glob must not be on that path. A lazy import would dodge it too, but vite-node
|
|
632
|
+
* closes its module server once the entry finishes evaluating, and the stdio server's `main()` is not awaited,
|
|
633
|
+
* so an import that late is refused.
|
|
634
|
+
*/
|
|
635
|
+
/**
|
|
636
|
+
* A fresh in-memory database with the schema built. Each call is independent, so tests share nothing; in the
|
|
637
|
+
* server this is called once and the handle kept alive for the process.
|
|
638
|
+
*/
|
|
502
639
|
async function createInMemoryDb() {
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
640
|
+
const client = new PGlite();
|
|
641
|
+
const db = drizzle(client, { schema: schema_exports });
|
|
642
|
+
await new PgDialect().migrate(await bundledMigrations(), db._.session, { migrationsFolder: "(bundled)" });
|
|
643
|
+
return {
|
|
644
|
+
db,
|
|
645
|
+
close: () => client.close()
|
|
646
|
+
};
|
|
510
647
|
}
|
|
511
|
-
Object.values(
|
|
512
|
-
|
|
648
|
+
Object.values(schema_exports).filter((value) => is(value, PgTable));
|
|
649
|
+
getTableName(users);
|
|
650
|
+
// src/db/rows.ts
|
|
651
|
+
/**
|
|
652
|
+
* Small helpers for reading Drizzle result arrays under `noUncheckedIndexedAccess`, where `rows[0]` and a
|
|
653
|
+
* destructured `[row]` are both `T | undefined`. Insert/update `.returning()` and by-id lookups are meant to
|
|
654
|
+
* produce exactly one row, so collapsing that to `T` (throwing when the assumption is wrong) keeps the call
|
|
655
|
+
* sites honest instead of scattering `!` or `?? throw` everywhere.
|
|
656
|
+
*
|
|
657
|
+
* `rowsOf` is the same idea for raw SQL, and is the single place the two drivers are reconciled (OPS-2).
|
|
658
|
+
*/
|
|
659
|
+
/** The single row a `.returning()` or unique lookup was meant to produce. Throws on none. */
|
|
513
660
|
function one(rows) {
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
661
|
+
const [row] = rows;
|
|
662
|
+
if (row === void 0) throw new Error("expected exactly one row, got none");
|
|
663
|
+
return row;
|
|
517
664
|
}
|
|
665
|
+
/** The first row, or null when there is none. For lookups that legitimately may miss. */
|
|
518
666
|
function maybeOne(rows) {
|
|
519
|
-
|
|
667
|
+
return rows[0] ?? null;
|
|
520
668
|
}
|
|
669
|
+
/**
|
|
670
|
+
* The rows of a raw `execute()`, typed by the caller.
|
|
671
|
+
*
|
|
672
|
+
* Raw SQL is where the driver seam actually shows. The `Database` type names what PGlite and node-postgres
|
|
673
|
+
* have in common (`PgDatabase<PgQueryResultHKT, ...>`), and at that base `execute()` is typed `unknown`,
|
|
674
|
+
* because the shape of a raw result is precisely what the two drivers disagree about in the type system. They
|
|
675
|
+
* do not disagree at runtime: both return `{ rows }`. So this is the one authorised cast, kept here rather
|
|
676
|
+
* than at each `WITH RECURSIVE` and full-text query, where it would be re-derived slightly differently every
|
|
677
|
+
* time and would have to be revisited driver by driver.
|
|
678
|
+
*
|
|
679
|
+
* The caller names the row type because raw SQL has no schema for us to infer from - the same bargain as
|
|
680
|
+
* `sql<string>` in a select. That is unchecked by construction, so keep raw queries few, which the storage
|
|
681
|
+
* notes already require: CTEs and full-text search only.
|
|
682
|
+
*
|
|
683
|
+
* A result with no `rows` **throws** rather than reading as empty. The version this replaces returned `[]`,
|
|
684
|
+
* and its only caller is the cycle check: an empty result there means "no cycle found", so a driver that ever
|
|
685
|
+
* stopped returning `{ rows }` would not fail, it would quietly let cyclic dependencies through. A driver
|
|
686
|
+
* contract this code cannot verify is exactly the thing that must be loud when it breaks.
|
|
687
|
+
*/
|
|
521
688
|
function rowsOf(result) {
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
689
|
+
const rows = result.rows;
|
|
690
|
+
if (!Array.isArray(rows)) throw new Error("raw query returned no `rows`: the database driver is not one this code knows");
|
|
691
|
+
return rows;
|
|
525
692
|
}
|
|
693
|
+
// src/domain/events.ts
|
|
526
694
|
async function recordEvent(tx, event) {
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
});
|
|
695
|
+
await tx.insert(events).values({
|
|
696
|
+
projectId: event.projectId,
|
|
697
|
+
entityType: event.entityType,
|
|
698
|
+
entityId: event.entityId,
|
|
699
|
+
kind: event.kind,
|
|
700
|
+
actor: event.actor,
|
|
701
|
+
correlationId: event.correlationId ?? null,
|
|
702
|
+
before: event.before === void 0 ? null : JSON.stringify(event.before),
|
|
703
|
+
after: event.after === void 0 ? null : JSON.stringify(event.after)
|
|
704
|
+
});
|
|
538
705
|
}
|
|
706
|
+
/**
|
|
707
|
+
* Run a mutation in a transaction that MUST produce an event. Every mutating domain function goes through
|
|
708
|
+
* this, which enforces the house rule by construction rather than convention: the body returns its `result`
|
|
709
|
+
* and the `event` to record, so it is impossible to forget the log or to write it outside the transaction.
|
|
710
|
+
* `actor` is threaded in once here, so the body supplies only the rest of the event.
|
|
711
|
+
*
|
|
712
|
+
* One event per call, deliberately: that fits every mutation today (a compound op composes several `mutate`
|
|
713
|
+
* calls). Widen `event` to an array only if a single transaction ever needs to log more than one.
|
|
714
|
+
*/
|
|
539
715
|
async function mutate(db, actor, body) {
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
716
|
+
return db.transaction(async (tx) => {
|
|
717
|
+
const { result, event } = await body(tx);
|
|
718
|
+
await recordEvent(tx, {
|
|
719
|
+
...event,
|
|
720
|
+
actor
|
|
721
|
+
});
|
|
722
|
+
return result;
|
|
723
|
+
});
|
|
545
724
|
}
|
|
546
|
-
|
|
725
|
+
// src/domain/users.ts
|
|
726
|
+
/**
|
|
727
|
+
* Accounts (`OPS-4`): resolving a verified token into the row that owns things.
|
|
728
|
+
*
|
|
729
|
+
* The identity a token carries and the identity we own are deliberately different. A row here is keyed by an
|
|
730
|
+
* id we generate, with `(issuer, subject)` and `email` as *attributes* - so `projects.owner_id` points at
|
|
731
|
+
* something no provider can invalidate. See the comment on the `users` table for why neither of those is the
|
|
732
|
+
* key; the short version is that a subject is issuer-scoped (a provider change would orphan every project)
|
|
733
|
+
* and an email is only as trustworthy as whoever asserted it.
|
|
734
|
+
*
|
|
735
|
+
* `ensureUser` is the whole of the module because provisioning is just-in-time: there is no sign-up step, so
|
|
736
|
+
* the first authenticated request is what creates the row.
|
|
737
|
+
*/
|
|
738
|
+
/**
|
|
739
|
+
* The single user of a file-backed store. File mode has no authentication and never will - it is one person's
|
|
740
|
+
* checkout - but the domain layer must not have to ask whether a caller exists, or "is there a caller" becomes
|
|
741
|
+
* a branch on every scoped query and the unauthenticated path becomes the untested one. So file mode
|
|
742
|
+
* synthesises this identity instead and takes exactly the same path as a token.
|
|
743
|
+
*
|
|
744
|
+
* `local` is not a reserved word to any real issuer, so it cannot collide with one.
|
|
745
|
+
*/
|
|
746
|
+
var LOCAL_IDENTITY = {
|
|
747
|
+
issuer: "local",
|
|
748
|
+
subject: "local"
|
|
749
|
+
};
|
|
750
|
+
/**
|
|
751
|
+
* The address to store, which is **only ever a verified one**.
|
|
752
|
+
*
|
|
753
|
+
* Making the column mean "an address some issuer vouched for" rather than "whatever the last token said" is
|
|
754
|
+
* what makes the linking fallback safe by construction instead of safe by remembering to check. An unverified
|
|
755
|
+
* claim is discarded rather than rejected, so someone whose provider will not vouch for their address still
|
|
756
|
+
* gets in - they simply get an account of their own rather than one that already exists.
|
|
757
|
+
*
|
|
758
|
+
* Lower-cased because that is how it is compared, and the unique index has to agree with the lookup about what
|
|
759
|
+
* counts as a duplicate.
|
|
760
|
+
*/
|
|
547
761
|
function verifiedEmail(identity) {
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
762
|
+
if (identity.emailVerified !== true) return null;
|
|
763
|
+
const email = identity.email?.trim().toLowerCase();
|
|
764
|
+
return email === void 0 || email === "" ? null : email;
|
|
551
765
|
}
|
|
766
|
+
/**
|
|
767
|
+
* The row for this identity, created on first sight.
|
|
768
|
+
*
|
|
769
|
+
* Three steps, and the middle one is the whole point:
|
|
770
|
+
*
|
|
771
|
+
* 1. **By `(issuer, subject)`** - the normal path, every request after the first. Exact, cheap, and immune to
|
|
772
|
+
* anything an email claim might be lying about.
|
|
773
|
+
* 2. **By verified email**, when step 1 misses: bind this new subject onto the existing row and carry on. This
|
|
774
|
+
* is what makes changing auth provider self-healing - each person's first login afterwards re-binds their
|
|
775
|
+
* own row - rather than a hand-written remap against a table of orphans. Only a *verified* address is ever
|
|
776
|
+
* stored (see `verifiedEmail`), so this step cannot match on one nobody vouched for - which is the
|
|
777
|
+
* difference between account linking and account takeover.
|
|
778
|
+
* 3. **Create**, when neither matched.
|
|
779
|
+
*
|
|
780
|
+
* All three run in one transaction, so two concurrent first requests from the same person cannot produce two
|
|
781
|
+
* rows - the unique indexes decide, and the loser's insert fails rather than silently duplicating an account.
|
|
782
|
+
*
|
|
783
|
+
* Only steps 2 and 3 write an event. Step 1 is the common case and logging it would append a row per request,
|
|
784
|
+
* drowning the log it is supposed to make readable; a linking or a creation is exactly the rare, consequential
|
|
785
|
+
* thing an audit trail is for.
|
|
786
|
+
*/
|
|
552
787
|
async function ensureUser(db, identity) {
|
|
553
|
-
|
|
788
|
+
return db.transaction((tx) => ensureUserIn(tx, identity));
|
|
554
789
|
}
|
|
790
|
+
/**
|
|
791
|
+
* The same thing for a caller already inside a transaction - the YAML importer, which must stamp the local
|
|
792
|
+
* owner onto every project it inserts and cannot open a nested one.
|
|
793
|
+
*/
|
|
555
794
|
async function ensureUserIn(tx, identity) {
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
795
|
+
const email = verifiedEmail(identity);
|
|
796
|
+
{
|
|
797
|
+
const bySubject = maybeOne(await tx.select().from(users).where(and(eq(users.issuer, identity.issuer), eq(users.subject, identity.subject))));
|
|
798
|
+
if (bySubject !== null) return refreshEmail(tx, bySubject, email);
|
|
799
|
+
if (email !== null) {
|
|
800
|
+
const byEmail = maybeOne(await tx.select().from(users).where(eq(users.email, email)));
|
|
801
|
+
if (byEmail !== null) {
|
|
802
|
+
const linked = one(await tx.update(users).set({
|
|
803
|
+
issuer: identity.issuer,
|
|
804
|
+
subject: identity.subject
|
|
805
|
+
}).where(eq(users.id, byEmail.id)).returning());
|
|
806
|
+
await recordEvent(tx, {
|
|
807
|
+
projectId: null,
|
|
808
|
+
entityType: "user",
|
|
809
|
+
entityId: linked.id,
|
|
810
|
+
kind: "linked",
|
|
811
|
+
actor: linked.id,
|
|
812
|
+
before: byEmail,
|
|
813
|
+
after: linked
|
|
814
|
+
});
|
|
815
|
+
return linked;
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
const created = one(await tx.insert(users).values({
|
|
819
|
+
issuer: identity.issuer,
|
|
820
|
+
subject: identity.subject,
|
|
821
|
+
email
|
|
822
|
+
}).returning());
|
|
823
|
+
await recordEvent(tx, {
|
|
824
|
+
projectId: null,
|
|
825
|
+
entityType: "user",
|
|
826
|
+
entityId: created.id,
|
|
827
|
+
kind: "created",
|
|
828
|
+
actor: created.id,
|
|
829
|
+
after: created
|
|
830
|
+
});
|
|
831
|
+
return created;
|
|
832
|
+
}
|
|
594
833
|
}
|
|
834
|
+
/**
|
|
835
|
+
* Keep a stored address in step with the token's, on the ordinary path.
|
|
836
|
+
*
|
|
837
|
+
* Not cosmetic: `email` is what the account-linking fallback matches on, so a stale one would send someone to
|
|
838
|
+
* the wrong row after a provider switch - the exact failure the fallback exists to prevent. Silent, and no
|
|
839
|
+
* event: it is a correction to a cached attribute, not a decision anyone made.
|
|
840
|
+
*
|
|
841
|
+
* A token with no email - or with an unverified one - never clears a stored address. What we once verified is
|
|
842
|
+
* better evidence than what this particular token happens to omit or decline to vouch for.
|
|
843
|
+
*
|
|
844
|
+
* **And it gives up rather than failing when another row already holds the address.** Reachable when someone
|
|
845
|
+
* signs in before their provider verifies them and a second account already has the verified address: this
|
|
846
|
+
* caller has already resolved correctly by `(issuer, subject)`, so the address is an anchor they happen to
|
|
847
|
+
* lack, not their identity - and a login is the wrong place to raise a conflict nobody can act on. The other
|
|
848
|
+
* row keeps it, which is right, because it is the one that proved the address first.
|
|
849
|
+
*
|
|
850
|
+
* A `SELECT` rather than catching the unique violation, deliberately: in Postgres a failed statement aborts
|
|
851
|
+
* the whole transaction, so "try it and recover" would leave the caller with a dead transaction rather than a
|
|
852
|
+
* user. The check and the update are in one transaction either way, so the race just re-runs on the next call.
|
|
853
|
+
*/
|
|
595
854
|
async function refreshEmail(tx, user, email) {
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
return one(await tx.update(users).set({ email }).where(eq(users.id, user.id)).returning());
|
|
855
|
+
if (email === null || email === user.email) return user;
|
|
856
|
+
if (maybeOne(await tx.select({ id: users.id }).from(users).where(eq(users.email, email))) !== null) return user;
|
|
857
|
+
return one(await tx.update(users).set({ email }).where(eq(users.id, user.id)).returning());
|
|
600
858
|
}
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
859
|
+
// src/serialise/format.ts
|
|
860
|
+
var YAML_FORMAT = { lineWidth: 0 };
|
|
861
|
+
// src/serialise/measurementRecords.ts
|
|
862
|
+
/**
|
|
863
|
+
* One recorded reading, as it appears in the file.
|
|
864
|
+
*
|
|
865
|
+
* The subject is written as an **item ref** (`LIFT-1`) rather than a uuid, because a ref is readable in a diff
|
|
866
|
+
* and is the identity the plan file already uses. `parent` stays a uuid: a measurement has no ref to be named
|
|
867
|
+
* by, so its id is the only handle it has.
|
|
868
|
+
*/
|
|
869
|
+
var recordSchema = z.object({
|
|
870
|
+
id: z.string(),
|
|
871
|
+
project: z.string(),
|
|
872
|
+
metric: z.string(),
|
|
873
|
+
value: z.number().optional(),
|
|
874
|
+
text: z.string().optional(),
|
|
875
|
+
unit: z.string().optional(),
|
|
876
|
+
label: z.string().optional(),
|
|
877
|
+
at: z.string(),
|
|
878
|
+
source: z.string().optional(),
|
|
879
|
+
/** The subject item, by ref. Absent means the subject is the project itself. */
|
|
880
|
+
ref: z.string().optional(),
|
|
881
|
+
parent: z.string().optional(),
|
|
882
|
+
actor: z.string(),
|
|
883
|
+
created_at: z.string()
|
|
618
884
|
});
|
|
619
885
|
z.array(recordSchema);
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
886
|
+
// scripts/tickets.ts
|
|
887
|
+
/**
|
|
888
|
+
* The shared ticket model: the status vocabulary, the `RoadmapItem` shape, and `areasOf`. It has NO Node
|
|
889
|
+
* dependencies, so the browser viewer (roadmap/) and the domain layer share one definition of a status and a
|
|
890
|
+
* ticket ref. It began life as the marker-format parser, but the store is the source of truth now and the
|
|
891
|
+
* markdown format is retired, so only the model remains.
|
|
892
|
+
*
|
|
893
|
+
* Status is a fixed vocabulary (below). Areas are open: the prefix of an id defines its area, and a new
|
|
894
|
+
* prefix is picked up automatically - no central list to update.
|
|
895
|
+
*/
|
|
896
|
+
/** The fixed status vocabulary, in workflow order (shipped -> back-of-queue). `icon` is the glyph the
|
|
897
|
+
* viewer shows, `colour` is the hue it uses when colouring by status, and `strike` marks a status whose
|
|
898
|
+
* title is struck through (a closed/complete item). */
|
|
899
|
+
var STATUSES = {
|
|
900
|
+
done: {
|
|
901
|
+
icon: "✓",
|
|
902
|
+
label: "done",
|
|
903
|
+
colour: "#34d399",
|
|
904
|
+
strike: true
|
|
905
|
+
},
|
|
906
|
+
review: {
|
|
907
|
+
icon: "◐",
|
|
908
|
+
label: "review",
|
|
909
|
+
colour: "#a884f3",
|
|
910
|
+
strike: false
|
|
911
|
+
},
|
|
912
|
+
"in-progress": {
|
|
913
|
+
icon: "●",
|
|
914
|
+
label: "in-progress",
|
|
915
|
+
colour: "#4f9dff",
|
|
916
|
+
strike: false
|
|
917
|
+
},
|
|
918
|
+
"to-do": {
|
|
919
|
+
icon: "○",
|
|
920
|
+
label: "to-do",
|
|
921
|
+
colour: "#fbbf24",
|
|
922
|
+
strike: false
|
|
923
|
+
},
|
|
924
|
+
planning: {
|
|
925
|
+
icon: "○",
|
|
926
|
+
label: "planning",
|
|
927
|
+
colour: "#e8590c",
|
|
928
|
+
strike: false
|
|
929
|
+
}
|
|
631
930
|
};
|
|
632
|
-
|
|
633
|
-
|
|
931
|
+
Object.keys(STATUSES);
|
|
932
|
+
/**
|
|
933
|
+
* A well-formed ref: an upper-case area prefix, then dot-separated positive integers (`MCP-3`, `MCP-3.1.2`).
|
|
934
|
+
* Kept here rather than in the domain because the same shape governs `sortPath`, the viewer's nesting and the
|
|
935
|
+
* store schema, and three copies of it would drift.
|
|
936
|
+
*/
|
|
937
|
+
var REF_PATTERN = /^[A-Z][A-Z0-9]*-[1-9]\d*(\.[1-9]\d*)*$/;
|
|
938
|
+
var isRef = (ref) => REF_PATTERN.test(ref);
|
|
939
|
+
/**
|
|
940
|
+
* A ref that names another project before the item: `apm:DIST-1` (`PROJ-11`).
|
|
941
|
+
*
|
|
942
|
+
* Split out rather than folded into `REF_PATTERN`, because the two are asked different questions: `isRef`
|
|
943
|
+
* asks "is this a ref in this project", which a scoped one is not. The colon is unambiguous because an area
|
|
944
|
+
* prefix is the text before the first `-` and a colon appears nowhere in a ref.
|
|
945
|
+
*
|
|
946
|
+
* **The tail must itself be a well-formed ref**, and a scope with a malformed tail returns null rather than
|
|
947
|
+
* throwing: it then falls through to the ordinary local-ref path, which already refuses an unknown ref by
|
|
948
|
+
* name. One refusal to read rather than two that disagree.
|
|
949
|
+
*/
|
|
634
950
|
function splitScope(ref) {
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
951
|
+
const cut = ref.indexOf(":");
|
|
952
|
+
if (cut <= 0) return null;
|
|
953
|
+
const bare = ref.slice(cut + 1);
|
|
954
|
+
return isRef(bare) ? {
|
|
955
|
+
project: ref.slice(0, cut),
|
|
956
|
+
ref: bare
|
|
957
|
+
} : null;
|
|
639
958
|
}
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
959
|
+
/** A ref with any project scope removed, which is the form every ref parser below expects. */
|
|
960
|
+
var unscoped = (ref) => splitScope(ref)?.ref ?? ref;
|
|
961
|
+
/** The area a ref belongs to: everything before the first `-`.
|
|
962
|
+
*
|
|
963
|
+
* Scope-stripped first, or `apm:OPS-9` would report an area of `apm:OPS` and silently invent one. */
|
|
964
|
+
var areaOf = (ref) => {
|
|
965
|
+
const bare = unscoped(ref);
|
|
966
|
+
return bare.slice(0, bare.indexOf("-"));
|
|
644
967
|
};
|
|
968
|
+
/**
|
|
969
|
+
* The parent of a nested ref (`MCP-3.1.2` -> `MCP-3.1`), or null for a top-level one. Nesting is *derived*
|
|
970
|
+
* from the ref rather than stored independently, so this is the only definition of parentage there is.
|
|
971
|
+
*/
|
|
645
972
|
function parentRef(ref) {
|
|
646
|
-
|
|
647
|
-
|
|
973
|
+
const cut = ref.lastIndexOf(".");
|
|
974
|
+
return cut === -1 ? null : ref.slice(0, cut);
|
|
648
975
|
}
|
|
649
|
-
|
|
976
|
+
/**
|
|
977
|
+
* Whether `ref` sits anywhere beneath `ancestor` in the nesting tree.
|
|
978
|
+
*
|
|
979
|
+
* The trailing dot is load-bearing: a bare `startsWith` would call `MCP-30` a child of `MCP-3`, which is the
|
|
980
|
+
* kind of bug that only shows up once a project has thirty tickets in one area.
|
|
981
|
+
*/
|
|
982
|
+
var isNestedUnder = (ancestor, ref) => ref.startsWith(`${ancestor}.`);
|
|
983
|
+
/**
|
|
984
|
+
* A calendar date, `2026-11-02`, as an item's `start` and `due` are written (`CAL-1`).
|
|
985
|
+
*
|
|
986
|
+
* The shape alone would pass `2026-02-30`, so the date is round-tripped through `Date` and has to come back
|
|
987
|
+
* unchanged. Parsed as UTC on purpose: a bare date is a day, not an instant, and reading it in local time is
|
|
988
|
+
* how a due date drifts by one for whoever is west of Greenwich. Here, so the viewer and the domain agree.
|
|
989
|
+
*/
|
|
650
990
|
function isCalendarDate(value) {
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
991
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
|
|
992
|
+
const day = /* @__PURE__ */ new Date(`${value}T00:00:00Z`);
|
|
993
|
+
return !Number.isNaN(day.getTime()) && day.toISOString().startsWith(value);
|
|
654
994
|
}
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
995
|
+
// src/serialise/plan.ts
|
|
996
|
+
/**
|
|
997
|
+
* The plan as data: the YAML schema, and the round trip between it and the database (`exportStore`, `importStore`,
|
|
998
|
+
* `parseStore`, `stringifyStore`). Everything about *where* a plan lives - paths, discovery, atomic writes, the
|
|
999
|
+
* stale-write guard - stays in `store.ts`. The split is `DIST-6`'s: nothing here imports Node, so the in-process
|
|
1000
|
+
* library can open a plan in a browser, and `store.ts` re-exports all of it so no existing import moves.
|
|
1001
|
+
*
|
|
1002
|
+
* The two rules that make the YAML trustworthy are in `store.ts`'s header, and hold for every function here.
|
|
1003
|
+
*/
|
|
1004
|
+
var areaSchema = z.object({
|
|
1005
|
+
key: z.string(),
|
|
1006
|
+
name: z.string(),
|
|
1007
|
+
description: z.string().optional(),
|
|
1008
|
+
colour: z.string().optional(),
|
|
1009
|
+
sort_order: z.number(),
|
|
1010
|
+
id: z.string(),
|
|
1011
|
+
created_at: z.string()
|
|
663
1012
|
});
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
1013
|
+
var commentSchema = z.object({
|
|
1014
|
+
body: z.string(),
|
|
1015
|
+
audience: z.string(),
|
|
1016
|
+
id: z.string(),
|
|
1017
|
+
at: z.string(),
|
|
1018
|
+
actor: z.string()
|
|
670
1019
|
});
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
1020
|
+
/** An attachment carries only the reference: the hash is the blob's identity and the bytes live under
|
|
1021
|
+
* `.apm/media/`. Putting them here instead would end deterministic diffs and could not survive a rebuild. */
|
|
1022
|
+
var attachmentSchema = z.object({
|
|
1023
|
+
hash: z.string(),
|
|
1024
|
+
mime: z.string(),
|
|
1025
|
+
bytes: z.number(),
|
|
1026
|
+
caption: z.string().optional(),
|
|
1027
|
+
id: z.string(),
|
|
1028
|
+
at: z.string(),
|
|
1029
|
+
actor: z.string()
|
|
679
1030
|
});
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
1031
|
+
/** One project's layout: node id -> "x,y", whole numbers on the layout's grid. */
|
|
1032
|
+
var layoutSchema = z.record(z.string(), z.string().regex(/^-?\d+,-?\d+$/, "a layout position is \"x,y\" in whole numbers"));
|
|
1033
|
+
var itemSchema = z.object({
|
|
1034
|
+
ref: z.string(),
|
|
1035
|
+
area: z.string(),
|
|
1036
|
+
title: z.string(),
|
|
1037
|
+
status: z.string(),
|
|
1038
|
+
sort_path: z.string(),
|
|
1039
|
+
/**
|
|
1040
|
+
* Accepted for old plan files, never written (`PROJ-8`). It was an integer read by nothing, and the
|
|
1041
|
+
* ordered `next` list is what actually answers the question it was there for - a global priority over
|
|
1042
|
+
* 159 items cannot be maintained, and it conflates *important* with *next*. Kept parseable rather than
|
|
1043
|
+
* deleted, for the same reason `sessions:` and `notes:` are: a plan file is committed history, and an
|
|
1044
|
+
* older checkout has to keep loading. The first export retires the key by itself.
|
|
1045
|
+
*/
|
|
1046
|
+
priority: z.number().optional(),
|
|
1047
|
+
parent: z.string().optional(),
|
|
1048
|
+
deps: z.array(z.string()).optional(),
|
|
1049
|
+
/** Planned dates, `YYYY-MM-DD` (`CAL-1`). Not validated here: the importer restores rows rather than
|
|
1050
|
+
* judging them, so a hand-edited date loads and `edit_item` is where it gets corrected. */
|
|
1051
|
+
start: z.string().optional(),
|
|
1052
|
+
due: z.string().optional(),
|
|
1053
|
+
body: z.string().optional(),
|
|
1054
|
+
id: z.string(),
|
|
1055
|
+
created_at: z.string(),
|
|
1056
|
+
updated_at: z.string(),
|
|
1057
|
+
closed_at: z.string().optional(),
|
|
1058
|
+
deleted_at: z.string().optional(),
|
|
1059
|
+
comments: z.array(commentSchema).optional(),
|
|
1060
|
+
/** Accepted for old plan files, never written: see `readComments` (CTX-2). */
|
|
1061
|
+
notes: z.array(commentSchema).optional(),
|
|
1062
|
+
attachments: z.array(attachmentSchema).optional()
|
|
710
1063
|
});
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
1064
|
+
var retiredSessionSchema = z.array(z.unknown());
|
|
1065
|
+
var projectSchema = z.object({
|
|
1066
|
+
key: z.string(),
|
|
1067
|
+
name: z.string(),
|
|
1068
|
+
type: z.string(),
|
|
1069
|
+
status: z.string(),
|
|
1070
|
+
direction: z.string().optional(),
|
|
1071
|
+
next: z.array(z.string()).optional(),
|
|
1072
|
+
id: z.string(),
|
|
1073
|
+
created_at: z.string(),
|
|
1074
|
+
updated_at: z.string(),
|
|
1075
|
+
archived_at: z.string().optional(),
|
|
1076
|
+
context: z.record(z.string(), z.string()).optional(),
|
|
1077
|
+
areas: z.array(areaSchema),
|
|
1078
|
+
items: z.array(itemSchema),
|
|
1079
|
+
sessions: retiredSessionSchema.optional(),
|
|
1080
|
+
comments: z.array(commentSchema).optional(),
|
|
1081
|
+
/** Accepted for old plan files, never written: see `readComments` (CTX-2). */
|
|
1082
|
+
notes: z.array(commentSchema).optional(),
|
|
1083
|
+
attachments: z.array(attachmentSchema).optional(),
|
|
1084
|
+
/**
|
|
1085
|
+
* The graph layout's memory (`VIEW-23.1`): node id -> "x,y", relative to the node's container.
|
|
1086
|
+
*
|
|
1087
|
+
* **Part of the plan as data, not of the plan file.** It travels with a project wherever the plan does - the
|
|
1088
|
+
* database, the cloud import, the library - but a plan *file* never carries it: `splitLayout` moves it to
|
|
1089
|
+
* `.attraverso/layout.yaml` on every write (`VIEW-23.2`), because positions churn on every drag and a new
|
|
1090
|
+
* item, and that churn would bury the edits a reviewer reads the plan file for. Still read here, so a plan
|
|
1091
|
+
* written in the few days the layout lived inline loads, and the next save moves it out.
|
|
1092
|
+
*/
|
|
1093
|
+
layout: layoutSchema.optional()
|
|
740
1094
|
});
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
1095
|
+
/**
|
|
1096
|
+
* Comments under either key, because they were `notes:` until 2026-09-01 (`CTX-2`).
|
|
1097
|
+
*
|
|
1098
|
+
* **Both are accepted indefinitely, and only `comments:` is written.** A plan file is committed history: a
|
|
1099
|
+
* checkout of an older branch, or a colleague's pull, has to keep loading, and there is no migration step to
|
|
1100
|
+
* hang a conversion off - the YAML *is* the database. The first export after a load quietly retires the old
|
|
1101
|
+
* key, so a file converts itself the first time anything writes to it.
|
|
1102
|
+
*
|
|
1103
|
+
* Both present would mean a hand-merged file or a half-finished edit. Concatenating is the safe reading:
|
|
1104
|
+
* ids are preserved on import, so a row appearing under both keys would collide on the primary key and fail
|
|
1105
|
+
* loudly rather than silently keeping one copy.
|
|
1106
|
+
*/
|
|
1107
|
+
var readComments = (owner) => [...owner.comments ?? [], ...owner.notes ?? []];
|
|
1108
|
+
var storeSchema = z.object({ projects: z.array(projectSchema) });
|
|
1109
|
+
/** Drop a null/empty optional so it is omitted from the YAML entirely (undefined is skipped by stringify). */
|
|
1110
|
+
var opt = (value) => value === null || value === void 0 ? void 0 : value;
|
|
744
1111
|
async function exportStore(db, ownerId) {
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
1112
|
+
const projectRows = await db.select().from(projects).where(eq(projects.ownerId, ownerId)).orderBy(asc(projects.key));
|
|
1113
|
+
const out = { projects: [] };
|
|
1114
|
+
for (const p of projectRows) {
|
|
1115
|
+
const areaRows = await db.select().from(areas).where(eq(areas.projectId, p.id)).orderBy(asc(areas.key));
|
|
1116
|
+
const itemRows = await db.select().from(items).where(eq(items.projectId, p.id)).orderBy(asc(items.areaKey), asc(items.sortPath));
|
|
1117
|
+
const idToRef = new Map(itemRows.map((i) => [i.id, i.ref]));
|
|
1118
|
+
const depRows = await db.select({
|
|
1119
|
+
itemId: dependencies.itemId,
|
|
1120
|
+
dependsOnId: dependencies.dependsOnId
|
|
1121
|
+
}).from(dependencies).innerJoin(items, eq(dependencies.itemId, items.id)).where(eq(items.projectId, p.id));
|
|
1122
|
+
const scopedDepRows = await db.select({
|
|
1123
|
+
itemId: scopedDependencies.itemId,
|
|
1124
|
+
project: scopedDependencies.targetProject,
|
|
1125
|
+
ref: scopedDependencies.targetRef
|
|
1126
|
+
}).from(scopedDependencies).innerJoin(items, eq(scopedDependencies.itemId, items.id)).where(eq(items.projectId, p.id));
|
|
1127
|
+
const depsByRef = /* @__PURE__ */ new Map();
|
|
1128
|
+
for (const d of depRows) {
|
|
1129
|
+
const ref = idToRef.get(d.itemId);
|
|
1130
|
+
const dependsOn = idToRef.get(d.dependsOnId);
|
|
1131
|
+
if (ref === void 0 || dependsOn === void 0) continue;
|
|
1132
|
+
(depsByRef.get(ref) ?? depsByRef.set(ref, []).get(ref)).push(dependsOn);
|
|
1133
|
+
}
|
|
1134
|
+
for (const d of scopedDepRows) {
|
|
1135
|
+
const ref = idToRef.get(d.itemId);
|
|
1136
|
+
if (ref === void 0) continue;
|
|
1137
|
+
(depsByRef.get(ref) ?? depsByRef.set(ref, []).get(ref)).push(`${d.project}:${d.ref}`);
|
|
1138
|
+
}
|
|
1139
|
+
const nextRows = await db.select({ ref: items.ref }).from(projectNext).innerJoin(items, eq(projectNext.itemId, items.id)).where(eq(projectNext.projectId, p.id)).orderBy(asc(projectNext.position));
|
|
1140
|
+
const sectionRows = await db.select().from(contextSections).where(eq(contextSections.projectId, p.id)).orderBy(asc(contextSections.sortOrder), asc(contextSections.heading));
|
|
1141
|
+
const context = {};
|
|
1142
|
+
for (const s of sectionRows) context[s.heading] = s.content;
|
|
1143
|
+
const commentRows = await db.select().from(comments).where(eq(comments.projectId, p.id)).orderBy(asc(comments.createdAt), asc(comments.body));
|
|
1144
|
+
const commentsByItem = /* @__PURE__ */ new Map();
|
|
1145
|
+
const projectComments = [];
|
|
1146
|
+
for (const n of commentRows) if (n.itemId === null) projectComments.push(n);
|
|
1147
|
+
else (commentsByItem.get(n.itemId) ?? commentsByItem.set(n.itemId, []).get(n.itemId)).push(n);
|
|
1148
|
+
const attachmentRows = await db.select().from(attachments).where(eq(attachments.projectId, p.id)).orderBy(asc(attachments.createdAt), asc(attachments.hash));
|
|
1149
|
+
const attachmentsByItem = /* @__PURE__ */ new Map();
|
|
1150
|
+
const projectAttachments = [];
|
|
1151
|
+
for (const a of attachmentRows) if (a.itemId === null) projectAttachments.push(a);
|
|
1152
|
+
else (attachmentsByItem.get(a.itemId) ?? attachmentsByItem.set(a.itemId, []).get(a.itemId)).push(a);
|
|
1153
|
+
const fmtAttachments = (rows) => rows.length > 0 ? rows.map((a) => ({
|
|
1154
|
+
hash: a.hash,
|
|
1155
|
+
mime: a.mime,
|
|
1156
|
+
bytes: a.bytes,
|
|
1157
|
+
caption: opt(a.caption),
|
|
1158
|
+
id: a.id,
|
|
1159
|
+
at: a.createdAt,
|
|
1160
|
+
actor: a.actor
|
|
1161
|
+
})) : void 0;
|
|
1162
|
+
const layoutRows = await db.select().from(layoutPositions).where(eq(layoutPositions.projectId, p.id)).orderBy(asc(layoutPositions.node));
|
|
1163
|
+
const fmtComments = (rows) => rows.length > 0 ? rows.map((n) => ({
|
|
1164
|
+
body: n.body,
|
|
1165
|
+
audience: n.audience,
|
|
1166
|
+
id: n.id,
|
|
1167
|
+
at: n.createdAt,
|
|
1168
|
+
actor: n.actor
|
|
1169
|
+
})) : void 0;
|
|
1170
|
+
out.projects.push({
|
|
1171
|
+
key: p.key,
|
|
1172
|
+
name: p.name,
|
|
1173
|
+
type: p.type,
|
|
1174
|
+
status: p.status,
|
|
1175
|
+
direction: opt(p.direction),
|
|
1176
|
+
next: nextRows.length > 0 ? nextRows.map((row) => row.ref) : void 0,
|
|
1177
|
+
id: p.id,
|
|
1178
|
+
created_at: p.createdAt,
|
|
1179
|
+
updated_at: p.updatedAt,
|
|
1180
|
+
archived_at: opt(p.archivedAt),
|
|
1181
|
+
context: sectionRows.length > 0 ? context : void 0,
|
|
1182
|
+
comments: fmtComments(projectComments),
|
|
1183
|
+
attachments: fmtAttachments(projectAttachments),
|
|
1184
|
+
areas: areaRows.map((a) => ({
|
|
1185
|
+
key: a.key,
|
|
1186
|
+
name: a.name,
|
|
1187
|
+
description: opt(a.description),
|
|
1188
|
+
colour: opt(a.colour),
|
|
1189
|
+
sort_order: a.sortOrder,
|
|
1190
|
+
id: a.id,
|
|
1191
|
+
created_at: a.createdAt
|
|
1192
|
+
})),
|
|
1193
|
+
items: itemRows.map((i) => {
|
|
1194
|
+
const deps = depsByRef.get(i.ref);
|
|
1195
|
+
return {
|
|
1196
|
+
ref: i.ref,
|
|
1197
|
+
area: i.areaKey,
|
|
1198
|
+
title: i.title,
|
|
1199
|
+
status: i.status,
|
|
1200
|
+
sort_path: i.sortPath,
|
|
1201
|
+
parent: i.parentId ? opt(idToRef.get(i.parentId)) : void 0,
|
|
1202
|
+
deps: deps && deps.length > 0 ? [...deps].sort() : void 0,
|
|
1203
|
+
start: opt(i.startOn),
|
|
1204
|
+
due: opt(i.dueOn),
|
|
1205
|
+
body: opt(i.body),
|
|
1206
|
+
id: i.id,
|
|
1207
|
+
created_at: i.createdAt,
|
|
1208
|
+
updated_at: i.updatedAt,
|
|
1209
|
+
closed_at: opt(i.closedAt),
|
|
1210
|
+
deleted_at: opt(i.deletedAt),
|
|
1211
|
+
comments: fmtComments(commentsByItem.get(i.id) ?? []),
|
|
1212
|
+
attachments: fmtAttachments(attachmentsByItem.get(i.id) ?? [])
|
|
1213
|
+
};
|
|
1214
|
+
}),
|
|
1215
|
+
layout: layoutRows.length > 0 ? Object.fromEntries(layoutRows.map((row) => [row.node, `${row.x},${row.y}`])) : void 0
|
|
1216
|
+
});
|
|
1217
|
+
}
|
|
1218
|
+
return out;
|
|
834
1219
|
}
|
|
1220
|
+
/** Rebuild a fresh database from a store. Not through the domain layer: this is a restore of exact rows
|
|
1221
|
+
* (ids, timestamps, no new events), so identity and history survive. Expects an empty database. */
|
|
835
1222
|
async function importStore(db, store) {
|
|
836
|
-
|
|
1223
|
+
await db.transaction((tx) => insertStore(tx, store));
|
|
837
1224
|
}
|
|
838
1225
|
async function insertStore(tx, store, owner) {
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
1226
|
+
const ownerId = owner ?? (await ensureUserIn(tx, LOCAL_IDENTITY)).id;
|
|
1227
|
+
for (const p of store.projects) {
|
|
1228
|
+
await tx.insert(projects).values({
|
|
1229
|
+
id: p.id,
|
|
1230
|
+
ownerId,
|
|
1231
|
+
key: p.key,
|
|
1232
|
+
name: p.name,
|
|
1233
|
+
type: p.type,
|
|
1234
|
+
direction: p.direction ?? null,
|
|
1235
|
+
status: p.status,
|
|
1236
|
+
createdAt: p.created_at,
|
|
1237
|
+
updatedAt: p.updated_at,
|
|
1238
|
+
archivedAt: p.archived_at ?? null
|
|
1239
|
+
});
|
|
1240
|
+
if (p.areas.length > 0) await tx.insert(areas).values(p.areas.map((a) => ({
|
|
1241
|
+
id: a.id,
|
|
1242
|
+
projectId: p.id,
|
|
1243
|
+
key: a.key,
|
|
1244
|
+
name: a.name,
|
|
1245
|
+
description: a.description ?? null,
|
|
1246
|
+
colour: a.colour ?? null,
|
|
1247
|
+
sortOrder: a.sort_order,
|
|
1248
|
+
createdAt: a.created_at
|
|
1249
|
+
})));
|
|
1250
|
+
const refToId = new Map(p.items.map((i) => [i.ref, i.id]));
|
|
1251
|
+
const inInsertOrder = [...p.items].sort((a, b) => a.sort_path < b.sort_path ? -1 : a.sort_path > b.sort_path ? 1 : 0);
|
|
1252
|
+
for (const i of inInsertOrder) await tx.insert(items).values({
|
|
1253
|
+
id: i.id,
|
|
1254
|
+
projectId: p.id,
|
|
1255
|
+
ref: i.ref,
|
|
1256
|
+
areaKey: i.area,
|
|
1257
|
+
sortPath: i.sort_path,
|
|
1258
|
+
parentId: i.parent ? refToId.get(i.parent) ?? null : null,
|
|
1259
|
+
title: i.title,
|
|
1260
|
+
body: i.body ?? null,
|
|
1261
|
+
status: i.status,
|
|
1262
|
+
createdAt: i.created_at,
|
|
1263
|
+
updatedAt: i.updated_at,
|
|
1264
|
+
closedAt: i.closed_at ?? null,
|
|
1265
|
+
deletedAt: i.deleted_at ?? null,
|
|
1266
|
+
startOn: i.start ?? null,
|
|
1267
|
+
dueOn: i.due ?? null
|
|
1268
|
+
});
|
|
1269
|
+
const scopedInFile = /* @__PURE__ */ new Map();
|
|
1270
|
+
const depValues = p.items.flatMap((i) => (i.deps ?? []).flatMap((depRef) => {
|
|
1271
|
+
const itemId = refToId.get(i.ref);
|
|
1272
|
+
if (itemId === void 0) return [];
|
|
1273
|
+
const split = splitScope(depRef);
|
|
1274
|
+
if (split !== null && split.project !== p.key) {
|
|
1275
|
+
scopedInFile.set(itemId, [...scopedInFile.get(itemId) ?? [], split]);
|
|
1276
|
+
return [];
|
|
1277
|
+
}
|
|
1278
|
+
const dependsOnId = refToId.get(split?.ref ?? depRef);
|
|
1279
|
+
if (dependsOnId === void 0) return [];
|
|
1280
|
+
return [{
|
|
1281
|
+
itemId,
|
|
1282
|
+
dependsOnId,
|
|
1283
|
+
createdAt: i.created_at
|
|
1284
|
+
}];
|
|
1285
|
+
}));
|
|
1286
|
+
if (depValues.length > 0) await tx.insert(dependencies).values(depValues);
|
|
1287
|
+
const scopedValues = [...scopedInFile].flatMap(([itemId, targets]) => targets.map((target) => ({
|
|
1288
|
+
itemId,
|
|
1289
|
+
targetProject: target.project,
|
|
1290
|
+
targetRef: target.ref,
|
|
1291
|
+
createdAt: p.created_at
|
|
1292
|
+
})));
|
|
1293
|
+
if (scopedValues.length > 0) await tx.insert(scopedDependencies).values(scopedValues);
|
|
1294
|
+
const nextValues = (p.next ?? []).flatMap((ref) => {
|
|
1295
|
+
const itemId = refToId.get(ref);
|
|
1296
|
+
return itemId === void 0 ? [] : [itemId];
|
|
1297
|
+
});
|
|
1298
|
+
if (nextValues.length > 0) await tx.insert(projectNext).values(nextValues.map((itemId, position) => ({
|
|
1299
|
+
projectId: p.id,
|
|
1300
|
+
itemId,
|
|
1301
|
+
position
|
|
1302
|
+
})));
|
|
1303
|
+
const layoutValues = Object.entries(p.layout ?? {}).map(([node, at]) => {
|
|
1304
|
+
const [x, y] = at.split(",").map(Number);
|
|
1305
|
+
return {
|
|
1306
|
+
projectId: p.id,
|
|
1307
|
+
node,
|
|
1308
|
+
x,
|
|
1309
|
+
y
|
|
1310
|
+
};
|
|
1311
|
+
});
|
|
1312
|
+
if (layoutValues.length > 0) await tx.insert(layoutPositions).values(layoutValues);
|
|
1313
|
+
const contextEntries = Object.entries(p.context ?? {});
|
|
1314
|
+
if (contextEntries.length > 0) await tx.insert(contextSections).values(contextEntries.map(([heading, content], index) => ({
|
|
1315
|
+
projectId: p.id,
|
|
1316
|
+
heading,
|
|
1317
|
+
content,
|
|
1318
|
+
sortOrder: index
|
|
1319
|
+
})));
|
|
1320
|
+
const commentValues = [...readComments(p).map((c) => ({
|
|
1321
|
+
comment: c,
|
|
1322
|
+
itemId: null
|
|
1323
|
+
})), ...p.items.flatMap((i) => readComments(i).map((c) => ({
|
|
1324
|
+
comment: c,
|
|
1325
|
+
itemId: refToId.get(i.ref) ?? null
|
|
1326
|
+
})))];
|
|
1327
|
+
if (commentValues.length > 0) await tx.insert(comments).values(commentValues.map(({ comment, itemId }) => ({
|
|
1328
|
+
id: comment.id,
|
|
1329
|
+
projectId: p.id,
|
|
1330
|
+
itemId,
|
|
1331
|
+
body: comment.body,
|
|
1332
|
+
audience: comment.audience,
|
|
1333
|
+
actor: comment.actor,
|
|
1334
|
+
createdAt: comment.at
|
|
1335
|
+
})));
|
|
1336
|
+
const attachmentValues = [...(p.attachments ?? []).map((a) => ({
|
|
1337
|
+
attachment: a,
|
|
1338
|
+
itemId: null
|
|
1339
|
+
})), ...p.items.flatMap((i) => (i.attachments ?? []).map((a) => ({
|
|
1340
|
+
attachment: a,
|
|
1341
|
+
itemId: refToId.get(i.ref) ?? null
|
|
1342
|
+
})))];
|
|
1343
|
+
if (attachmentValues.length > 0) await tx.insert(attachments).values(attachmentValues.map(({ attachment: a, itemId }) => ({
|
|
1344
|
+
id: a.id,
|
|
1345
|
+
projectId: p.id,
|
|
1346
|
+
itemId,
|
|
1347
|
+
hash: a.hash,
|
|
1348
|
+
mime: a.mime,
|
|
1349
|
+
bytes: a.bytes,
|
|
1350
|
+
caption: a.caption ?? null,
|
|
1351
|
+
actor: a.actor,
|
|
1352
|
+
createdAt: a.at
|
|
1353
|
+
})));
|
|
1354
|
+
}
|
|
958
1355
|
}
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
1356
|
+
/** The plan as text, in the one layout every writer shares (`IMP-19`, see `format.ts`). */
|
|
1357
|
+
var stringifyStore = (store) => stringify(store, YAML_FORMAT);
|
|
1358
|
+
z.record(z.string(), layoutSchema);
|
|
1359
|
+
function parseStore(text) {
|
|
1360
|
+
return storeSchema.parse(parse(text));
|
|
962
1361
|
}
|
|
963
|
-
|
|
1362
|
+
// src/domain/context.ts
|
|
1363
|
+
/**
|
|
1364
|
+
* Context sections (CTX): the project's living narrative as named prose blocks - "Goals", "Assumptions",
|
|
1365
|
+
* "Open questions". An open set of headings, set by heading (so writing one twice revises it in place), with
|
|
1366
|
+
* every change captured in the event log rather than a supersede column. This is the durable context a
|
|
1367
|
+
* returning session reads, distinct from the one-line `projects.direction` and from the session journal.
|
|
1368
|
+
*/
|
|
1369
|
+
/** The reserved heading for a project's protocol (CTX-9): its session-operating instructions as data, which
|
|
1370
|
+
* `get_project` surfaces first and a session applies before acting. A normal context section, distinguished
|
|
1371
|
+
* only by this heading and by being ordered to the front of the pack. */
|
|
1372
|
+
var PROTOCOL_HEADING = "protocol";
|
|
1373
|
+
/** New sections append after the existing ones, so heading order reflects the order they were introduced. */
|
|
964
1374
|
async function nextSortOrder(tx, projectId) {
|
|
965
|
-
|
|
966
|
-
await tx.select({ max: sql`max(${contextSections.sortOrder})` }).from(contextSections).where(eq(contextSections.projectId, projectId))
|
|
967
|
-
);
|
|
968
|
-
return (row?.max ?? -1) + 1;
|
|
1375
|
+
return (maybeOne(await tx.select({ max: sql`max(${contextSections.sortOrder})` }).from(contextSections).where(eq(contextSections.projectId, projectId)))?.max ?? -1) + 1;
|
|
969
1376
|
}
|
|
1377
|
+
/**
|
|
1378
|
+
* The `sortOrder` that puts a section immediately after `heading` (or first, when `heading` is null).
|
|
1379
|
+
*
|
|
1380
|
+
* Positions are integers and sections between them are not renumbered, so this returns a value *between* the
|
|
1381
|
+
* anchor and whatever follows it. Fractional, deliberately: renumbering the tail on every move is the version
|
|
1382
|
+
* that turns a reorder into a write over every section, and gets it wrong under a concurrent edit. The column
|
|
1383
|
+
* is an integer today, so this scales the whole project's positions when there is no gap to land in - rare,
|
|
1384
|
+
* bounded, and confined to this function.
|
|
1385
|
+
*
|
|
1386
|
+
* Callers pass a heading because that is the operation people actually have ("put Licensing after Thesis"). An
|
|
1387
|
+
* agent handed raw integers picks colliding ones, and recovering from a collision means renumbering, which is
|
|
1388
|
+
* a worse problem than the one being solved.
|
|
1389
|
+
*/
|
|
970
1390
|
async function orderAfter(tx, projectId, after, movingHeading) {
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
1391
|
+
const ordered = (await tx.select({
|
|
1392
|
+
heading: contextSections.heading,
|
|
1393
|
+
sortOrder: contextSections.sortOrder
|
|
1394
|
+
}).from(contextSections).where(eq(contextSections.projectId, projectId)).orderBy(asc(contextSections.sortOrder), asc(contextSections.heading))).filter((s) => s.heading !== movingHeading);
|
|
1395
|
+
if (after === null) return (ordered[0]?.sortOrder ?? 1) - 1;
|
|
1396
|
+
const index = ordered.findIndex((s) => s.heading === after);
|
|
1397
|
+
if (index === -1) throw new Error(`no context section "${after}" to place this after`);
|
|
1398
|
+
const anchor = ordered[index].sortOrder;
|
|
1399
|
+
const next = ordered[index + 1]?.sortOrder;
|
|
1400
|
+
if (next === void 0) return anchor + 1;
|
|
1401
|
+
if (next - anchor > 1) return anchor + Math.floor((next - anchor) / 2);
|
|
1402
|
+
for (const [position, section] of ordered.entries()) await tx.update(contextSections).set({ sortOrder: position * 16 }).where(and(eq(contextSections.projectId, projectId), eq(contextSections.heading, section.heading)));
|
|
1403
|
+
return index * 16 + 8;
|
|
983
1404
|
}
|
|
984
1405
|
async function setSection(db, input, actor) {
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1406
|
+
return mutate(db, actor, async (tx) => {
|
|
1407
|
+
const existing = maybeOne(await tx.select().from(contextSections).where(and(eq(contextSections.projectId, input.projectId), eq(contextSections.heading, input.heading))));
|
|
1408
|
+
const now = timestamp();
|
|
1409
|
+
const order = input.sortOrder ?? (input.after !== void 0 ? await orderAfter(tx, input.projectId, input.after, input.heading) : existing?.sortOrder ?? await nextSortOrder(tx, input.projectId));
|
|
1410
|
+
const after = one(await tx.insert(contextSections).values({
|
|
1411
|
+
projectId: input.projectId,
|
|
1412
|
+
heading: input.heading,
|
|
1413
|
+
content: input.content,
|
|
1414
|
+
sortOrder: order,
|
|
1415
|
+
createdAt: now,
|
|
1416
|
+
updatedAt: now
|
|
1417
|
+
}).onConflictDoUpdate({
|
|
1418
|
+
target: [contextSections.projectId, contextSections.heading],
|
|
1419
|
+
set: {
|
|
1420
|
+
content: input.content,
|
|
1421
|
+
sortOrder: order,
|
|
1422
|
+
updatedAt: now
|
|
1423
|
+
}
|
|
1424
|
+
}).returning());
|
|
1425
|
+
return {
|
|
1426
|
+
result: after,
|
|
1427
|
+
event: {
|
|
1428
|
+
projectId: input.projectId,
|
|
1429
|
+
entityType: "context_section",
|
|
1430
|
+
entityId: after.id,
|
|
1431
|
+
kind: existing ? "updated" : "created",
|
|
1432
|
+
before: existing ?? void 0,
|
|
1433
|
+
after
|
|
1434
|
+
}
|
|
1435
|
+
};
|
|
1436
|
+
});
|
|
1009
1437
|
}
|
|
1438
|
+
/** Read one section by its exact heading, so a caller can revise it from its current content. */
|
|
1010
1439
|
async function getSection(db, projectId, heading) {
|
|
1011
|
-
|
|
1012
|
-
await db.select().from(contextSections).where(and(eq(contextSections.projectId, projectId), eq(contextSections.heading, heading)))
|
|
1013
|
-
);
|
|
1440
|
+
return maybeOne(await db.select().from(contextSections).where(and(eq(contextSections.projectId, projectId), eq(contextSections.heading, heading))));
|
|
1014
1441
|
}
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1442
|
+
// src/domain/projects.ts
|
|
1443
|
+
/**
|
|
1444
|
+
* Projects (PROJ-1): identity and the running direction. One database holds all of a person's projects, so
|
|
1445
|
+
* "what am I working on across everything?" is a query. Every mutation writes an event in the same
|
|
1446
|
+
* transaction (DATA-4).
|
|
1447
|
+
*
|
|
1448
|
+
* `type` is an open string ("software" | "learning" | ...), validated nowhere here on purpose: a new project
|
|
1449
|
+
* type must never be a migration or a code change to this file.
|
|
1450
|
+
*/
|
|
1451
|
+
/**
|
|
1452
|
+
* The only place an `OwnedProjectId` is minted (`DATA-16`), and it sits here because every caller of it is a
|
|
1453
|
+
* line or two below an ownership check. A reviewer asking "is this scoping sound?" has one function to read.
|
|
1454
|
+
*/
|
|
1455
|
+
var owned = (project) => project;
|
|
1456
|
+
/**
|
|
1457
|
+
* The default `protocol` a new project starts with (CTX-9): the session-operating instructions as data,
|
|
1458
|
+
* surfaced first by `get_project` and applied before acting. It is an ordinary revisable section, so a
|
|
1459
|
+
* project elaborates or rewrites it over time (a learning project's protocol is its session methodology, not
|
|
1460
|
+
* this tool-hygiene note).
|
|
1461
|
+
*
|
|
1462
|
+
* **Every word here is re-read at the top of every session, forever**, so this text is kept to what an agent
|
|
1463
|
+
* cannot get anywhere else. Two things are therefore deliberately absent, both of which used to be here:
|
|
1464
|
+
*
|
|
1465
|
+
* - **A tool inventory.** MCP already hands the model every tool name, description and input schema. Listing
|
|
1466
|
+
* them again, and describing the entity shapes those schemas already define, spent context restating what
|
|
1467
|
+
* the client had already supplied.
|
|
1468
|
+
* - **Anything assuming a software repo.** It described itself as a project-scoped `CLAUDE.md`, explained
|
|
1469
|
+
* this codebase's own schema rationale ("no type column, since a schedule is an optional attachment"), and
|
|
1470
|
+
* closed with a warning about hand-editing the YAML while a server runs. All meaningless to someone
|
|
1471
|
+
* learning a language from a home-dir store, who will never open that file - and it is the *default*, so it
|
|
1472
|
+
* was shipping this repo's assumptions into every project of any kind.
|
|
1473
|
+
*
|
|
1474
|
+
* What survives is what the model cannot infer: that this section is the thing to read first and to revise,
|
|
1475
|
+
* a placeholder for the project's own session shape, and the write-as-you-go instruction - which is a
|
|
1476
|
+
* behavioural default, not a fact about the API, and is the one thing that stops a session leaving no record.
|
|
1477
|
+
*
|
|
1478
|
+
* The closing "not filled in yet" block is the onboarding interview, and it is written to delete itself once
|
|
1479
|
+
* used. That is deliberate: setup guidance is relevant exactly once, but the protocol is re-read at the top of
|
|
1480
|
+
* every session, so leaving it in place would mean permanently spending context on instructions that no longer
|
|
1481
|
+
* apply. It lives here rather than only in the `create_project` tool description so that a project seeded by an
|
|
1482
|
+
* import or a script still knows it is unfinished and what to ask.
|
|
1483
|
+
*
|
|
1484
|
+
* There is deliberately no per-type variant of this text. Branching the default on "software" vs "learning"
|
|
1485
|
+
* would put a domain noun in the domain layer, which is the one thing the model forbids; the interview adapts
|
|
1486
|
+
* because an agent conducts it, not because a switch statement does.
|
|
1487
|
+
*/
|
|
1488
|
+
var DEFAULT_PROTOCOL = {
|
|
1489
|
+
heading: PROTOCOL_HEADING,
|
|
1490
|
+
content: `This is the project's protocol: the first thing a session reads, and where to keep how this project should be run. Apply it before acting, and revise it with set_context as you learn - the next session inherits whatever is here, and nothing else carries over. Markdown, as are item bodies and context sections.
|
|
1019
1491
|
|
|
1020
1492
|
**Overview.** What this project is and where it is going - fill this in.
|
|
1021
1493
|
|
|
@@ -1032,89 +1504,163 @@ const DEFAULT_PROTOCOL = {
|
|
|
1032
1504
|
Ask a couple at a time and infer what you reasonably can rather than interrogating; a thin protocol that gets used beats a thorough one that stalls the first session.`
|
|
1033
1505
|
};
|
|
1034
1506
|
async function createProject(db, input, actor) {
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1507
|
+
return mutate(db, actor, async (tx) => {
|
|
1508
|
+
if ((await tx.select({ id: projects.id }).from(projects).where(and(eq(projects.ownerId, input.ownerId), eq(projects.key, input.key)))).length > 0) throw new Error(`a project with key "${input.key}" already exists`);
|
|
1509
|
+
const project = one(await tx.insert(projects).values({
|
|
1510
|
+
key: input.key,
|
|
1511
|
+
ownerId: input.ownerId,
|
|
1512
|
+
name: input.name,
|
|
1513
|
+
type: input.type,
|
|
1514
|
+
direction: input.direction ?? null,
|
|
1515
|
+
status: "active"
|
|
1516
|
+
}).returning());
|
|
1517
|
+
const result = owned(project);
|
|
1518
|
+
return {
|
|
1519
|
+
result,
|
|
1520
|
+
event: {
|
|
1521
|
+
projectId: result.id,
|
|
1522
|
+
entityType: "project",
|
|
1523
|
+
entityId: result.id,
|
|
1524
|
+
kind: "created",
|
|
1525
|
+
after: project
|
|
1526
|
+
}
|
|
1527
|
+
};
|
|
1528
|
+
});
|
|
1051
1529
|
}
|
|
1530
|
+
/**
|
|
1531
|
+
* Create a project and seed its default `protocol` section. This is the path a user or agent takes when
|
|
1532
|
+
* creating a project through the tool, so a fresh project is never blank - it opens already knowing how to run
|
|
1533
|
+
* a session and to edit itself through the tools. Kept separate from `createProject` (a pure single-mutation
|
|
1534
|
+
* primitive) and composed from two `mutate` calls, per the one-event-per-mutation rule; the primitive stays
|
|
1535
|
+
* available for tests and any path that wants a project with no defaults.
|
|
1536
|
+
*/
|
|
1052
1537
|
async function createProjectWithDefaults(db, input, actor) {
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1538
|
+
const project = await createProject(db, input, actor);
|
|
1539
|
+
await setSection(db, {
|
|
1540
|
+
projectId: project.id,
|
|
1541
|
+
heading: DEFAULT_PROTOCOL.heading,
|
|
1542
|
+
content: DEFAULT_PROTOCOL.content
|
|
1543
|
+
}, actor);
|
|
1544
|
+
return project;
|
|
1056
1545
|
}
|
|
1546
|
+
/**
|
|
1547
|
+
* The caller's projects, and only theirs (OPS-4).
|
|
1548
|
+
*
|
|
1549
|
+
* `ownerId` is required rather than optional-meaning-all: an unowned project matches no owner and so is
|
|
1550
|
+
* visible to nobody, which is the direction this has to fail in while the deployed database is being
|
|
1551
|
+
* backfilled. An optional parameter would make "show me everything" the *default* and one forgotten argument
|
|
1552
|
+
* away, which is precisely the leak.
|
|
1553
|
+
*/
|
|
1057
1554
|
async function listProjects(db, ownerId) {
|
|
1058
|
-
|
|
1555
|
+
return (await db.select().from(projects).where(eq(projects.ownerId, ownerId)).orderBy(asc(projects.createdAt))).map(owned);
|
|
1059
1556
|
}
|
|
1557
|
+
/**
|
|
1558
|
+
* Look a project up by the handle its owner knows it by. Keys are unique per owner, not globally, so the
|
|
1559
|
+
* owner is half the identifier rather than a filter applied afterwards - and a key belonging to someone else
|
|
1560
|
+
* is indistinguishable here from one that does not exist, which is the answer a caller should get.
|
|
1561
|
+
*/
|
|
1060
1562
|
async function getProjectByKey(db, ownerId, key) {
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
);
|
|
1064
|
-
return project === null ? null : owned(project);
|
|
1563
|
+
const project = maybeOne(await db.select().from(projects).where(and(eq(projects.ownerId, ownerId), eq(projects.key, key))));
|
|
1564
|
+
return project === null ? null : owned(project);
|
|
1065
1565
|
}
|
|
1566
|
+
// src/domain/dependencies.ts
|
|
1567
|
+
/**
|
|
1568
|
+
* The dependency graph (MCP-16, MCP-17): the edges between items, and the two integrity rules that make
|
|
1569
|
+
* letting an agent write them safe.
|
|
1570
|
+
*
|
|
1571
|
+
* Until this module existed, edges could only arrive through the YAML importer - which meant they came from a
|
|
1572
|
+
* markdown file a human had already kept acyclic. Once a tool can add one, the first mistaken pair makes the
|
|
1573
|
+
* graph unrenderable, and the failure surfaces in the viewer rather than at the call that caused it. So both
|
|
1574
|
+
* checks live on the write path, and both name what was wrong rather than only refusing.
|
|
1575
|
+
*
|
|
1576
|
+
* The edge direction is `item depends on dependsOn`: the dependency must be done first.
|
|
1577
|
+
*/
|
|
1578
|
+
/**
|
|
1579
|
+
* The refs an item depends on, ordered stably (area then sort_path) so a reply and an export never disagree.
|
|
1580
|
+
*
|
|
1581
|
+
* Scoped refs (`PROJ-11`) come last, ordered by project then ref. They cannot be interleaved by sort path,
|
|
1582
|
+
* because the point of one is that the item it names may not be loaded to have a sort path - and a listing
|
|
1583
|
+
* whose order depended on which other store file happened to be open would not be deterministic.
|
|
1584
|
+
*/
|
|
1066
1585
|
async function dependencyRefs(tx, itemId) {
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1586
|
+
const rows = await tx.select({ ref: items.ref }).from(dependencies).innerJoin(items, eq(dependencies.dependsOnId, items.id)).where(eq(dependencies.itemId, itemId)).orderBy(asc(items.areaKey), asc(items.sortPath));
|
|
1587
|
+
const scoped = await tx.select({
|
|
1588
|
+
project: scopedDependencies.targetProject,
|
|
1589
|
+
ref: scopedDependencies.targetRef
|
|
1590
|
+
}).from(scopedDependencies).where(eq(scopedDependencies.itemId, itemId)).orderBy(asc(scopedDependencies.targetProject), asc(scopedDependencies.targetRef));
|
|
1591
|
+
return [...rows.map((row) => row.ref), ...scoped.map(scopedRef)];
|
|
1070
1592
|
}
|
|
1071
|
-
|
|
1593
|
+
/** A scoped dependency as it is written and read: `apm:DIST-1`. */
|
|
1594
|
+
var scopedRef = (target) => `${target.project}:${target.ref}`;
|
|
1595
|
+
/**
|
|
1596
|
+
* Replace an item's whole dependency set.
|
|
1597
|
+
*
|
|
1598
|
+
* Declarative rather than add/remove, deliberately: an agent that can only append cannot correct its own
|
|
1599
|
+
* mistake, and replacing is how the same edit would be written by hand in the YAML. Passing `[]` clears them.
|
|
1600
|
+
*/
|
|
1072
1601
|
async function setDependencies(tx, item, depRefs) {
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1602
|
+
const asked = [...new Set(depRefs)];
|
|
1603
|
+
const self = (await tx.select({
|
|
1604
|
+
key: projects.key,
|
|
1605
|
+
ownerId: projects.ownerId
|
|
1606
|
+
}).from(projects).where(eq(projects.id, item.projectId)))[0];
|
|
1607
|
+
const scoped = [];
|
|
1608
|
+
const local = [];
|
|
1609
|
+
for (const ref of asked) {
|
|
1610
|
+
const split = splitScope(ref);
|
|
1611
|
+
if (split === null) local.push(ref);
|
|
1612
|
+
else if (split.project === self?.key) local.push(split.ref);
|
|
1613
|
+
else scoped.push(split);
|
|
1614
|
+
}
|
|
1615
|
+
const wanted = [...new Set(local)];
|
|
1616
|
+
const targets = wanted.length === 0 ? [] : await tx.select({
|
|
1617
|
+
id: items.id,
|
|
1618
|
+
ref: items.ref
|
|
1619
|
+
}).from(items).where(and(eq(items.projectId, item.projectId), inArray(items.ref, wanted)));
|
|
1620
|
+
const found = new Map(targets.map((t) => [t.ref, t.id]));
|
|
1621
|
+
const missing = wanted.filter((ref) => !found.has(ref));
|
|
1622
|
+
if (missing.length > 0) throw new Error(`no ticket ${missing.map((r) => `"${r}"`).join(", ")} in this project`);
|
|
1623
|
+
for (const ref of wanted) {
|
|
1624
|
+
if (ref === item.ref) throw new Error(`${item.ref} cannot depend on itself`);
|
|
1625
|
+
if (isNestedUnder(ref, item.ref) || isNestedUnder(item.ref, ref)) throw new Error(`${item.ref} and ${ref} are already related by nesting, so a dependency between them would never be drawn`);
|
|
1626
|
+
}
|
|
1627
|
+
for (const target of scoped) {
|
|
1628
|
+
if (self === void 0) break;
|
|
1629
|
+
const other = (await tx.select({ id: projects.id }).from(projects).where(and(eq(projects.ownerId, self.ownerId), eq(projects.key, target.project))))[0];
|
|
1630
|
+
if (other === void 0) continue;
|
|
1631
|
+
if ((await tx.select({ id: items.id }).from(items).where(and(eq(items.projectId, other.id), eq(items.ref, target.ref))))[0] === void 0) throw new Error(`no item "${target.ref}" in project "${target.project}", which is loaded - so the ref is wrong, not merely unresolvable`);
|
|
1632
|
+
}
|
|
1633
|
+
const now = timestamp();
|
|
1634
|
+
await tx.delete(dependencies).where(eq(dependencies.itemId, item.id));
|
|
1635
|
+
if (wanted.length > 0) await tx.insert(dependencies).values(wanted.map((ref) => ({
|
|
1636
|
+
itemId: item.id,
|
|
1637
|
+
dependsOnId: found.get(ref),
|
|
1638
|
+
createdAt: now
|
|
1639
|
+
})));
|
|
1640
|
+
await tx.delete(scopedDependencies).where(eq(scopedDependencies.itemId, item.id));
|
|
1641
|
+
if (scoped.length > 0) await tx.insert(scopedDependencies).values(scoped.map((target) => ({
|
|
1642
|
+
itemId: item.id,
|
|
1643
|
+
targetProject: target.project,
|
|
1644
|
+
targetRef: target.ref,
|
|
1645
|
+
createdAt: now
|
|
1646
|
+
})));
|
|
1647
|
+
const cycle = await findCycleThrough(tx, item.id);
|
|
1648
|
+
if (cycle !== null) throw new Error(`that would create a dependency cycle: ${cycle.join(" -> ")}`);
|
|
1649
|
+
return dependencyRefs(tx, item.id);
|
|
1115
1650
|
}
|
|
1651
|
+
/**
|
|
1652
|
+
* The path of a dependency cycle running through `startId`, or null if there is none.
|
|
1653
|
+
*
|
|
1654
|
+
* `WITH RECURSIVE` because this is transitive reachability, which no query builder expresses - one of the
|
|
1655
|
+
* cases the storage notes reserve for raw SQL through Drizzle's `sql` tag.
|
|
1656
|
+
*
|
|
1657
|
+
* The `<> ALL(path)` guard is what makes it terminate: a node already on the path is not walked again. The
|
|
1658
|
+
* `OR = start` beside it is the exception that makes it *work*, since closing the loop means arriving back at
|
|
1659
|
+
* a node that is by definition already on the path. Without the guard this runs forever on any cycle; without
|
|
1660
|
+
* the exception it can never find one.
|
|
1661
|
+
*/
|
|
1116
1662
|
async function findCycleThrough(tx, startId) {
|
|
1117
|
-
|
|
1663
|
+
const row = rowsOf(await tx.execute(sql`
|
|
1118
1664
|
WITH RECURSIVE walk(id, path) AS (
|
|
1119
1665
|
SELECT depends_on_id, ARRAY[item_id, depends_on_id]
|
|
1120
1666
|
FROM dependencies
|
|
@@ -1126,203 +1672,482 @@ async function findCycleThrough(tx, startId) {
|
|
|
1126
1672
|
WHERE d.depends_on_id <> ALL(w.path) OR d.depends_on_id = ${startId}
|
|
1127
1673
|
)
|
|
1128
1674
|
SELECT path FROM walk WHERE id = ${startId} LIMIT 1
|
|
1129
|
-
`);
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1675
|
+
`))[0];
|
|
1676
|
+
if (row === void 0) return null;
|
|
1677
|
+
const path = row.path;
|
|
1678
|
+
const named = await tx.select({
|
|
1679
|
+
id: items.id,
|
|
1680
|
+
ref: items.ref
|
|
1681
|
+
}).from(items).where(inArray(items.id, [...new Set(path)]));
|
|
1682
|
+
const refOf = new Map(named.map((n) => [n.id, n.ref]));
|
|
1683
|
+
return path.map((id) => refOf.get(id) ?? id);
|
|
1136
1684
|
}
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1685
|
+
// src/domain/comments.ts
|
|
1686
|
+
/**
|
|
1687
|
+
* Comments (CTX-2): free prose written down as work happens, optionally attached to an item.
|
|
1688
|
+
*
|
|
1689
|
+
* Why this exists alongside context sections, which also hold prose. A section is *revised* - you read it,
|
|
1690
|
+
* rewrite the whole block, and write it back - which is right for a project's settled narrative and wrong for
|
|
1691
|
+
* "the learner reached for the conditional and could not say it". Recording that through a section means a read, a
|
|
1692
|
+
* merge and a full rewrite, and an agent in the middle of a task will simply defer it. Deferred writes are
|
|
1693
|
+
* lost writes: a Claude Desktop conversation does not end, it gets abandoned. A comment is one append with no
|
|
1694
|
+
* read first, cheap enough to write mid-exercise, which is the whole point.
|
|
1695
|
+
*
|
|
1696
|
+
* **These were called notes until 2026-09-01.** The rename is not cosmetic: it was measured. `add_note` said
|
|
1697
|
+
* *"One observation, in a sentence or two"* and across all 64 rows **not one had ever complied** - averaging
|
|
1698
|
+
* 2.3kB, and the earliest were already ~1kB, so it was never drift. The cause is a cost asymmetry this module
|
|
1699
|
+
* designed on purpose: an append needs no read first, editing an item body does, so when there is something
|
|
1700
|
+
* substantial to record the cheap path is a note and the correct path is an edit, and the cheap path wins
|
|
1701
|
+
* every time. What was being written was not notes at all - it was **decision records about an item**, which
|
|
1702
|
+
* are amendments to that item's reasoning and belong in its body.
|
|
1703
|
+
*
|
|
1704
|
+
* "Note" is a neutral word that invites anything. "Comment" carries its own shape: it is *about* the thing,
|
|
1705
|
+
* secondary to it, and nobody has ever thought a comment replaces the issue it sits on. See `MAX_BODY` for
|
|
1706
|
+
* why the word alone was not considered enough.
|
|
1707
|
+
*
|
|
1708
|
+
* Comments are editable and deletable. The tempting purity is to make them
|
|
1709
|
+
* append-only so history stays legible, but that is already true for a different reason: **the event log
|
|
1710
|
+
* keeps the before and after of every mutation**, so a corrected or removed comment is still in the audit trail
|
|
1711
|
+
* and nothing is actually lost. Refusing to edit would not buy legibility, it would only leave a wrong comment
|
|
1712
|
+
* to be re-read by every future session - and a comment written mid-task is exactly the kind of thing that turns
|
|
1713
|
+
* out to be wrong or to stop mattering. This is the same reasoning as `deleteSection` in `context.ts`.
|
|
1714
|
+
*
|
|
1715
|
+
* Revisable durable *facts*, where the supersede chain itself is the interesting record, are a different
|
|
1716
|
+
* thing again (`CTX-3`, observations) - which is also why nothing here describes a comment as being "for
|
|
1717
|
+
* observations". Two words for two things, one careless description away from colliding.
|
|
1718
|
+
*/
|
|
1719
|
+
/** Who a comment is for. `agent` is Claude's own working store: unsurfaced by default, never hidden. */
|
|
1720
|
+
var AUDIENCES = ["user", "agent"];
|
|
1721
|
+
/**
|
|
1722
|
+
* The refusal, shared by add and edit so the two cannot drift apart.
|
|
1723
|
+
*
|
|
1724
|
+
* Two branches, because there are two ways to be over the cap, and **one destination each**. A comment on an
|
|
1725
|
+
* item that has outgrown a remark is reasoning belonging to that item. A comment on *no* item cannot be
|
|
1726
|
+
* created any more at all, so an over-length one is legacy data and the useful instruction is how to convert
|
|
1727
|
+
* it. Neither branch offers trimming as an alternative: see the note on the cap for what happened when one
|
|
1728
|
+
* did.
|
|
1729
|
+
*/
|
|
1730
|
+
var tooLong = (body, itemId) => /* @__PURE__ */ new Error(itemId != null ? `this comment is ${body.length} characters and the limit is 800, which means it is not a remark - it is reasoning about the item. Put it in the item itself with edit_item, where a reader will find it. Do not cut it down to fit: what survives is the same content in the wrong place, minus what you dropped.` : `this comment is ${body.length} characters and the limit is 800. It is attached to the project rather than to an item, which is no longer allowed: if it holds readings, record them with record_measurements; if it is settled prose about the project, move it into a context section with set_context. Then delete this comment.`);
|
|
1731
|
+
/**
|
|
1732
|
+
* The refusal that deprecates project-level comments (`CTX-15`).
|
|
1733
|
+
*
|
|
1734
|
+
* **Unwritable, still readable.** Nothing existing is destroyed or hidden - `list_comments` still returns
|
|
1735
|
+
* them and the importer still loads them - because a plan file is committed history and a health tracker's
|
|
1736
|
+
* year of entries must not become unopenable over a rule that arrived after they were written.
|
|
1737
|
+
*
|
|
1738
|
+
* **The refusal is the migration trigger**, which is why it names three destinations rather than saying no.
|
|
1739
|
+
* `CTX-2` learned this from the cap: a refusal without a destination loses content instead of relocating it.
|
|
1740
|
+
* Converting prose entries into readings is not mechanical - it needs an agent reading each one - so there is
|
|
1741
|
+
* no migration script to run, and the moment somebody tries to write the next one is the moment to do it.
|
|
1742
|
+
*
|
|
1743
|
+
* **No plan ref in the message.** `CTX-15` is a ticket in *this* repo's backlog, and this text is read by an
|
|
1744
|
+
* agent working on somebody else's project, where that ref names nothing and is worth going to look for. The
|
|
1745
|
+
* ref belongs in this comment, where a maintainer is; the message gets the reason instead. Operator-facing
|
|
1746
|
+
* errors (a boot failure, a missing env var) are the exception - the person reading those is deploying this.
|
|
1747
|
+
*/
|
|
1748
|
+
var needsAnItem = () => /* @__PURE__ */ new Error("a comment must be about an item, so give `ref`. If you were recording readings - a weight, macros, a duration, a count - use record_measurements, which is what dated data belongs in. If it is settled prose about the project, use set_context. Existing project-level comments are still readable with list_comments.");
|
|
1145
1749
|
async function addComment(db, input, actor) {
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1750
|
+
const audience = input.audience ?? "user";
|
|
1751
|
+
if (!AUDIENCES.includes(audience)) throw new Error(`unknown audience "${audience}" (expected ${AUDIENCES.join(" | ")})`);
|
|
1752
|
+
const body = input.body.trim();
|
|
1753
|
+
if (body === "") throw new Error("a comment needs a body");
|
|
1754
|
+
if (input.itemId == null) throw needsAnItem();
|
|
1755
|
+
if (body.length > 800) throw tooLong(body, input.itemId);
|
|
1756
|
+
return mutate(db, actor, async (tx) => {
|
|
1757
|
+
const comment = one(await tx.insert(comments).values({
|
|
1758
|
+
projectId: input.projectId,
|
|
1759
|
+
itemId: input.itemId ?? null,
|
|
1760
|
+
body,
|
|
1761
|
+
audience,
|
|
1762
|
+
actor
|
|
1763
|
+
}).returning());
|
|
1764
|
+
return {
|
|
1765
|
+
result: comment,
|
|
1766
|
+
event: {
|
|
1767
|
+
projectId: input.projectId,
|
|
1768
|
+
entityType: "comment",
|
|
1769
|
+
entityId: comment.id,
|
|
1770
|
+
kind: "created",
|
|
1771
|
+
after: comment
|
|
1772
|
+
}
|
|
1773
|
+
};
|
|
1774
|
+
});
|
|
1158
1775
|
}
|
|
1776
|
+
/** Newest first, because the recent ones are what a returning session needs; ties broken by id, which is
|
|
1777
|
+
* UUIDv7 and therefore time-ordered, so two comments written in the same millisecond still order deterministically. */
|
|
1159
1778
|
async function listComments(db, input) {
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1779
|
+
const filters = [eq(comments.projectId, input.projectId)];
|
|
1780
|
+
if (input.itemId === null) filters.push(isNull(comments.itemId));
|
|
1781
|
+
else if (input.itemId !== void 0) filters.push(eq(comments.itemId, input.itemId));
|
|
1782
|
+
if (input.audience !== void 0) filters.push(eq(comments.audience, input.audience));
|
|
1783
|
+
return db.select().from(comments).where(and(...filters)).orderBy(desc(comments.createdAt), desc(comments.id)).limit(input.limit ?? 20);
|
|
1165
1784
|
}
|
|
1166
|
-
|
|
1785
|
+
// src/domain/items.ts
|
|
1786
|
+
/**
|
|
1787
|
+
* Items (DATA-6): the plan layer. One table for tickets and, later, skills and care items, with no type
|
|
1788
|
+
* column - see the schema. This module also does id allocation (DATA-7) and status validation.
|
|
1789
|
+
*
|
|
1790
|
+
* The storage and domain layers speak of "items"; the MCP tools say "ticket", because that is what a person
|
|
1791
|
+
* means. Genericity lives in the schema, not the vocabulary.
|
|
1792
|
+
*/
|
|
1793
|
+
var isStatus = (value) => Object.prototype.hasOwnProperty.call(STATUSES, value);
|
|
1794
|
+
/** Validate against the fixed vocabulary in one place; the schema leaves `status` an open string on purpose. */
|
|
1167
1795
|
function assertStatus(value) {
|
|
1168
|
-
|
|
1796
|
+
if (!isStatus(value)) throw new Error(`unknown status "${value}"; expected one of ${Object.keys(STATUSES).join(", ")}`);
|
|
1169
1797
|
}
|
|
1798
|
+
/**
|
|
1799
|
+
* Check an item's planned dates (`CAL-1`), as they will stand after the write: each a real calendar day, and a
|
|
1800
|
+
* start no later than its due. Checked against the *resulting* pair, so moving a due date earlier than an
|
|
1801
|
+
* existing start is caught by an edit that only names the due date.
|
|
1802
|
+
*/
|
|
1170
1803
|
function assertDates(start, due) {
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
}
|
|
1174
|
-
if (start !== null && due !== null && start > due) throw new Error(`start ${start} is after due ${due}`);
|
|
1804
|
+
for (const [name, value] of [["start", start], ["due", due]]) if (value !== null && !isCalendarDate(value)) throw new Error(`${name} "${value}" is not a calendar date; expected YYYY-MM-DD, like 2026-11-02`);
|
|
1805
|
+
if (start !== null && due !== null && start > due) throw new Error(`start ${start} is after due ${due}`);
|
|
1175
1806
|
}
|
|
1807
|
+
/** The highest `sort_path` among a set of siblings, as the number of its last segment. Because a `sort_path`
|
|
1808
|
+
* segment is just the zero-padded ref number, this is "the highest N so far" with no string parsing in SQL. */
|
|
1176
1809
|
async function highestSibling(tx, where) {
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1810
|
+
const row = maybeOne(await tx.select({ max: sql`max(${items.sortPath})` }).from(items).where(where));
|
|
1811
|
+
if (!row?.max) return 0;
|
|
1812
|
+
return parseInt(row.max.slice(row.max.lastIndexOf(".") + 1), 10);
|
|
1180
1813
|
}
|
|
1181
|
-
|
|
1814
|
+
/** Advisory locks share one server-wide space, so ours are namespaced by a constant in the first of the two
|
|
1815
|
+
* int4 keys. Arbitrary, only has to be ours and stay put. */
|
|
1816
|
+
var ALLOCATION_LOCK = 1634757937;
|
|
1817
|
+
/**
|
|
1818
|
+
* Work out the ref a new item gets. Three ways in, in precedence order:
|
|
1819
|
+
*
|
|
1820
|
+
* 1. an **explicit ref** (`MCP-18`), which migration needs and which lets a body reference a ticket that
|
|
1821
|
+
* does not exist yet, since the caller no longer has to create it first to learn its number;
|
|
1822
|
+
* 2. a **parent ref**, allocating the next child beneath it (`MCP-3` -> `MCP-3.2`);
|
|
1823
|
+
* 3. an **area**, allocating the next top-level ref in it (`DATA` -> `DATA-7`).
|
|
1824
|
+
*
|
|
1825
|
+
* Deleted items still hold their refs here (no `deleted_at` filter), which is deliberate: reusing `MCP-3`
|
|
1826
|
+
* after deleting it would silently retarget every body, note and commit message that mentions it.
|
|
1827
|
+
*
|
|
1828
|
+
* **Allocation is serialised per project by an advisory lock, and that is load-bearing on real Postgres**
|
|
1829
|
+
* (fixed 2026-08-09, `OPS-2`). Two of these three paths are `max(sort_path) + 1`, a textbook read-modify-write
|
|
1830
|
+
* race: under READ COMMITTED two overlapping transactions both read `MCP-19` and both try to write `MCP-20`.
|
|
1831
|
+
* This code previously relied on the race being impossible, which was true only because PGlite runs one
|
|
1832
|
+
* connection and serialises `db.transaction` itself. Running the suite against server Postgres broke exactly
|
|
1833
|
+
* the test that pinned that assumption, which is the whole reason for running it there.
|
|
1834
|
+
*
|
|
1835
|
+
* A lock rather than retrying on the unique violation, because parallel creates are the *designed* case
|
|
1836
|
+
* (Claude Code fans out independent tool calls, so "create five tickets" arrives as five overlapping ones).
|
|
1837
|
+
* Retrying makes contention quadratic - each round lets exactly one winner through - whereas the lock costs
|
|
1838
|
+
* one round trip and turns the contended case into an orderly queue. The unique index stays as the backstop
|
|
1839
|
+
* that would catch this being got wrong again.
|
|
1840
|
+
*/
|
|
1182
1841
|
async function allocate(tx, projectId, input) {
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1842
|
+
await tx.execute(sql`SELECT pg_advisory_xact_lock(${ALLOCATION_LOCK}, hashtext(${projectId}))`);
|
|
1843
|
+
if (input.ref !== void 0) {
|
|
1844
|
+
const ref = input.ref.trim();
|
|
1845
|
+
if (!isRef(ref)) throw new Error(`"${ref}" is not a valid ref: expected an area prefix and dotted numbers, like MCP-3 or MCP-3.1`);
|
|
1846
|
+
const clash = await byRef(tx, projectId, ref);
|
|
1847
|
+
if (clash !== null) throw new Error(`ref "${ref}" is already taken by: ${clash.title}`);
|
|
1848
|
+
const parent = parentRef(ref);
|
|
1849
|
+
return {
|
|
1850
|
+
ref,
|
|
1851
|
+
path: sortPath(ref),
|
|
1852
|
+
area: areaOf(ref),
|
|
1853
|
+
parentId: parent === null ? null : (await requireRef(tx, projectId, parent)).id
|
|
1854
|
+
};
|
|
1855
|
+
}
|
|
1856
|
+
if (input.parent !== void 0) {
|
|
1857
|
+
const parent = await requireRef(tx, projectId, input.parent.trim());
|
|
1858
|
+
const next = await highestSibling(tx, and(eq(items.projectId, projectId), eq(items.parentId, parent.id))) + 1;
|
|
1859
|
+
const ref = `${parent.ref}.${next}`;
|
|
1860
|
+
return {
|
|
1861
|
+
ref,
|
|
1862
|
+
path: sortPath(ref),
|
|
1863
|
+
area: parent.areaKey,
|
|
1864
|
+
parentId: parent.id
|
|
1865
|
+
};
|
|
1866
|
+
}
|
|
1867
|
+
if (input.area === void 0) throw new Error("give an area (or a parent ref, or an explicit ref) to create a ticket under");
|
|
1868
|
+
const area = input.area.trim().toUpperCase();
|
|
1869
|
+
const ref = `${area}-${await highestSibling(tx, and(eq(items.projectId, projectId), eq(items.areaKey, area), isNull(items.parentId))) + 1}`;
|
|
1870
|
+
return {
|
|
1871
|
+
ref,
|
|
1872
|
+
path: sortPath(ref),
|
|
1873
|
+
area,
|
|
1874
|
+
parentId: null
|
|
1875
|
+
};
|
|
1203
1876
|
}
|
|
1204
|
-
|
|
1877
|
+
var byRef = async (tx, projectId, ref) => maybeOne(await tx.select().from(items).where(and(eq(items.projectId, projectId), eq(items.ref, ref))));
|
|
1205
1878
|
async function requireRef(tx, projectId, ref) {
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1879
|
+
const item = await byRef(tx, projectId, ref);
|
|
1880
|
+
if (item === null) throw new Error(`no ticket "${ref}" in this project`);
|
|
1881
|
+
return item;
|
|
1209
1882
|
}
|
|
1210
1883
|
async function createItem(db, input, actor) {
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1884
|
+
const status = input.status ?? "to-do";
|
|
1885
|
+
assertStatus(status);
|
|
1886
|
+
const startOn = input.start ?? null;
|
|
1887
|
+
const dueOn = input.due ?? null;
|
|
1888
|
+
assertDates(startOn, dueOn);
|
|
1889
|
+
return mutate(db, actor, async (tx) => {
|
|
1890
|
+
const { ref, path, area, parentId } = await allocate(tx, input.projectId, input);
|
|
1891
|
+
const item = one(await tx.insert(items).values({
|
|
1892
|
+
projectId: input.projectId,
|
|
1893
|
+
ref,
|
|
1894
|
+
areaKey: area,
|
|
1895
|
+
sortPath: path,
|
|
1896
|
+
parentId,
|
|
1897
|
+
title: input.title,
|
|
1898
|
+
body: input.body ?? null,
|
|
1899
|
+
status,
|
|
1900
|
+
startOn,
|
|
1901
|
+
dueOn
|
|
1902
|
+
}).returning());
|
|
1903
|
+
if (input.deps && input.deps.length > 0) await setDependencies(tx, item, input.deps);
|
|
1904
|
+
return {
|
|
1905
|
+
result: item,
|
|
1906
|
+
event: {
|
|
1907
|
+
projectId: input.projectId,
|
|
1908
|
+
entityType: "item",
|
|
1909
|
+
entityId: item.id,
|
|
1910
|
+
kind: "created",
|
|
1911
|
+
after: item
|
|
1912
|
+
}
|
|
1913
|
+
};
|
|
1914
|
+
});
|
|
1224
1915
|
}
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
dueOn: items.dueOn
|
|
1916
|
+
var SUMMARY_COLUMNS = {
|
|
1917
|
+
id: items.id,
|
|
1918
|
+
ref: items.ref,
|
|
1919
|
+
areaKey: items.areaKey,
|
|
1920
|
+
sortPath: items.sortPath,
|
|
1921
|
+
parentId: items.parentId,
|
|
1922
|
+
title: items.title,
|
|
1923
|
+
status: items.status,
|
|
1924
|
+
createdAt: items.createdAt,
|
|
1925
|
+
updatedAt: items.updatedAt,
|
|
1926
|
+
closedAt: items.closedAt,
|
|
1927
|
+
startOn: items.startOn,
|
|
1928
|
+
dueOn: items.dueOn
|
|
1239
1929
|
};
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
}
|
|
1254
|
-
return and(...conditions);
|
|
1930
|
+
var listConditions = (filter) => {
|
|
1931
|
+
const conditions = [eq(items.projectId, filter.projectId), isNull(items.deletedAt)];
|
|
1932
|
+
if (filter.status) conditions.push(eq(items.status, filter.status));
|
|
1933
|
+
if (filter.area) conditions.push(eq(items.areaKey, filter.area.toUpperCase()));
|
|
1934
|
+
if (windowed(filter)) {
|
|
1935
|
+
for (const [name, value] of [["from", filter.from], ["to", filter.to]]) if (value !== void 0 && !isCalendarDate(value)) throw new Error(`${name} "${value}" is not a calendar date; expected YYYY-MM-DD, like 2026-11-02`);
|
|
1936
|
+
if (filter.from !== void 0 && filter.to !== void 0 && filter.from > filter.to) throw new Error(`from ${filter.from} is after to ${filter.to}`);
|
|
1937
|
+
const first = sql`coalesce(${items.startOn}, ${items.dueOn})`;
|
|
1938
|
+
const last = sql`coalesce(${items.dueOn}, ${items.startOn})`;
|
|
1939
|
+
if (filter.to !== void 0) conditions.push(sql`${first} <= ${filter.to}`);
|
|
1940
|
+
if (filter.from !== void 0) conditions.push(sql`${last} >= ${filter.from}`);
|
|
1941
|
+
}
|
|
1942
|
+
return and(...conditions);
|
|
1255
1943
|
};
|
|
1256
1944
|
async function listItems(db, filter) {
|
|
1257
|
-
|
|
1945
|
+
return db.select(SUMMARY_COLUMNS).from(items).where(listConditions(filter)).orderBy(...windowed(filter) ? [sql`coalesce(${items.startOn}, ${items.dueOn})`] : [], asc(items.areaKey), asc(items.sortPath));
|
|
1258
1946
|
}
|
|
1259
|
-
|
|
1947
|
+
var windowed = (filter) => filter.from !== void 0 || filter.to !== void 0;
|
|
1260
1948
|
async function getItem(db, projectId, ref) {
|
|
1261
|
-
|
|
1949
|
+
return maybeOne(await db.select().from(items).where(and(eq(items.projectId, projectId), eq(items.ref, ref))));
|
|
1262
1950
|
}
|
|
1951
|
+
/** One item with its dependency refs resolved - what a read tool needs to show a whole ticket (body included).
|
|
1952
|
+
* Null when no item has that ref in the project.
|
|
1953
|
+
*
|
|
1954
|
+
* Comments come with it rather than needing a second call: a comment attached to a ticket *is* part of that
|
|
1955
|
+
* ticket - what went wrong on it, what was tried - and a reader who has to know to go looking will not. */
|
|
1263
1956
|
async function getItemDetail(db, projectId, ref) {
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1957
|
+
const item = await getItem(db, projectId, ref);
|
|
1958
|
+
if (item === null) return null;
|
|
1959
|
+
return {
|
|
1960
|
+
item,
|
|
1961
|
+
deps: await dependencyRefs(db, item.id),
|
|
1962
|
+
comments: await listComments(db, {
|
|
1963
|
+
projectId,
|
|
1964
|
+
itemId: item.id
|
|
1965
|
+
})
|
|
1966
|
+
};
|
|
1267
1967
|
}
|
|
1268
1968
|
async function setStatus(db, args, actor) {
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1969
|
+
assertStatus(args.status);
|
|
1970
|
+
return mutate(db, actor, async (tx) => {
|
|
1971
|
+
const before = maybeOne(await tx.select().from(items).where(and(eq(items.projectId, args.projectId), eq(items.ref, args.ref))));
|
|
1972
|
+
if (before === null) throw new Error(`no ticket "${args.ref}" in this project`);
|
|
1973
|
+
const now = timestamp();
|
|
1974
|
+
const after = one(await tx.update(items).set({
|
|
1975
|
+
status: args.status,
|
|
1976
|
+
updatedAt: now,
|
|
1977
|
+
closedAt: args.status === "done" ? now : null
|
|
1978
|
+
}).where(eq(items.id, before.id)).returning());
|
|
1979
|
+
return {
|
|
1980
|
+
result: after,
|
|
1981
|
+
event: {
|
|
1982
|
+
projectId: args.projectId,
|
|
1983
|
+
entityType: "item",
|
|
1984
|
+
entityId: before.id,
|
|
1985
|
+
kind: "status-changed",
|
|
1986
|
+
before,
|
|
1987
|
+
after
|
|
1988
|
+
}
|
|
1989
|
+
};
|
|
1990
|
+
});
|
|
1279
1991
|
}
|
|
1992
|
+
/** Revise a ticket's title, body, dependencies and/or planned dates. Status has its own path (`setStatus`), so this never
|
|
1993
|
+
* touches it; at least one field must be given. The whole before/after is logged, so the edit is auditable
|
|
1994
|
+
* and reversible like any other mutation. */
|
|
1280
1995
|
async function editItem(db, input, actor) {
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1996
|
+
if (input.title === void 0 && input.body === void 0 && input.deps === void 0 && input.start === void 0 && input.due === void 0) throw new Error("nothing to edit: provide a title, body, deps, start and/or due");
|
|
1997
|
+
return mutate(db, actor, async (tx) => {
|
|
1998
|
+
const before = maybeOne(await tx.select().from(items).where(and(eq(items.projectId, input.projectId), eq(items.ref, input.ref))));
|
|
1999
|
+
if (before === null) throw new Error(`no ticket "${input.ref}" in this project`);
|
|
2000
|
+
const changes = { updatedAt: timestamp() };
|
|
2001
|
+
if (input.title !== void 0) changes.title = input.title;
|
|
2002
|
+
if (input.body !== void 0) changes.body = input.body;
|
|
2003
|
+
if (input.start !== void 0) changes.startOn = input.start;
|
|
2004
|
+
if (input.due !== void 0) changes.dueOn = input.due;
|
|
2005
|
+
assertDates(input.start === void 0 ? before.startOn : input.start, input.due === void 0 ? before.dueOn : input.due);
|
|
2006
|
+
const after = one(await tx.update(items).set(changes).where(eq(items.id, before.id)).returning());
|
|
2007
|
+
const beforeDeps = input.deps === void 0 ? void 0 : await dependencyRefs(tx, before.id);
|
|
2008
|
+
const afterDeps = input.deps === void 0 ? void 0 : await setDependencies(tx, before, input.deps);
|
|
2009
|
+
return {
|
|
2010
|
+
result: after,
|
|
2011
|
+
event: {
|
|
2012
|
+
projectId: input.projectId,
|
|
2013
|
+
entityType: "item",
|
|
2014
|
+
entityId: before.id,
|
|
2015
|
+
kind: "edited",
|
|
2016
|
+
before: {
|
|
2017
|
+
...before,
|
|
2018
|
+
deps: beforeDeps
|
|
2019
|
+
},
|
|
2020
|
+
after: {
|
|
2021
|
+
...after,
|
|
2022
|
+
deps: afterDeps
|
|
2023
|
+
}
|
|
2024
|
+
}
|
|
2025
|
+
};
|
|
2026
|
+
});
|
|
2027
|
+
}
|
|
2028
|
+
/**
|
|
2029
|
+
* How much an item outranks a comment or a context section at the same textual relevance.
|
|
2030
|
+
*
|
|
2031
|
+
* **A starting guess, and explicitly a knob to tune** (`DATA-11` slice 4). The reasoning is that an item is a
|
|
2032
|
+
* thing you act on and so is usually the more useful answer to "what do we know about X", while a comment is
|
|
2033
|
+
* evidence about it. That is a hypothesis about how this gets used, and there was no usage to check it against
|
|
2034
|
+
* when it was written. Revisit against real searches rather than by arguing about the number.
|
|
2035
|
+
*/
|
|
2036
|
+
var ITEM_BOOST = 1.5;
|
|
2037
|
+
/**
|
|
2038
|
+
* `MaxFragments=2` so a long body can contribute two separate matching passages rather than one window that
|
|
2039
|
+
* happens to cover the first hit. `**` rather than the default `<b>`, because these are read by an agent and
|
|
2040
|
+
* rendered as markdown, not as HTML.
|
|
2041
|
+
*/
|
|
2042
|
+
var HEADLINE_OPTIONS = "MaxFragments=2,MinWords=6,MaxWords=18,StartSel=**,StopSel=**,FragmentDelimiter= ... ";
|
|
2043
|
+
var BRACKETED_OPTIONS = `MaxFragments=2,MinWords=6,MaxWords=18,StartSel=⟦,StopSel=⟧,FragmentDelimiter= ... `;
|
|
2044
|
+
/**
|
|
2045
|
+
* Why a **term-dense** query can match nothing at all - which is not the same as a long one.
|
|
2046
|
+
*
|
|
2047
|
+
* `websearch_to_tsquery` joins terms with **AND**, so "optional flag tool argument the model chooses" becomes
|
|
2048
|
+
* `option & flag & tool & argument & model & choos` - six stems required in a single document. Measured
|
|
2049
|
+
* against this project's own 152 items on 2026-09-01, that matched **nothing**; the same terms OR-ed matched
|
|
2050
|
+
* 93.
|
|
2051
|
+
*
|
|
2052
|
+
* **Length is the wrong diagnosis, and the first version of this comment gave it.** Stop words are stripped
|
|
2053
|
+
* before the AND applies, and an English question is mostly stop words, so it collapses to very few terms:
|
|
2054
|
+
*
|
|
2055
|
+
* 7 words -> 3 terms 'viewer' & 'authent' & 'user' ("how does the viewer authenticate a user")
|
|
2056
|
+
* 5 words -> 2 terms 'choos' & 'postgr' ("why did we choose postgres")
|
|
2057
|
+
* 7 words -> 6 terms 'option' & 'flag' & 'tool' & ... (the query above)
|
|
2058
|
+
*
|
|
2059
|
+
* The failing one is a *list of nouns*, which is what a query written as a description of a concept looks
|
|
2060
|
+
* like. Fifteen realistic questions against the real store all matched strictly, including every long one, so
|
|
2061
|
+
* **the fallback below is a rare safety net rather than the normal path** - which is what keeps `relaxed`
|
|
2062
|
+
* meaningful as a signal and keeps the second query off the common path.
|
|
2063
|
+
*
|
|
2064
|
+
* It also explains why the miss reply's nudge works: telling someone to use the words that would appear in
|
|
2065
|
+
* the writing is telling them to write a sentence, and sentences survive the AND.
|
|
2066
|
+
*
|
|
2067
|
+
* So when the strict query finds nothing, relax it to "any of these" and let ranking sort out the flood. On
|
|
2068
|
+
* the query that actually failed, this returns the right ticket first.
|
|
2069
|
+
*
|
|
2070
|
+
* **Only when the strict query found nothing**, never by default: AND is right whenever it matches, and 93
|
|
2071
|
+
* ranked hits is a worse answer than 4 matched ones. Always relaxing would also make "nothing is recorded
|
|
2072
|
+
* about this" unsayable, and that is a real answer the caller wanted.
|
|
2073
|
+
*
|
|
2074
|
+
* **And only when relaxing is meaningful and safe**, which is two conditions:
|
|
2075
|
+
*
|
|
2076
|
+
* - The query must contain a top-level `&`. A single term has nothing to relax, and re-running it as itself
|
|
2077
|
+
* is a wasted scan.
|
|
2078
|
+
* - It must contain no `!`. `framework -backend` renders as `framework & !backend`, and rewriting that to
|
|
2079
|
+
* `framework | !backend` matches nearly every document in the project - an exclusion turned into a wildcard.
|
|
2080
|
+
* Someone who wrote an exclusion was being precise, so the honest answer there is the empty one.
|
|
2081
|
+
*
|
|
2082
|
+
* A quoted phrase renders with `<->` rather than `&` and so passes through untouched, which is the behaviour
|
|
2083
|
+
* you want: `"backend framework"` stays a phrase in both passes.
|
|
2084
|
+
*/
|
|
2085
|
+
var relaxable = (tsquery) => tsquery.includes(" & ") && !tsquery.includes("!");
|
|
2086
|
+
/**
|
|
2087
|
+
* The word a person is still typing: the query's last run of letters and digits, when the query ends in one.
|
|
2088
|
+
* Not when it ends in a space (the word is finished), a quote (a phrase is), or anything else.
|
|
2089
|
+
*/
|
|
2090
|
+
var PARTIAL = /(?:^|[^\p{L}\p{N}"-])([\p{L}\p{N}]+)$/u;
|
|
2091
|
+
/**
|
|
2092
|
+
* The tsquery for a search. **As typed** (`prefix`, `VIEW-25`), the last word also matches any word it begins:
|
|
2093
|
+
* "collap" finds "collapse", which a search box needs and `websearch_to_tsquery` cannot do, since it matches
|
|
2094
|
+
* whole stemmed words. The rest of the query is parsed exactly as without it, and the partial word becomes
|
|
2095
|
+
* `to_tsquery('collap:*')`, stemmed by the same configuration, ANDed on.
|
|
2096
|
+
*
|
|
2097
|
+
* **One matching rule, two modes**, rather than the viewer filtering on its own: the box and `search_plan` run
|
|
2098
|
+
* this same query, so the human and the agent cannot get differently-ranked answers. The agent does not ask
|
|
2099
|
+
* for the prefix, because it writes finished words and a prefix only widens what they match.
|
|
2100
|
+
*/
|
|
2101
|
+
function tsquery(query, prefix) {
|
|
2102
|
+
const partial = prefix ? PARTIAL.exec(query) : null;
|
|
2103
|
+
if (partial === null) return sql`websearch_to_tsquery(${TEXT_SEARCH_CONFIG}, ${query})`;
|
|
2104
|
+
const head = query.slice(0, partial.index + partial[0].length - partial[1].length);
|
|
2105
|
+
const word = sql`to_tsquery(${TEXT_SEARCH_CONFIG}, ${`${partial[1]}:*`})`;
|
|
2106
|
+
return head.trim() === "" ? word : sql`(websearch_to_tsquery(${TEXT_SEARCH_CONFIG}, ${head}) && ${word})`;
|
|
1308
2107
|
}
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
2108
|
+
/** The strict query, and the same query with its top-level ANDs turned into ORs. */
|
|
2109
|
+
var AND_QUERY = (query, prefix = false) => tsquery(query, prefix);
|
|
2110
|
+
var OR_QUERY = (query, prefix = false) => sql`replace((${tsquery(query, prefix)})::text, ' & ', ' | ')::tsquery`;
|
|
2111
|
+
/**
|
|
2112
|
+
* Search one project's items, comments and context sections in a single query.
|
|
2113
|
+
*
|
|
2114
|
+
* **Ranking and snippets are separated on purpose.** The inner select matches and ranks over the GIN indexes
|
|
2115
|
+
* and is cut to `limit`; only then does the outer select call `ts_headline`, which is the expensive part
|
|
2116
|
+
* because it re-parses the document text it is quoting from. Running it before the cut would headline every
|
|
2117
|
+
* match in the project to throw nearly all of them away.
|
|
2118
|
+
*
|
|
2119
|
+
* **Scoping is the security boundary.** `projectId` is an `OwnedProjectId`, so it cannot be reached without
|
|
2120
|
+
* having gone through `resolveProject` - which matters more here than almost anywhere else, since this is a
|
|
2121
|
+
* query over every row of prose in the database and an unscoped one would return another owner's plan.
|
|
2122
|
+
* Soft-deleted items are excluded for the same class of reason: there is no hard-delete path, so a deleted
|
|
2123
|
+
* ticket is still a row and would otherwise surface as a live one.
|
|
2124
|
+
*/
|
|
2125
|
+
async function search(db, projectId, query, limit = 8, options = {}) {
|
|
2126
|
+
const prefix = options.prefix === true;
|
|
2127
|
+
const headline = options.bracketed === true ? BRACKETED_OPTIONS : HEADLINE_OPTIONS;
|
|
2128
|
+
if (query.trim() === "") return {
|
|
2129
|
+
hits: [],
|
|
2130
|
+
relaxed: false
|
|
2131
|
+
};
|
|
2132
|
+
const strict = await matching(db, projectId, AND_QUERY(query, prefix), sql`ts_rank`, limit, headline);
|
|
2133
|
+
if (strict.length > 0) return {
|
|
2134
|
+
hits: strict,
|
|
2135
|
+
relaxed: false
|
|
2136
|
+
};
|
|
2137
|
+
const [built] = rowsOf(await db.execute(sql`SELECT (${AND_QUERY(query, prefix)})::text AS tsq`));
|
|
2138
|
+
if (built === void 0 || !relaxable(built.tsq)) return {
|
|
2139
|
+
hits: [],
|
|
2140
|
+
relaxed: false
|
|
2141
|
+
};
|
|
2142
|
+
const loose = await matching(db, projectId, OR_QUERY(query, prefix), sql`ts_rank`, limit, headline);
|
|
2143
|
+
return {
|
|
2144
|
+
hits: loose,
|
|
2145
|
+
relaxed: loose.length > 0
|
|
2146
|
+
};
|
|
1323
2147
|
}
|
|
1324
|
-
|
|
1325
|
-
|
|
2148
|
+
/** One pass of the search, for a given tsquery expression and ranking function. */
|
|
2149
|
+
async function matching(db, projectId, q, rank, limit, headline) {
|
|
2150
|
+
return rowsOf(await db.execute(sql`
|
|
1326
2151
|
WITH matches AS (
|
|
1327
2152
|
SELECT 'item' AS source,
|
|
1328
2153
|
i.ref AS ref,
|
|
@@ -1361,121 +2186,209 @@ async function matching(db, projectId, q, rank, limit) {
|
|
|
1361
2186
|
SELECT * FROM matches ORDER BY rank DESC, at DESC, id ASC LIMIT ${limit}
|
|
1362
2187
|
)
|
|
1363
2188
|
SELECT source, ref, id, title, audience, at, rank,
|
|
1364
|
-
ts_headline(${TEXT_SEARCH_CONFIG}, text, ${q}, ${
|
|
2189
|
+
ts_headline(${TEXT_SEARCH_CONFIG}, text, ${q}, ${headline}) AS snippet
|
|
1365
2190
|
FROM top
|
|
1366
2191
|
ORDER BY rank DESC, at DESC, id ASC
|
|
1367
|
-
`)
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
audience: row.audience,
|
|
1378
|
-
at: row.at
|
|
1379
|
-
}));
|
|
2192
|
+
`)).map((row) => ({
|
|
2193
|
+
source: row.source,
|
|
2194
|
+
ref: row.ref,
|
|
2195
|
+
id: row.id,
|
|
2196
|
+
title: row.title,
|
|
2197
|
+
snippet: row.snippet,
|
|
2198
|
+
rank: Number(row.rank),
|
|
2199
|
+
audience: row.audience,
|
|
2200
|
+
at: row.at
|
|
2201
|
+
}));
|
|
1380
2202
|
}
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
title: i.title,
|
|
1388
|
-
status: i.status,
|
|
1389
|
-
createdAt: i.createdAt,
|
|
1390
|
-
updatedAt: i.updatedAt,
|
|
1391
|
-
closedAt: i.closedAt,
|
|
1392
|
-
start: i.startOn,
|
|
1393
|
-
due: i.dueOn
|
|
2203
|
+
// src/library/records.ts
|
|
2204
|
+
var projectOf = (p) => ({
|
|
2205
|
+
key: p.key,
|
|
2206
|
+
name: p.name,
|
|
2207
|
+
type: p.type,
|
|
2208
|
+
direction: p.direction ?? null
|
|
1394
2209
|
});
|
|
1395
|
-
|
|
1396
|
-
|
|
2210
|
+
/** `A-3.1` -> `A-3`; an undotted ref has no parent. */
|
|
2211
|
+
var parentOf = (ref) => ref.includes(".") ? ref.slice(0, ref.lastIndexOf(".")) : null;
|
|
2212
|
+
var summaryOf = (i) => ({
|
|
2213
|
+
ref: i.ref,
|
|
2214
|
+
area: i.areaKey,
|
|
2215
|
+
parent: parentOf(i.ref),
|
|
2216
|
+
title: i.title,
|
|
2217
|
+
status: i.status,
|
|
2218
|
+
createdAt: i.createdAt,
|
|
2219
|
+
updatedAt: i.updatedAt,
|
|
2220
|
+
closedAt: i.closedAt,
|
|
2221
|
+
start: i.startOn,
|
|
2222
|
+
due: i.dueOn
|
|
2223
|
+
});
|
|
2224
|
+
var itemOf = (i) => ({
|
|
2225
|
+
...summaryOf(i),
|
|
2226
|
+
body: i.body ?? ""
|
|
2227
|
+
});
|
|
2228
|
+
var commentOf = (c, ref) => ({
|
|
2229
|
+
id: c.id,
|
|
2230
|
+
ref,
|
|
2231
|
+
body: c.body,
|
|
2232
|
+
audience: c.audience,
|
|
2233
|
+
actor: c.actor,
|
|
2234
|
+
at: c.createdAt
|
|
2235
|
+
});
|
|
2236
|
+
// src/library/project.ts
|
|
1397
2237
|
function projectHandle({ db, project, actor, writing }) {
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
2238
|
+
const projectId = project.id;
|
|
2239
|
+
const itemIdOf = async (ref) => {
|
|
2240
|
+
const found = await getItem(db, projectId, ref);
|
|
2241
|
+
if (found === null) throw new Error(`no item "${ref}" in ${project.key}`);
|
|
2242
|
+
return found.id;
|
|
2243
|
+
};
|
|
2244
|
+
return {
|
|
2245
|
+
key: project.key,
|
|
2246
|
+
listItems: async (filter = {}) => (await listItems(db, {
|
|
2247
|
+
projectId,
|
|
2248
|
+
...filter
|
|
2249
|
+
})).map(summaryOf),
|
|
2250
|
+
getItem: async (ref) => {
|
|
2251
|
+
const detail = await getItemDetail(db, projectId, ref);
|
|
2252
|
+
if (detail === null) return null;
|
|
2253
|
+
return {
|
|
2254
|
+
...itemOf(detail.item),
|
|
2255
|
+
deps: detail.deps,
|
|
2256
|
+
comments: detail.comments.map((c) => commentOf(c, detail.item.ref))
|
|
2257
|
+
};
|
|
2258
|
+
},
|
|
2259
|
+
createItem: (input) => writing(async () => itemOf(await createItem(db, {
|
|
2260
|
+
projectId,
|
|
2261
|
+
...input
|
|
2262
|
+
}, actor))),
|
|
2263
|
+
editItem: (ref, changes) => writing(async () => itemOf(await editItem(db, {
|
|
2264
|
+
projectId,
|
|
2265
|
+
ref,
|
|
2266
|
+
...changes
|
|
2267
|
+
}, actor))),
|
|
2268
|
+
setStatus: (ref, status) => writing(async () => itemOf(await setStatus(db, {
|
|
2269
|
+
projectId,
|
|
2270
|
+
ref,
|
|
2271
|
+
status
|
|
2272
|
+
}, actor))),
|
|
2273
|
+
addComment: (ref, body, { audience } = {}) => writing(async () => {
|
|
2274
|
+
const itemId = await itemIdOf(ref);
|
|
2275
|
+
return commentOf(await addComment(db, {
|
|
2276
|
+
projectId,
|
|
2277
|
+
body,
|
|
2278
|
+
itemId,
|
|
2279
|
+
audience
|
|
2280
|
+
}, actor), ref);
|
|
2281
|
+
}),
|
|
2282
|
+
listComments: async ({ ref, audience, limit } = {}) => {
|
|
2283
|
+
const itemId = ref === void 0 || ref === null ? ref : await itemIdOf(ref);
|
|
2284
|
+
const rows = await listComments(db, {
|
|
2285
|
+
projectId,
|
|
2286
|
+
itemId,
|
|
2287
|
+
audience,
|
|
2288
|
+
limit
|
|
2289
|
+
});
|
|
2290
|
+
const refById = new Map((await listItems(db, { projectId })).map((i) => [i.id, i.ref]));
|
|
2291
|
+
return rows.map((c) => commentOf(c, c.itemId === null ? null : refById.get(c.itemId) ?? null));
|
|
2292
|
+
},
|
|
2293
|
+
getSection: async (heading) => (await getSection(db, projectId, heading))?.content ?? null,
|
|
2294
|
+
setSection: (heading, content, { after } = {}) => writing(async () => {
|
|
2295
|
+
await setSection(db, {
|
|
2296
|
+
projectId,
|
|
2297
|
+
heading,
|
|
2298
|
+
content,
|
|
2299
|
+
after
|
|
2300
|
+
}, actor);
|
|
2301
|
+
}),
|
|
2302
|
+
search: async (query, { limit = 8 } = {}) => {
|
|
2303
|
+
const { hits, relaxed } = await search(db, projectId, query, limit);
|
|
2304
|
+
return {
|
|
2305
|
+
hits: hits.map((hit) => ({ ...hit })),
|
|
2306
|
+
relaxed
|
|
2307
|
+
};
|
|
2308
|
+
}
|
|
2309
|
+
};
|
|
1434
2310
|
}
|
|
2311
|
+
// src/library/open.ts
|
|
2312
|
+
/**
|
|
2313
|
+
* Opening a plan (`DIST-6`): the in-memory database, the YAML loaded into it, and the write-through to `save`. The
|
|
2314
|
+
* public face of this is `openPlan` in `index.ts`, whose types are the contract this fulfils.
|
|
2315
|
+
*/
|
|
1435
2316
|
async function open(options) {
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
2317
|
+
const actor = options.actor ?? "claude";
|
|
2318
|
+
const { db, close } = await createInMemoryDb();
|
|
2319
|
+
try {
|
|
2320
|
+
if (options.yaml !== void 0 && options.yaml.trim() !== "") await importStore(db, parseStore(options.yaml));
|
|
2321
|
+
} catch (error) {
|
|
2322
|
+
await close();
|
|
2323
|
+
throw error;
|
|
2324
|
+
}
|
|
2325
|
+
const { id: ownerId } = await ensureUser(db, LOCAL_IDENTITY);
|
|
2326
|
+
const toYaml = async () => stringifyStore(await exportStore(db, ownerId));
|
|
2327
|
+
let saving = Promise.resolve();
|
|
2328
|
+
const persist = async () => {
|
|
2329
|
+
const save = options.save;
|
|
2330
|
+
if (save === void 0) return;
|
|
2331
|
+
const next = saving.then(async () => save(await toYaml()));
|
|
2332
|
+
saving = next.catch(() => {});
|
|
2333
|
+
await next;
|
|
2334
|
+
};
|
|
2335
|
+
/** A mutation, then its save, so a write resolves only once it is durable wherever `save` puts it. */
|
|
2336
|
+
const writing = async (work) => {
|
|
2337
|
+
const result = await work();
|
|
2338
|
+
await persist();
|
|
2339
|
+
return result;
|
|
2340
|
+
};
|
|
2341
|
+
const resolve = async (key) => {
|
|
2342
|
+
const project = await getProjectByKey(db, ownerId, key);
|
|
2343
|
+
if (project === null) throw new Error(`no project with key "${key}"`);
|
|
2344
|
+
return project;
|
|
2345
|
+
};
|
|
2346
|
+
return {
|
|
2347
|
+
listProjects: async () => (await listProjects(db, ownerId)).map(projectOf),
|
|
2348
|
+
createProject: (input) => writing(async () => projectOf(await createProjectWithDefaults(db, {
|
|
2349
|
+
...input,
|
|
2350
|
+
ownerId
|
|
2351
|
+
}, actor))),
|
|
2352
|
+
project: async (key) => projectHandle({
|
|
2353
|
+
db,
|
|
2354
|
+
project: await resolve(key),
|
|
2355
|
+
actor,
|
|
2356
|
+
writing
|
|
2357
|
+
}),
|
|
2358
|
+
toYaml,
|
|
2359
|
+
close: async () => {
|
|
2360
|
+
await saving;
|
|
2361
|
+
await close();
|
|
2362
|
+
}
|
|
2363
|
+
};
|
|
1475
2364
|
}
|
|
2365
|
+
// src/library/index.ts
|
|
2366
|
+
/**
|
|
2367
|
+
* The in-process library (`DIST-6`): open a plan and call it directly, typed, with no child process and no MCP.
|
|
2368
|
+
*
|
|
2369
|
+
* The MCP tools are written for a model - budget-bounded replies in prose - and a program reading them has to
|
|
2370
|
+
* parse our display text back into data (Law & Lore's `store.ts` did, by regex). This is the program's own
|
|
2371
|
+
* door onto the same domain functions, so a write here is exactly a tool call's write: one transaction, an
|
|
2372
|
+
* event row, then the plan re-serialised and handed to `save`.
|
|
2373
|
+
*
|
|
2374
|
+
* **It runs in a browser.** Nothing this module reaches imports Node: the plan arrives as YAML text and leaves
|
|
2375
|
+
* through a callback, the migrations are compiled in (`db/bundledMigrations.ts`), and PGlite is WASM either way.
|
|
2376
|
+
* Where the text is kept - a file, IndexedDB, the origin-private file system - is the caller's business, which
|
|
2377
|
+
* is what lets one build serve a Node script and a static site. A file-backed `openPlan(paths)`, with the
|
|
2378
|
+
* server's reload and stale-write guard (`IMP-10`, `IMP-13`), is the Node-only follow-up `DIST-6` describes.
|
|
2379
|
+
*
|
|
2380
|
+
* **This file is the contract: the public types, declared here and only here.** Every exported signature names a
|
|
2381
|
+
* type from this file rather than a database row, so the published `.d.ts` is self-contained (the build fails if
|
|
2382
|
+
* it is not) and a column added to the schema is not an API change. The implementation is beside it, in files the
|
|
2383
|
+
* declaration never reaches: `open.ts` opens the plan and chains the saves, `project.ts` is a project's handle,
|
|
2384
|
+
* and `records.ts` maps rows to these types. Their imports of this file are type-only, so nothing here runs
|
|
2385
|
+
* before they do.
|
|
2386
|
+
*
|
|
2387
|
+
* **One writer.** Like the MCP server, a plan opened here assumes nothing else writes the same text while it is
|
|
2388
|
+
* open. Two handles on one plan would each save over the other.
|
|
2389
|
+
*/
|
|
2390
|
+
/** Open a plan from its YAML text. See `PlanOptions` for where changes go. */
|
|
1476
2391
|
function openPlan(options = {}) {
|
|
1477
|
-
|
|
2392
|
+
return open(options);
|
|
1478
2393
|
}
|
|
1479
|
-
export {
|
|
1480
|
-
openPlan
|
|
1481
|
-
};
|
|
2394
|
+
export { openPlan };
|