@wirecat/cli-core 0.603.0 → 0.605.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +92 -0
- package/dist/calendar/prepare.d.ts +4 -2
- package/dist/calendar/prepare.js +8 -8
- package/dist/cli/index.d.ts +1 -1
- package/dist/cli/index.js +1 -1
- package/dist/cli/messenger/contacts-command.js +3 -2
- package/dist/cli/messenger/doctor-command.js +14 -7
- package/dist/cli/messenger/search-answers.js +8 -1
- package/dist/cli/messenger/store-maintenance-command.d.ts +34 -2
- package/dist/cli/messenger/store-maintenance-command.js +31 -4
- package/dist/cli/model-catalogue-command.js +28 -2
- package/dist/cli/program.js +11 -2
- package/dist/cli/steps.js +9 -1
- package/dist/cli/store-recover.d.ts +10 -2
- package/dist/cli/store-recover.js +18 -4
- package/dist/domain/record-types.d.ts +61 -0
- package/dist/domain/record-types.js +26 -0
- package/dist/domain/records.d.ts +3 -5
- package/dist/domain/records.js +10 -13
- package/dist/entities/contact-activity.d.ts +4 -0
- package/dist/entities/contact-activity.js +1 -0
- package/dist/entities/contact-context.d.ts +20 -0
- package/dist/entities/contact-context.js +2 -0
- package/dist/entities/index.d.ts +22 -0
- package/dist/errors/failures.d.ts +17 -1
- package/dist/errors/failures.js +57 -1
- package/dist/errors/reasons.js +16 -0
- package/dist/mcp/tool.js +2 -1
- package/dist/runs/recording.js +13 -4
- package/dist/search/lucene/plain.d.ts +2 -1
- package/dist/search/lucene/plain.js +15 -1
- package/dist/services/deps.js +4 -6
- package/dist/services/index.d.ts +1 -1
- package/dist/services/link-scorers/chat-senders.d.ts +3 -2
- package/dist/services/link-scorers/chat-senders.js +7 -4
- package/dist/services/link-scorers/mail-thread.js +1 -0
- package/dist/services/link-scorers/member-chats.js +1 -0
- package/dist/services/link-scorers/member-dialog.d.ts +1 -1
- package/dist/services/link-scorers/member-dialog.js +4 -3
- package/dist/services/link-scorers/scan.d.ts +5 -2
- package/dist/services/link-scorers/scan.js +98 -53
- package/dist/services/link-scorers/shared.d.ts +2 -2
- package/dist/services/link-scorers/shared.js +7 -4
- package/dist/services/link-scorers/types.d.ts +3 -0
- package/dist/services/metadata.d.ts +1 -1
- package/dist/services/model-downloads.d.ts +5 -3
- package/dist/services/model-downloads.js +6 -6
- package/dist/services/notes-search.js +4 -2
- package/dist/services/person-context.d.ts +24 -7
- package/dist/services/person-context.js +45 -11
- package/dist/services/person-preparation.js +4 -5
- package/dist/services/search-all.d.ts +6 -0
- package/dist/services/search-all.js +16 -8
- package/dist/speech/install.d.ts +6 -7
- package/dist/speech/install.js +17 -10
- package/dist/store/damage.d.ts +3 -1
- package/dist/store/damage.js +19 -12
- package/dist/store/document-transfer/index.js +7 -0
- package/dist/store/index.d.ts +1 -0
- package/dist/store/index.js +1 -0
- package/dist/store/marks.d.ts +57 -0
- package/dist/store/marks.js +121 -0
- package/dist/store/project-transfer/preview.js +12 -7
- package/dist/store/recover.js +16 -1
- package/dist/store/sqlite/finance.d.ts +8 -1
- package/dist/store/sqlite/finance.js +10 -3
- package/dist/store/sqlite/note-dates.d.ts +6 -0
- package/dist/store/sqlite/note-dates.js +23 -0
- package/dist/store/sqlite/notes.d.ts +13 -0
- package/dist/store/sqlite/notes.js +6 -1
- package/dist/store/sqlite/open-store.js +4 -1
- package/dist/store/sqlite/own-identities.d.ts +1 -1
- package/dist/store/sqlite/own-identities.js +7 -5
- package/dist/store/sqlite/person-links.d.ts +5 -2
- package/dist/store/sqlite/person-links.js +24 -18
- package/dist/store/sqlite/person-separation.d.ts +5 -0
- package/dist/store/sqlite/person-separation.js +26 -0
- package/dist/store/sqlite/record-projectors.d.ts +44 -0
- package/dist/store/sqlite/record-projectors.js +72 -0
- package/dist/store/sqlite/records.js +12 -70
- package/dist/store/sqlite/transaction.js +2 -5
- package/dist/store/types.d.ts +5 -0
- package/package.json +3 -3
- package/parity.json +3 -1
|
@@ -15,6 +15,14 @@ import { MAX_SEARCH_OFFSET, searchStore } from "./messages-archive-search.js";
|
|
|
15
15
|
import { nearEligible } from "./messages-discovery.js";
|
|
16
16
|
import { notesScopeOf, RRF_K, searchNotes } from "./notes-search.js";
|
|
17
17
|
export const RESOURCES_SEARCHED = ["messages", "mail", "notes", "events", "crm"];
|
|
18
|
+
const refusal = (error, text) => {
|
|
19
|
+
const { reason, span } = (error.details ?? {});
|
|
20
|
+
const why = typeof reason === "string" ? reason : undefined;
|
|
21
|
+
const token = span && Number.isInteger(span.start) && Number.isInteger(span.end)
|
|
22
|
+
? text.slice(span.start, span.end).trim()
|
|
23
|
+
: "";
|
|
24
|
+
return { ...(why ? { why } : {}), ...(token ? { token } : {}) };
|
|
25
|
+
};
|
|
18
26
|
/** A query a resource cannot answer is skipped with its reason, never a failure of the whole search. */
|
|
19
27
|
const skippable = (error) => error instanceof CliError && (error.code === "validation_error" || error.code === "not_found");
|
|
20
28
|
/**
|
|
@@ -42,7 +50,8 @@ export const titleWords = (text) => {
|
|
|
42
50
|
node.kind === "predicate" &&
|
|
43
51
|
node.field === "text" &&
|
|
44
52
|
(node.operator === "term" || node.operator === "phrase")
|
|
45
|
-
?
|
|
53
|
+
? // A title holds "invoice", not the question mark of "invoice?".
|
|
54
|
+
node.value.replace(/\?+$/u, "") || node.value
|
|
46
55
|
: (() => {
|
|
47
56
|
throw new CliError("validation_error", "deals and leads are found by the words of their title only");
|
|
48
57
|
})());
|
|
@@ -164,13 +173,12 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
|
|
|
164
173
|
const held = fused.get(hit.locator);
|
|
165
174
|
if (held)
|
|
166
175
|
held.item.foundBy = ["words", "meaning"];
|
|
167
|
-
|
|
176
|
+
const vote = 1 / (RRF_K + rank + 1);
|
|
177
|
+
// As in notes: a question's any-word list holds most of what meaning finds, so a second vote would bury the rest.
|
|
168
178
|
if (held && discovers)
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
item: held?.item ?? itemOf(hit, ["meaning"]),
|
|
172
|
-
score: (held?.score ?? 0) + 1 / (RRF_K + rank + 1),
|
|
173
|
-
});
|
|
179
|
+
held.score = Math.max(held.score, vote);
|
|
180
|
+
else
|
|
181
|
+
fused.set(hit.locator, { item: held?.item ?? itemOf(hit, ["meaning"]), score: (held?.score ?? 0) + vote });
|
|
174
182
|
});
|
|
175
183
|
return [...fused.values()].sort((a, b) => b.score - a.score).map(({ item }) => item);
|
|
176
184
|
};
|
|
@@ -285,7 +293,7 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
|
|
|
285
293
|
catch (error) {
|
|
286
294
|
if (!skippable(error))
|
|
287
295
|
throw error;
|
|
288
|
-
skipped.push({ resource, code: error.code, reason: error.message });
|
|
296
|
+
skipped.push({ resource, code: error.code, reason: error.message, ...refusal(error, request.text) });
|
|
289
297
|
}
|
|
290
298
|
}
|
|
291
299
|
}
|
package/dist/speech/install.d.ts
CHANGED
|
@@ -14,15 +14,14 @@ export declare const installedBytes: (model: SpeechModel) => number;
|
|
|
14
14
|
export type Fetch = (url: string, init?: {
|
|
15
15
|
signal?: AbortSignal;
|
|
16
16
|
}) => Promise<Response>;
|
|
17
|
-
export
|
|
17
|
+
export interface InstallOptions {
|
|
18
18
|
fetch?: Fetch;
|
|
19
19
|
progress?: (line: string) => void;
|
|
20
|
+
/** Bytes in place so far, of all the files', a file already there counted whole; called as each chunk lands. */
|
|
21
|
+
bytes?: (done: number, total: number) => void;
|
|
20
22
|
verifyExisting?: boolean;
|
|
21
|
-
}
|
|
23
|
+
}
|
|
24
|
+
export declare const install: (model: SpeechModel, directory: string, { fetch: get, progress, bytes, verifyExisting }?: InstallOptions) => Promise<void>;
|
|
22
25
|
/** Each file not already in place, downloaded and checked against its sha256 before it takes its name. */
|
|
23
|
-
export declare const installFiles: (files: [ModelFile, string][], { fetch: get, progress,
|
|
24
|
-
fetch?: Fetch;
|
|
25
|
-
progress?: (line: string) => void;
|
|
26
|
-
verifyExisting?: boolean;
|
|
27
|
-
}) => Promise<void>;
|
|
26
|
+
export declare const installFiles: (files: [ModelFile, string][], { fetch: get, progress, bytes, verifyExisting }?: InstallOptions) => Promise<void>;
|
|
28
27
|
export declare const megabytes: (bytes: number) => string;
|
package/dist/speech/install.js
CHANGED
|
@@ -45,12 +45,12 @@ const sizeOf = (path) => {
|
|
|
45
45
|
}
|
|
46
46
|
};
|
|
47
47
|
export const installedBytes = (model) => model.files.reduce((sum, file) => sum + file.bytes, 0);
|
|
48
|
-
export const install = async (model, directory, { fetch: get = fetch, progress,
|
|
48
|
+
export const install = async (model, directory, { fetch: get = fetch, progress, bytes, verifyExisting } = {}) => {
|
|
49
49
|
mkdirSync(join(directory, model.id), { recursive: true, mode: 0o700 });
|
|
50
|
-
await installFiles(placed(model, directory), { fetch: get, progress, verifyExisting });
|
|
50
|
+
await installFiles(placed(model, directory), { fetch: get, progress, bytes, verifyExisting });
|
|
51
51
|
};
|
|
52
52
|
/** Each file not already in place, downloaded and checked against its sha256 before it takes its name. */
|
|
53
|
-
export const installFiles = async (files, { fetch: get = fetch, progress,
|
|
53
|
+
export const installFiles = async (files, { fetch: get = fetch, progress, bytes = () => { }, verifyExisting } = {}) => {
|
|
54
54
|
if (verifyExisting)
|
|
55
55
|
for (const [file, path] of files) {
|
|
56
56
|
if (sizeOf(path) !== undefined) {
|
|
@@ -63,18 +63,24 @@ export const installFiles = async (files, { fetch: get = fetch, progress, verify
|
|
|
63
63
|
}
|
|
64
64
|
}
|
|
65
65
|
}
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
66
|
+
const total = files.reduce((sum, [file]) => sum + file.bytes, 0);
|
|
67
|
+
const missing = files.filter(([file, path]) => sizeOf(path) !== file.bytes);
|
|
68
|
+
let done = total - missing.reduce((sum, [file]) => sum + file.bytes, 0);
|
|
69
|
+
bytes(done, total);
|
|
70
|
+
for (const [file, path] of missing) {
|
|
69
71
|
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
70
72
|
progress?.(`downloading ${file.name} (${megabytes(file.bytes)})`);
|
|
71
|
-
|
|
73
|
+
const before = done;
|
|
74
|
+
await fetchVerified(file, path, get, (received) => {
|
|
75
|
+
done = before + received;
|
|
76
|
+
bytes(done, total);
|
|
77
|
+
});
|
|
72
78
|
}
|
|
73
79
|
};
|
|
74
|
-
const fetchVerified = async (file, path, get) => {
|
|
80
|
+
const fetchVerified = async (file, path, get, received) => {
|
|
75
81
|
const stalled = watchdog(STALL_MS);
|
|
76
82
|
try {
|
|
77
|
-
await fetchInto(file, path, get, stalled);
|
|
83
|
+
await fetchInto(file, path, get, stalled, received);
|
|
78
84
|
}
|
|
79
85
|
catch (error) {
|
|
80
86
|
if (stalled.signal.aborted) {
|
|
@@ -86,7 +92,7 @@ const fetchVerified = async (file, path, get) => {
|
|
|
86
92
|
stalled.stop();
|
|
87
93
|
}
|
|
88
94
|
};
|
|
89
|
-
const fetchInto = async (file, path, get, stalled) => {
|
|
95
|
+
const fetchInto = async (file, path, get, stalled, received) => {
|
|
90
96
|
const response = await get(file.url, { signal: stalled.signal });
|
|
91
97
|
if (!response.ok || !response.body) {
|
|
92
98
|
await response.body?.cancel();
|
|
@@ -104,6 +110,7 @@ const fetchInto = async (file, path, get, stalled) => {
|
|
|
104
110
|
return;
|
|
105
111
|
}
|
|
106
112
|
hash.update(chunk);
|
|
113
|
+
received(bytes);
|
|
107
114
|
done(null, chunk);
|
|
108
115
|
},
|
|
109
116
|
});
|
package/dist/store/damage.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { StoreHealth } from "./health.js";
|
|
2
|
+
import type { DamageMark } from "./marks.js";
|
|
2
3
|
/**
|
|
3
4
|
* What a damaged store means, in the owner's words: one structure the CLIs render and the desktop app can show as it
|
|
4
5
|
* is. Built from a health check only, so it never reads the damaged file again.
|
|
@@ -16,4 +17,5 @@ export interface DamageExplanation {
|
|
|
16
17
|
* vectors, which a search by meaning computes again for any text that has none.
|
|
17
18
|
*/
|
|
18
19
|
export declare const isDerivedTable: (table: string, searchIndexes: readonly string[]) => boolean;
|
|
19
|
-
|
|
20
|
+
/** `mark`: a run saw the damage; the quick check reads too little to see it, so it alone can make a store damaged. */
|
|
21
|
+
export declare const explainDamage: (health: StoreHealth, command: string, mark?: DamageMark | null) => DamageExplanation | null;
|
package/dist/store/damage.js
CHANGED
|
@@ -8,8 +8,10 @@ export const isDerivedTable = (table, searchIndexes) => DERIVED.has(table) ||
|
|
|
8
8
|
table.startsWith("vector_index_") ||
|
|
9
9
|
searchIndexes.some((index) => table === index || table.startsWith(`${index}_`));
|
|
10
10
|
const WIRECAT_UNITS = ["memo-*", "mail-*", "tg-*", "max-*", "wirecat-*"];
|
|
11
|
-
|
|
12
|
-
|
|
11
|
+
const seen = (mark) => `\`${mark.command}\` found the store damaged at ${mark.at} (${mark.error})`;
|
|
12
|
+
/** `mark`: a run saw the damage; the quick check reads too little to see it, so it alone can make a store damaged. */
|
|
13
|
+
export const explainDamage = (health, command, mark = null) => {
|
|
14
|
+
if (health.ok && !mark)
|
|
13
15
|
return null;
|
|
14
16
|
const indexNames = (health.searchIndexes ?? []).map((index) => index.name);
|
|
15
17
|
const badIndexes = (health.searchIndexes ?? []).filter((index) => !index.ok).map((index) => index.name);
|
|
@@ -18,14 +20,17 @@ export const explainDamage = (health, command) => {
|
|
|
18
20
|
const derived = [...new Set([...tables.filter((table) => isDerivedTable(table, indexNames)), ...badIndexes])];
|
|
19
21
|
const unopened = health.error !== undefined;
|
|
20
22
|
const json = (health.invalidJson ?? []).map(({ table, column }) => `${table}.${column}`);
|
|
21
|
-
const
|
|
22
|
-
?
|
|
23
|
-
:
|
|
24
|
-
?
|
|
25
|
-
:
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
23
|
+
const checked = health.ok
|
|
24
|
+
? `${seen(mark)}; the quick check reads too little to see it, and a deep check that passes clears it`
|
|
25
|
+
: unopened
|
|
26
|
+
? `the store file cannot be opened: ${health.error}`
|
|
27
|
+
: health.checked === "quick"
|
|
28
|
+
? "the store file's header or schema is damaged"
|
|
29
|
+
: `the store file is damaged: ${health.problems ?? 0} problems` +
|
|
30
|
+
(sources.length ? ` in the data of ${named(sources)}` : "") +
|
|
31
|
+
(derived.length ? `${sources.length ? ", and" : " in"} the search data of ${named(derived)}` : "") +
|
|
32
|
+
(json.length ? `; values that are not valid JSON in ${named(json)}` : "");
|
|
33
|
+
const what = mark && !health.ok ? `${checked}; ${seen(mark)}` : checked;
|
|
29
34
|
const impact = [
|
|
30
35
|
...(sources.length
|
|
31
36
|
? [`some rows of ${named(sources)} cannot be read; a recovery keeps every row it can read and names the rest`]
|
|
@@ -36,7 +41,9 @@ export const explainDamage = (health, command) => {
|
|
|
36
41
|
...(json.length
|
|
37
42
|
? [`a read of a row with a broken JSON value fails ("malformed JSON"); a recovery clears those values`]
|
|
38
43
|
: []),
|
|
39
|
-
|
|
44
|
+
mark
|
|
45
|
+
? "reads that do not touch a damaged page work; every command that writes the store refuses until it is recovered"
|
|
46
|
+
: "reads that do not touch a damaged page work; a write that touches one fails until the store is recovered",
|
|
40
47
|
];
|
|
41
48
|
return {
|
|
42
49
|
what,
|
|
@@ -49,7 +56,7 @@ export const explainDamage = (health, command) => {
|
|
|
49
56
|
`journalctl --user ${WIRECAT_UNITS.map((unit) => `-u '${unit}'`).join(" ")} --since -14d | grep -i -e malformed -e corrupt -e 'disk full'`,
|
|
50
57
|
"journalctl -k --since -14d | grep -i -e 'I/O error' -e nvme -e ata",
|
|
51
58
|
`df -h ${health.path.replace(/\/[^/]*$/, "")}`,
|
|
52
|
-
...(health.checked === "quick" ? [`${command} store recover`] : []),
|
|
59
|
+
...(health.checked === "quick" || health.ok ? [`${command} store recover`] : []),
|
|
53
60
|
],
|
|
54
61
|
impact,
|
|
55
62
|
externalUnaffected: "only this computer's copy is damaged: Telegram, MAX, the mail servers and Google Drive keep their own data, " +
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { realpathSync, statSync } from "node:fs";
|
|
2
2
|
import { resolve } from "node:path";
|
|
3
3
|
import { CliError } from "@wirecat/cli-base";
|
|
4
|
+
import { damagedFile } from "../../errors/failures.js";
|
|
4
5
|
import { MIGRATIONS, migrate } from "../migrations.js";
|
|
5
6
|
import { applyTransfer } from "../sqlite/document-transfer/apply.js";
|
|
6
7
|
import { planTransfer } from "../sqlite/document-transfer/plan.js";
|
|
@@ -75,6 +76,9 @@ const openPreviewTarget = async (path) => {
|
|
|
75
76
|
};
|
|
76
77
|
export const previewDocumentTransfer = async (options) => {
|
|
77
78
|
const location = locations(options);
|
|
79
|
+
return damagedFile([location.source, location.destination], () => previewWith(location, options));
|
|
80
|
+
};
|
|
81
|
+
const previewWith = async (location, options) => {
|
|
78
82
|
const source = await openSource(location.source);
|
|
79
83
|
try {
|
|
80
84
|
const target = await openPreviewTarget(location.destination);
|
|
@@ -93,6 +97,9 @@ export const applyDocumentTransfer = async (options) => {
|
|
|
93
97
|
if (!/^[a-f0-9]{64}$/.test(options.expected_fingerprint))
|
|
94
98
|
throw new CliError("validation_error", "apply requires the fingerprint returned by a transfer preview");
|
|
95
99
|
const location = locations(options);
|
|
100
|
+
return damagedFile([location.source, location.destination], () => applyWith(location, options));
|
|
101
|
+
};
|
|
102
|
+
const applyWith = async (location, options) => {
|
|
96
103
|
const source = await openSource(location.source);
|
|
97
104
|
try {
|
|
98
105
|
const snapshot = transferSnapshot(source.database, options.collection);
|
package/dist/store/index.d.ts
CHANGED
|
@@ -20,6 +20,7 @@ export { EVIDENCE_FINDINGS_KIND, type EvidenceFindingsBatch, type EvidenceFindin
|
|
|
20
20
|
export { type DamagedTable, type InvalidJson, QUICK_HEALTH_CHECKS, type SearchIndexHealth, type StoreHealth, storeHealth, } from "./health.js";
|
|
21
21
|
export { ORGANIZATIONS_QUERY, organization, PROJECTS_QUERY, project, REMINDERS_QUERY, reminder, } from "./knowledge-query.js";
|
|
22
22
|
export { MAIL_FINDINGS_KIND, type MailFindingsBatch, type MailFindingsCheck, type MailFindingsStore, } from "./mail-findings.js";
|
|
23
|
+
export { clearDamageMark, type DamageMark, damageMarkPath, type HealthMark, healthMarkPath, markStoreDamaged, readDamageMark, readHealthMark, recordDeepCheck, } from "./marks.js";
|
|
23
24
|
export type { MeetingFindingsBatch, MeetingFindingsStore } from "./meeting-findings.js";
|
|
24
25
|
export { MIGRATIONS, type Migration, migrate } from "./migrations.js";
|
|
25
26
|
export { openCache } from "./open.js";
|
package/dist/store/index.js
CHANGED
|
@@ -12,6 +12,7 @@ export { EVIDENCE_FINDINGS_KIND, validateEvidenceFindings, } from "./evidence-fi
|
|
|
12
12
|
export { QUICK_HEALTH_CHECKS, storeHealth, } from "./health.js";
|
|
13
13
|
export { ORGANIZATIONS_QUERY, organization, PROJECTS_QUERY, project, REMINDERS_QUERY, reminder, } from "./knowledge-query.js";
|
|
14
14
|
export { MAIL_FINDINGS_KIND, } from "./mail-findings.js";
|
|
15
|
+
export { clearDamageMark, damageMarkPath, healthMarkPath, markStoreDamaged, readDamageMark, readHealthMark, recordDeepCheck, } from "./marks.js";
|
|
15
16
|
export { MIGRATIONS, migrate } from "./migrations.js";
|
|
16
17
|
export { openCache } from "./open.js";
|
|
17
18
|
export { storePath } from "./path.js";
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type { StoreHealth } from "./health.js";
|
|
2
|
+
/**
|
|
3
|
+
* Both marks live beside the store, not in it: the store may be the file that cannot be read. Each holds no content,
|
|
4
|
+
* only times, command names and SQLite's own message.
|
|
5
|
+
*/
|
|
6
|
+
export declare const damageMarkPath: (store: string) => string;
|
|
7
|
+
export declare const healthMarkPath: (store: string) => string;
|
|
8
|
+
/** A run saw SQLite say the store is damaged. Every writable open refuses while it names the file in place. */
|
|
9
|
+
export interface DamageMark {
|
|
10
|
+
at: string;
|
|
11
|
+
command: string;
|
|
12
|
+
cli_version?: string;
|
|
13
|
+
run_id?: string;
|
|
14
|
+
error: string;
|
|
15
|
+
/** The file it was seen in: a store restored, reset or recovered since is another file, and the mark is stale. */
|
|
16
|
+
inode: number;
|
|
17
|
+
}
|
|
18
|
+
/** The newest deep check of the store, and the time of the newest one that passed: the last known good. */
|
|
19
|
+
export interface HealthMark {
|
|
20
|
+
checked_at: string;
|
|
21
|
+
ok: boolean;
|
|
22
|
+
problems: number;
|
|
23
|
+
schema: number | null;
|
|
24
|
+
cli: string;
|
|
25
|
+
cli_version?: string;
|
|
26
|
+
last_ok_at: string | null;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Leaves the damage mark when `error` is SQLite saying the store is damaged; the first sighting is kept. Never
|
|
30
|
+
* throws: the failure being reported matters more than the mark.
|
|
31
|
+
*/
|
|
32
|
+
export declare const markStoreDamaged: (error: unknown, { store, command, version, runId, now, }: {
|
|
33
|
+
store: string;
|
|
34
|
+
command: string;
|
|
35
|
+
version?: string;
|
|
36
|
+
runId?: string;
|
|
37
|
+
now?: () => number;
|
|
38
|
+
}) => boolean;
|
|
39
|
+
/** The mark, or null; a mark left by another file at this path is removed. An unreadable mark still counts. */
|
|
40
|
+
export declare const readDamageMark: (store: string) => DamageMark | null;
|
|
41
|
+
export declare const clearDamageMark: (store: string) => void;
|
|
42
|
+
/** Thrown by a writable open of a store a run found damaged, so timers fail fast instead of writing into it. */
|
|
43
|
+
export declare const refuseDamagedStore: (store: string, cli?: string) => void;
|
|
44
|
+
export declare const readHealthMark: (store: string) => HealthMark | null;
|
|
45
|
+
/**
|
|
46
|
+
* Records a deep check of the store. One that passed also removes the damage mark: the file reads whole. Returns the
|
|
47
|
+
* mark it replaced, whose `last_ok_at` is the last known good before this check, and the damage mark it removed.
|
|
48
|
+
*/
|
|
49
|
+
export declare const recordDeepCheck: (store: string, health: Pick<StoreHealth, "ok" | "problems">, { cli, version, schema, now, }: {
|
|
50
|
+
cli: string;
|
|
51
|
+
version?: string;
|
|
52
|
+
schema: number | null;
|
|
53
|
+
now?: () => number;
|
|
54
|
+
}) => {
|
|
55
|
+
previous: HealthMark | null;
|
|
56
|
+
cleared: DamageMark | null;
|
|
57
|
+
};
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { CliError } from "@wirecat/cli-base";
|
|
3
|
+
import { isCliFailure, isStoreDamage } from "../errors/failures.js";
|
|
4
|
+
import { refuseOwnerStoreInTests } from "./path.js";
|
|
5
|
+
/**
|
|
6
|
+
* Both marks live beside the store, not in it: the store may be the file that cannot be read. Each holds no content,
|
|
7
|
+
* only times, command names and SQLite's own message.
|
|
8
|
+
*/
|
|
9
|
+
export const damageMarkPath = (store) => `${store}.damaged.json`;
|
|
10
|
+
export const healthMarkPath = (store) => `${store}.health.json`;
|
|
11
|
+
const inodeOf = (store) => statSync(store, { throwIfNoEntry: false })?.ino;
|
|
12
|
+
const readJson = (path) => {
|
|
13
|
+
try {
|
|
14
|
+
return JSON.parse(readFileSync(path, "utf8"));
|
|
15
|
+
}
|
|
16
|
+
catch (error) {
|
|
17
|
+
if (error.code === "ENOENT")
|
|
18
|
+
return null;
|
|
19
|
+
throw error;
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
const ownerStoreInTests = (store) => {
|
|
23
|
+
try {
|
|
24
|
+
refuseOwnerStoreInTests(store);
|
|
25
|
+
return false;
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return true;
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
/** SQLite's own failure under a `store.damaged` CliError, or the error itself; the mark's own refusal has none. */
|
|
32
|
+
const sqliteFailure = (error) => isCliFailure(error) && error.details?.reason === "store.damaged" ? error.cause : error;
|
|
33
|
+
/**
|
|
34
|
+
* Leaves the damage mark when `error` is SQLite saying the store is damaged; the first sighting is kept. Never
|
|
35
|
+
* throws: the failure being reported matters more than the mark.
|
|
36
|
+
*/
|
|
37
|
+
export const markStoreDamaged = (error, { store, command, version, runId, now = Date.now, }) => {
|
|
38
|
+
const failure = sqliteFailure(error);
|
|
39
|
+
if (!isStoreDamage(failure) || ownerStoreInTests(store))
|
|
40
|
+
return false;
|
|
41
|
+
const inode = inodeOf(store);
|
|
42
|
+
if (inode === undefined)
|
|
43
|
+
return false;
|
|
44
|
+
const mark = {
|
|
45
|
+
at: new Date(now()).toISOString(),
|
|
46
|
+
command,
|
|
47
|
+
...(version ? { cli_version: version } : {}),
|
|
48
|
+
...(runId ? { run_id: runId } : {}),
|
|
49
|
+
error: failure.message.slice(0, 500),
|
|
50
|
+
inode,
|
|
51
|
+
};
|
|
52
|
+
try {
|
|
53
|
+
writeFileSync(damageMarkPath(store), `${JSON.stringify(mark, null, 2)}\n`, { flag: "wx", mode: 0o600 });
|
|
54
|
+
return true;
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
return false;
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
/** The mark, or null; a mark left by another file at this path is removed. An unreadable mark still counts. */
|
|
61
|
+
export const readDamageMark = (store) => {
|
|
62
|
+
const path = damageMarkPath(store);
|
|
63
|
+
let mark;
|
|
64
|
+
try {
|
|
65
|
+
mark = readJson(path);
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
return { at: "unknown", command: "unknown", error: `${path} cannot be read`, inode: inodeOf(store) ?? 0 };
|
|
69
|
+
}
|
|
70
|
+
if (mark === null)
|
|
71
|
+
return null;
|
|
72
|
+
if (mark.inode !== inodeOf(store)) {
|
|
73
|
+
clearDamageMark(store);
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
return mark;
|
|
77
|
+
};
|
|
78
|
+
export const clearDamageMark = (store) => rmSync(damageMarkPath(store), { force: true });
|
|
79
|
+
/** Thrown by a writable open of a store a run found damaged, so timers fail fast instead of writing into it. */
|
|
80
|
+
export const refuseDamagedStore = (store, cli) => {
|
|
81
|
+
const mark = readDamageMark(store);
|
|
82
|
+
if (!mark)
|
|
83
|
+
return;
|
|
84
|
+
throw new CliError("configuration_error", `the store was found damaged at ${mark.at} by \`${mark.command}\` (${mark.error}), so nothing writes to it until ` +
|
|
85
|
+
`it is recovered; \`${cli ?? "<cli>"} store recover\` says what is damaged and what to do`, { reason: "store.damaged" });
|
|
86
|
+
};
|
|
87
|
+
export const readHealthMark = (store) => {
|
|
88
|
+
try {
|
|
89
|
+
return readJson(healthMarkPath(store));
|
|
90
|
+
}
|
|
91
|
+
catch {
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
/**
|
|
96
|
+
* Records a deep check of the store. One that passed also removes the damage mark: the file reads whole. Returns the
|
|
97
|
+
* mark it replaced, whose `last_ok_at` is the last known good before this check, and the damage mark it removed.
|
|
98
|
+
*/
|
|
99
|
+
export const recordDeepCheck = (store, health, { cli, version, schema, now = Date.now, }) => {
|
|
100
|
+
const previous = readHealthMark(store);
|
|
101
|
+
if (ownerStoreInTests(store))
|
|
102
|
+
return { previous, cleared: null };
|
|
103
|
+
const checkedAt = new Date(now()).toISOString();
|
|
104
|
+
const mark = {
|
|
105
|
+
checked_at: checkedAt,
|
|
106
|
+
ok: health.ok,
|
|
107
|
+
problems: health.problems ?? 0,
|
|
108
|
+
schema,
|
|
109
|
+
cli,
|
|
110
|
+
...(version ? { cli_version: version } : {}),
|
|
111
|
+
last_ok_at: health.ok ? checkedAt : (previous?.last_ok_at ?? null),
|
|
112
|
+
};
|
|
113
|
+
const cleared = health.ok ? readDamageMark(store) : null;
|
|
114
|
+
try {
|
|
115
|
+
writeFileSync(healthMarkPath(store), `${JSON.stringify(mark, null, 2)}\n`, { mode: 0o600 });
|
|
116
|
+
}
|
|
117
|
+
catch { }
|
|
118
|
+
if (cleared)
|
|
119
|
+
clearDamageMark(store);
|
|
120
|
+
return { previous, cleared };
|
|
121
|
+
};
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { CliError } from "@wirecat/cli-base";
|
|
2
|
+
import { damagedFile } from "../../errors/failures.js";
|
|
2
3
|
import { openStoreContext } from "../sqlite/open-store.js";
|
|
3
4
|
import { SnapshotBudget } from "../sqlite/project-transfer/budget.js";
|
|
4
5
|
import { previewAnnotationSnapshot } from "../sqlite/project-transfer/preview.js";
|
|
@@ -19,11 +20,15 @@ export const previewProjectAnnotationSnapshot = async (options) => {
|
|
|
19
20
|
!Number.isSafeInteger(Number(options.project.slice(8))))
|
|
20
21
|
throw new CliError("validation_error", "project preview project is a project:<safe integer id> reference");
|
|
21
22
|
const budget = new SnapshotBudget(options.maxReadBytes ?? 4 * 1024 * 1024);
|
|
22
|
-
const
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
23
|
+
const target = options.target;
|
|
24
|
+
const project = options.project;
|
|
25
|
+
return damagedFile([target], async () => {
|
|
26
|
+
const context = await openStoreContext({ path: target, env: options.env, readOnly: true });
|
|
27
|
+
try {
|
|
28
|
+
return previewAnnotationSnapshot(context.database, Number(project.slice(8)), snapshot, options.bindings, budget);
|
|
29
|
+
}
|
|
30
|
+
finally {
|
|
31
|
+
context.database.close();
|
|
32
|
+
}
|
|
33
|
+
});
|
|
29
34
|
};
|
package/dist/store/recover.js
CHANGED
|
@@ -4,7 +4,10 @@ import { basename, dirname, join } from "node:path";
|
|
|
4
4
|
import { Transform } from "node:stream";
|
|
5
5
|
import { CliError } from "@wirecat/cli-base";
|
|
6
6
|
import { holdersOf } from "../background/processes.js";
|
|
7
|
+
import { isStoreDamage } from "../errors/failures.js";
|
|
8
|
+
import { fileSchemaOf } from "./compatibility.js";
|
|
7
9
|
import { fts5Tables, invalidJson, storeHealth } from "./health.js";
|
|
10
|
+
import { recordDeepCheck } from "./marks.js";
|
|
8
11
|
import { migrate } from "./migrations.js";
|
|
9
12
|
import { resetAttachmentWords } from "./sqlite/attachment-texts.js";
|
|
10
13
|
import { involvementStoreOver } from "./sqlite/involvements.js";
|
|
@@ -393,7 +396,16 @@ const recoverLocked = async ({ path, command, version, sqlite3, now, note, copy,
|
|
|
393
396
|
};
|
|
394
397
|
try {
|
|
395
398
|
const dataVersion = () => Number(watch.prepare("PRAGMA data_version").get()?.data_version);
|
|
396
|
-
|
|
399
|
+
let rowsBefore;
|
|
400
|
+
try {
|
|
401
|
+
rowsBefore = tableRows(watch);
|
|
402
|
+
}
|
|
403
|
+
catch (error) {
|
|
404
|
+
if (!isStoreDamage(error))
|
|
405
|
+
throw error;
|
|
406
|
+
throw new CliError("configuration_error", "the store file's header or schema is damaged, so its tables cannot be listed and it cannot be recovered; " +
|
|
407
|
+
"the file was left as it was", { reason: "store.unreadable" });
|
|
408
|
+
}
|
|
397
409
|
const before = { data: dataVersion(), inode: statSync(path).ino };
|
|
398
410
|
const stamp = new Date(now()).toISOString().replace(/[:.]/g, "-");
|
|
399
411
|
const target = `${path}.recovering-${stamp}`;
|
|
@@ -422,6 +434,7 @@ const recoverLocked = async ({ path, command, version, sqlite3, now, note, copy,
|
|
|
422
434
|
let dangling;
|
|
423
435
|
let json;
|
|
424
436
|
let fetch;
|
|
437
|
+
let schema;
|
|
425
438
|
try {
|
|
426
439
|
kept = tableRows(opened.database);
|
|
427
440
|
migrate(opened.database, { command, ...(version ? { version } : {}) });
|
|
@@ -431,6 +444,7 @@ const recoverLocked = async ({ path, command, version, sqlite3, now, note, copy,
|
|
|
431
444
|
note("looking for rows that point at rows that were lost");
|
|
432
445
|
dangling = danglingRows(opened.database);
|
|
433
446
|
fetch = mailToFetch(opened.database);
|
|
447
|
+
schema = fileSchemaOf(opened.database).version;
|
|
434
448
|
opened.database.exec("PRAGMA wal_checkpoint(TRUNCATE)");
|
|
435
449
|
}
|
|
436
450
|
catch (error) {
|
|
@@ -459,6 +473,7 @@ const recoverLocked = async ({ path, command, version, sqlite3, now, note, copy,
|
|
|
459
473
|
for (const suffix of STORE_PARTS)
|
|
460
474
|
if (existsSync(`${target}${suffix}`))
|
|
461
475
|
renameSync(`${target}${suffix}`, `${path}${suffix}`);
|
|
476
|
+
recordDeepCheck(path, health, { cli: command, ...(version ? { version } : {}), schema, now });
|
|
462
477
|
const lost = Object.entries(rowsBefore)
|
|
463
478
|
.map(([table, before]) => ({ table, before, read: read[table] ?? 0, kept: kept[table] ?? 0 }))
|
|
464
479
|
.filter(({ before, read, kept }) => before === null || before > kept || read > kept);
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type FinanceReview, type InvoiceDirection, type InvoiceStatus, type MoneyDirection } from "../../domain/finance.js";
|
|
2
2
|
import { type Money } from "../../domain/money.js";
|
|
3
|
+
import { RECORD_TYPES } from "../../domain/record-types.js";
|
|
3
4
|
import { type Decider } from "../decisions.js";
|
|
4
5
|
import { type Actor, type ProposedByFilter } from "./actors.js";
|
|
5
6
|
import { type Author } from "./memories.js";
|
|
@@ -207,6 +208,12 @@ export interface FinanceStore {
|
|
|
207
208
|
}>;
|
|
208
209
|
}
|
|
209
210
|
type Row = Record<string, unknown>;
|
|
211
|
+
/** The types `decide` settles money for; other proposal types get their own route. */
|
|
212
|
+
declare const FINANCE_TYPES: readonly ["invoice", "payment"];
|
|
213
|
+
type FinanceType = (typeof FINANCE_TYPES)[number];
|
|
214
|
+
type FinanceTable = (typeof RECORD_TYPES)[FinanceType]["table"];
|
|
215
|
+
/** One article, for the first prefix only: `an invoice: or payment:`. */
|
|
216
|
+
export declare const prefixesText: (types: readonly string[]) => string;
|
|
210
217
|
export declare const refuse: (message: string, reason: string, code?: "validation_error" | "permission_error") => never;
|
|
211
218
|
export declare const oneOf: <T extends string>(value: unknown, allowed: readonly T[], what: string) => T;
|
|
212
219
|
export declare const text: (value: unknown, what: string, limit: number) => string | null;
|
|
@@ -242,7 +249,7 @@ export declare const reviewedRowsOver: (context: StoreContext) => {
|
|
|
242
249
|
evidence: string[];
|
|
243
250
|
}>) => void;
|
|
244
251
|
ownerOnly: (by: Author, what: string) => void;
|
|
245
|
-
keepDecision: (table:
|
|
252
|
+
keepDecision: (table: FinanceTable | "orders", id: number, by: Decider, reason?: string) => void;
|
|
246
253
|
};
|
|
247
254
|
type FinanceOperations = {
|
|
248
255
|
[K in keyof FinanceStore]: FinanceStore[K] extends (...args: infer A) => Promise<infer R> ? (...args: A) => R : never;
|
|
@@ -1,11 +1,18 @@
|
|
|
1
1
|
import { CliError } from "@wirecat/cli-base";
|
|
2
2
|
import { FINANCE_REVIEWS, INVOICE_DIRECTIONS, INVOICE_STATUSES, invoiceTitle, MONEY_DIRECTIONS, paymentEntryTitle, settledStatus, } from "../../domain/finance.js";
|
|
3
3
|
import { currencyOf, formatDecimal, lineUnits, minorUnits, moneyLabel, moneyOf, quantityOf, scaleOf, } from "../../domain/money.js";
|
|
4
|
+
import { RECORD_TYPES } from "../../domain/record-types.js";
|
|
4
5
|
import { assertMayDecide, botKey, deciderAuthor } from "../decisions.js";
|
|
5
6
|
import { proposedBySql, proposerOf } from "./actors.js";
|
|
6
7
|
import { authorActor, authorOf, evidenceOf, linkEvidence, projectId, projectOf, subjectOf, } from "./memories.js";
|
|
7
8
|
import { requiredThing } from "./notes.js";
|
|
8
9
|
import { write } from "./transaction.js";
|
|
10
|
+
/** The types `decide` settles money for; other proposal types get their own route. */
|
|
11
|
+
const FINANCE_TYPES = ["invoice", "payment"];
|
|
12
|
+
const isFinanceType = (type) => FINANCE_TYPES.includes(type);
|
|
13
|
+
const article = (word) => (/^[aeiou]/.test(word) ? "an" : "a");
|
|
14
|
+
/** One article, for the first prefix only: `an invoice: or payment:`. */
|
|
15
|
+
export const prefixesText = (types) => `${article(types[0] ?? "")} ${types.map((type) => `${type}:`).join(" or ")}`;
|
|
9
16
|
export const refuse = (message, reason, code = "validation_error") => {
|
|
10
17
|
throw new CliError(code, message, { reason });
|
|
11
18
|
};
|
|
@@ -287,10 +294,10 @@ export const financeOperationsOver = (context) => {
|
|
|
287
294
|
};
|
|
288
295
|
const decide = (reference, by, reason, confirm) => {
|
|
289
296
|
const thing = requiredThing(database, reference, "the proposal");
|
|
290
|
-
if (thing.type
|
|
291
|
-
return refuse(`${reference} is not
|
|
297
|
+
if (!isFinanceType(thing.type))
|
|
298
|
+
return refuse(`${reference} is not ${prefixesText(FINANCE_TYPES)}`, "finance.ref");
|
|
292
299
|
const type = thing.type;
|
|
293
|
-
const table = type
|
|
300
|
+
const table = RECORD_TYPES[type].table;
|
|
294
301
|
const row = rowOf(reference, type);
|
|
295
302
|
const ref = `${type}:${row.id}`;
|
|
296
303
|
assertMayDecide({ id: ref, proposedBy: proposerOf(database, row.author_type, row.author_id), ownerOnly: true }, by, context.decisions);
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { CacheDatabase } from "../driver.js";
|
|
2
|
+
/** `store.notes.dateFileNotes` for a folder's account row: only the time column moves, so it is not an edit. */
|
|
3
|
+
export declare const dateFileNotes: (database: CacheDatabase, folder: number, dates: {
|
|
4
|
+
path: string;
|
|
5
|
+
modifiedAt: string;
|
|
6
|
+
}[]) => number;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { CliError } from "@wirecat/cli-base";
|
|
2
|
+
/** `store.notes.dateFileNotes` for a folder's account row: only the time column moves, so it is not an edit. */
|
|
3
|
+
export const dateFileNotes = (database, folder, dates) => {
|
|
4
|
+
const fileAt = database.prepare("SELECT id, document_id FROM files WHERE account_id = ? AND external_id = ? AND kind <> 'folder' AND deleted_at IS NULL");
|
|
5
|
+
const legacy = database.prepare("SELECT id FROM documents WHERE account_id = ? AND external_id = ? AND deleted_at IS NULL");
|
|
6
|
+
const dateFile = database.prepare("UPDATE files SET external_updated_at = ? WHERE id = ? AND external_updated_at IS NOT ?");
|
|
7
|
+
// Only the document's own file dates the document; a copy in another folder dates its file row.
|
|
8
|
+
const dateDocument = database.prepare("UPDATE documents SET external_updated_at = ? WHERE id = ? AND account_id = ? AND external_id = ? " +
|
|
9
|
+
"AND external_updated_at IS NOT ?");
|
|
10
|
+
let changed = 0;
|
|
11
|
+
for (const { path, modifiedAt } of dates) {
|
|
12
|
+
const time = Date.parse(modifiedAt);
|
|
13
|
+
if (!Number.isFinite(time))
|
|
14
|
+
throw new CliError("validation_error", `${modifiedAt} is not a time`);
|
|
15
|
+
const place = fileAt.get(folder, path);
|
|
16
|
+
const id = place?.document_id ?? legacy.get(folder, path)?.id;
|
|
17
|
+
const file = place ? dateFile.run(time, Number(place.id), time).changes : 0;
|
|
18
|
+
const document = id == null ? 0 : dateDocument.run(time, Number(id), folder, path, time).changes;
|
|
19
|
+
if (file + document > 0)
|
|
20
|
+
changed++;
|
|
21
|
+
}
|
|
22
|
+
return changed;
|
|
23
|
+
};
|
|
@@ -42,6 +42,11 @@ export interface Note {
|
|
|
42
42
|
contentHash: string | null;
|
|
43
43
|
revision: number;
|
|
44
44
|
exportPath: string | null;
|
|
45
|
+
/**
|
|
46
|
+
* When the source dates the note: a local file's front matter date or modification time, a Drive file's last
|
|
47
|
+
* edit; `null` when the source gave none. `createdAt` and `updatedAt` are the store's own times.
|
|
48
|
+
*/
|
|
49
|
+
modifiedAt: string | null;
|
|
45
50
|
createdAt: string;
|
|
46
51
|
updatedAt: string;
|
|
47
52
|
deletedAt: string | null;
|
|
@@ -127,6 +132,14 @@ export interface NotesStore extends NoteSearch, ImportedDocuments {
|
|
|
127
132
|
}>;
|
|
128
133
|
/** Moves a file note to a new path in its folder, keeping its id, links and tags; a gone note at `to` is dropped. */
|
|
129
134
|
renameFileNote(folderId: string, from: string, to: string): Promise<Note>;
|
|
135
|
+
/**
|
|
136
|
+
* Sets the time the source dates each note at these paths (ISO 8601), the note's `modifiedAt`, without counting
|
|
137
|
+
* as an edit: text, revision and `updatedAt` stay. Answers how many notes it changed.
|
|
138
|
+
*/
|
|
139
|
+
dateFileNotes(folderId: string, dates: {
|
|
140
|
+
path: string;
|
|
141
|
+
modifiedAt: string;
|
|
142
|
+
}[]): Promise<number>;
|
|
130
143
|
/** Marks the folder's notes at these paths deleted; answers how many were live. */
|
|
131
144
|
deleteFileNotes(folderId: string, paths: string[]): Promise<number>;
|
|
132
145
|
/** A note about the things named, the first of them its subject; about nothing, a note to self. */
|