@kitkat-vn/kitcode 0.2.0-staging.10 → 0.2.0-staging.13

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.
@@ -0,0 +1,93 @@
1
+ Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono)
2
+
3
+ This Font Software is licensed under the SIL Open Font License, Version 1.1.
4
+
5
+ This license is copied below, and is also available with a FAQ at: https://scripts.sil.org/OFL
6
+
7
+
8
+ -----------------------------------------------------------
9
+ SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
10
+ -----------------------------------------------------------
11
+
12
+ PREAMBLE
13
+ The goals of the Open Font License (OFL) are to stimulate worldwide
14
+ development of collaborative font projects, to support the font creation
15
+ efforts of academic and linguistic communities, and to provide a free and
16
+ open framework in which fonts may be shared and improved in partnership
17
+ with others.
18
+
19
+ The OFL allows the licensed fonts to be used, studied, modified and
20
+ redistributed freely as long as they are not sold by themselves. The
21
+ fonts, including any derivative works, can be bundled, embedded,
22
+ redistributed and/or sold with any software provided that any reserved
23
+ names are not used by derivative works. The fonts and derivatives,
24
+ however, cannot be released under any other type of license. The
25
+ requirement for fonts to remain under this license does not apply
26
+ to any document created using the fonts or their derivatives.
27
+
28
+ DEFINITIONS
29
+ "Font Software" refers to the set of files released by the Copyright
30
+ Holder(s) under this license and clearly marked as such. This may
31
+ include source files, build scripts and documentation.
32
+
33
+ "Reserved Font Name" refers to any names specified as such after the
34
+ copyright statement(s).
35
+
36
+ "Original Version" refers to the collection of Font Software components as
37
+ distributed by the Copyright Holder(s).
38
+
39
+ "Modified Version" refers to any derivative made by adding to, deleting,
40
+ or substituting -- in part or in whole -- any of the components of the
41
+ Original Version, by changing formats or by porting the Font Software to a
42
+ new environment.
43
+
44
+ "Author" refers to any designer, engineer, programmer, technical
45
+ writer or other person who contributed to the Font Software.
46
+
47
+ PERMISSION & CONDITIONS
48
+ Permission is hereby granted, free of charge, to any person obtaining
49
+ a copy of the Font Software, to use, study, copy, merge, embed, modify,
50
+ redistribute, and sell modified and unmodified copies of the Font
51
+ Software, subject to the following conditions:
52
+
53
+ 1) Neither the Font Software nor any of its individual components,
54
+ in Original or Modified Versions, may be sold by itself.
55
+
56
+ 2) Original or Modified Versions of the Font Software may be bundled,
57
+ redistributed and/or sold with any software, provided that each copy
58
+ contains the above copyright notice and this license. These can be
59
+ included either as stand-alone text files, human-readable headers or
60
+ in the appropriate machine-readable metadata fields within text or
61
+ binary files as long as those fields can be easily viewed by the user.
62
+
63
+ 3) No Modified Version of the Font Software may use the Reserved Font
64
+ Name(s) unless explicit written permission is granted by the corresponding
65
+ Copyright Holder. This restriction only applies to the primary font name as
66
+ presented to the users.
67
+
68
+ 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
69
+ Software shall not be used to promote, endorse or advertise any
70
+ Modified Version, except to acknowledge the contribution(s) of the
71
+ Copyright Holder(s) and the Author(s) or with their explicit written
72
+ permission.
73
+
74
+ 5) The Font Software, modified or unmodified, in part or in whole,
75
+ must be distributed entirely under this license, and must not be
76
+ distributed under any other license. The requirement for fonts to
77
+ remain under this license does not apply to any document created
78
+ using the Font Software.
79
+
80
+ TERMINATION
81
+ This license becomes null and void if any of the above conditions are
82
+ not met.
83
+
84
+ DISCLAIMER
85
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
86
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
87
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
88
+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
89
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
90
+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
91
+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
92
+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
93
+ OTHER DEALINGS IN THE FONT SOFTWARE.
@@ -104,11 +104,21 @@ function notify(title, message) {
104
104
  // A milestone reached is said in neutral words (the operator's decisions 5 and 6 of 2026-10-01): its message, from the
105
105
  // campaign, is on the dashboard, and no milestone is a reward ready, or a code. Until then this said "Reward ready at",
106
106
  // and the announcement below "KitCode break code ready".
107
+ //
108
+ // Since 2026-10-22 (rewards/3-repeat-vouchers, phase 2) the milestones are those of the cycle counted in (reward.mjs): from cycle
109
+ // 2 on the context names it, "KitCode progress (cycle 2): …", and the milestones it lists and announces are that cycle's; the =
110
+ // and the time are the totals, which keep counting. Cycle 1 reads as it always has. The cycle is the record's, read with the
111
+ // rest of the file: no receipt is checked here (hard rule 7).
112
+ function cycleOf(reward) {
113
+ return Number.isSafeInteger(reward?.cycle) && reward.cycle > 1 ? reward.cycle : null;
114
+ }
115
+
107
116
  function progressContextFor(reward) {
108
117
  const nextBreak = reward.nextBreak ?? nextBreakReminder(reward);
109
118
  const ready = reward.milestones.filter((entry) => entry.status === 'ready' && !entry.redeemed);
119
+ const cycle = cycleOf(reward);
110
120
  const parts = [
111
- `KitCode progress: ${reward.totalEquals} = counted, ${formatBreakDuration(reward.earnedSeconds)} active.`,
121
+ `KitCode progress${cycle === null ? '' : ` (cycle ${cycle})`}: ${reward.totalEquals} = counted, ${formatBreakDuration(reward.earnedSeconds)} active.`,
112
122
  ];
113
123
 
114
124
  if (ready.length > 0) {
@@ -140,7 +150,8 @@ function hookOutputFor({tiers = [], reward = null}) {
140
150
  };
141
151
  }
142
152
 
143
- const labels = tiers.map((tier) => `${tier.percent}%`).join(', ');
153
+ const cycle = cycleOf(reward);
154
+ const labels = `${tiers.map((tier) => `${tier.percent}%`).join(', ')}${cycle === null ? '' : `, cycle ${cycle}`}`;
144
155
  const command = 'kitcode dashboard';
145
156
  const additionalContext = [
146
157
  progressContext,
@@ -206,7 +217,8 @@ export async function runPromptHook({source}) {
206
217
  }
207
218
 
208
219
  const label = announced.map((tier) => `${tier.percent}%`).join(', ');
209
- notify('KitCode milestone reached', `Milestone ${label} unlocked. Open kitcode dashboard.`);
220
+ const cycle = cycleOf(reward);
221
+ notify('KitCode milestone reached', `Milestone ${label}${cycle === null ? '' : ` of cycle ${cycle}`} unlocked. Open kitcode dashboard.`);
210
222
  process.stdout.write(`${JSON.stringify(hookOutputFor({tiers: announced, reward}))}\n`);
211
223
  } catch (error) {
212
224
  failure = error;
@@ -10,6 +10,13 @@ export const DASHBOARD_URL = "https://staging.kitcode.vn/";
10
10
  // staging dashboard's /v1/diagnostics, which scripts/tester-build.mjs alone writes here, as it writes DASHBOARD_URL. null in
11
11
  // the repository, and so in every release of it: such a CLI collects, writes and sends no diagnostics at all.
12
12
  export const DIAGNOSTICS_URL = "https://staging.kitcode.vn/v1/diagnostics";
13
+ // The claim backend's public key for cycle receipts (src/cycle-receipt.mjs; docs/backend.md, "The cycle receipt"): base64url of
14
+ // the 32 raw bytes of the Ed25519 key whose private half exists on the claim backend's server alone. The tracker begins a
15
+ // cycle only on a receipt it signed (api.mjs, POST /api/claim/receipt). Public, as the repository is, and written here by
16
+ // scripts/tester-build.mjs alone, from the key the staging server printed (deploy/staging/cycle-receipt.pub), as it writes
17
+ // DIAGNOSTICS_URL. null in the repository, and so in every release of it until a production claim backend has a key of its
18
+ // own: such a CLI takes no receipt, and never begins a second cycle.
19
+ export const CYCLE_RECEIPT_PUBLIC_KEY = "QsSBNGXhReBhjz0qk32fFLYiVCDtqKEGQwFB30LflTw";
13
20
  export const LOCAL_SERVER_URL = 'http://127.0.0.1:4747';
14
21
  export const STATE_DISPLAY_PATH = '~/.kitcode/state.json';
15
22
  export const RUNNER_PATH_PARTS = ['.kitcode', 'bin', 'kitcode'];
@@ -24,14 +31,48 @@ export const RUNNER_DISPLAY_PATH = `~/${RUNNER_PATH_PARTS.join('/')}`;
24
31
  // 30, 50 and 100 %, each with the targets it had: 30 % the one tier, 50 and 100 % shown and never announced, as before.
25
32
  // Until then 10 % (3 =, 6 min) and 20 % (6 =, 12 min) were tiers too. A record an earlier version kept of either, an
26
33
  // announcement, a code shown or the time it was reached, stays in the file as it is, and nothing reads it.
27
- export const KITCODE_REWARD_TIERS = [
28
- {percent: 30, requiredEquals: 9},
29
- ];
34
+ //
35
+ // Since 2026-10-20 (rewards/2-no-stack; the plan of that day, decisions 1 and 4) each milestone's targets, its focus time
36
+ // and its =, are counted fresh from the moment the milestone before it was reached, the first's from install, and each
37
+ // milestone names its own focus time, where 3600 s × its percent was the time target until then (reward.mjs). Two tables,
38
+ // both public: the tester table, the short one, which every build of this repository and every tester build counts by,
39
+ // its numbers the ones the milestones had; and the production table, whose numbers are DRAFTS until the client gives the
40
+ // campaign's length: 3 h and 300 =, 5 h and 500 =, 10 h and 1,000 =, so 18 h and 1,800 = in all to reach 100 %.
41
+ // MILESTONE_TABLE names the one in force: 'tester' here, and so in every tester build; a production release's copy alone
42
+ // says 'production', which scripts/release.mjs writes there, one line, checked line by line, as tester-build.mjs writes
43
+ // DASHBOARD_URL.
44
+ //
45
+ // Since 2026-10-21 both tables hold the operator's numbers of that day ("change the progress to 30% - 3h - 300 = / 50% -
46
+ // 5h - 500 = / 100% - 8h - 1000 =", then "1. staging too 2. as written"): 3 h and 300 =, 5 h and 500 =, 8 h and 1,000 =,
47
+ // so 16 h and 1,800 = in all to reach 100 %. Tester builds have no short targets any more, which reverses the plan's
48
+ // decision 4 for the tester table; the production table's numbers are no longer drafts, and its 100 % is 8 h where the
49
+ // draft said 10. The two tables stay two, equal, so that production's can differ again by one table's edit (a ruling,
50
+ // docs/reward-rules.md §2). Until then the tester table was 1080 s and 9 =, 1800 s and 12 =, 3600 s and 15 =.
51
+ export const MILESTONE_TABLES = Object.freeze({
52
+ tester: Object.freeze([
53
+ Object.freeze({percent: 30, requiredSeconds: 10800, requiredEquals: 300}),
54
+ Object.freeze({percent: 50, requiredSeconds: 18000, requiredEquals: 500}),
55
+ Object.freeze({percent: 100, requiredSeconds: 28800, requiredEquals: 1000}),
56
+ ]),
57
+ production: Object.freeze([
58
+ Object.freeze({percent: 30, requiredSeconds: 10800, requiredEquals: 300}),
59
+ Object.freeze({percent: 50, requiredSeconds: 18000, requiredEquals: 500}),
60
+ Object.freeze({percent: 100, requiredSeconds: 28800, requiredEquals: 1000}),
61
+ ]),
62
+ });
63
+
64
+ export const MILESTONE_TABLE = 'tester';
65
+
66
+ const MILESTONE_TARGETS = MILESTONE_TABLES[MILESTONE_TABLE];
67
+
68
+ if (!Array.isArray(MILESTONE_TARGETS)) {
69
+ throw new Error(`MILESTONE_TABLE is ${JSON.stringify(MILESTONE_TABLE)}, which is not one of the milestone tables: ${Object.keys(MILESTONE_TABLES).join(', ')}.`);
70
+ }
30
71
 
31
- export const KITCODE_DISPLAY_MILESTONES = [
32
- {percent: 50, requiredEquals: 12, displayOnly: true},
33
- {percent: 100, requiredEquals: 15, displayOnly: true},
34
- ];
72
+ // 30 %, the first milestone, is the one tier; 50 and 100 % are shown alone.
73
+ export const KITCODE_REWARD_TIERS = MILESTONE_TARGETS.slice(0, 1).map((milestone) => ({...milestone}));
74
+
75
+ export const KITCODE_DISPLAY_MILESTONES = MILESTONE_TARGETS.slice(1).map((milestone) => ({...milestone, displayOnly: true}));
35
76
 
36
77
  export const AGENT_SPECS = {
37
78
  codex: {
@@ -172,7 +213,7 @@ export function kitCodeSkillMarkdown(source) {
172
213
  ` ${RUNNER_DISPLAY_PATH} dashboard`,
173
214
  '',
174
215
  'The prompt hook runs after each prompt submit and may add compact progress context such as total `=` counted, active time, next break remaining (`=` left and time left), or milestones reached. Treat that hook context as authoritative.',
175
- 'When hook context includes remaining equals and time to the next break milestone, briefly mention both in one short line after your normal answer on every turn (for example: `Break next: 4 = to break · 12m to break (30%).`). Do not calculate these values yourself.',
216
+ 'When hook context includes remaining equals and time to the next break milestone, briefly mention both in one short line after your normal answer on every turn (for example: `Break next: 120 = to break · 1h 20m to break (30%).`). Do not calculate these values yourself.',
176
217
  '',
177
218
  'Do not run git counting commands, do not edit the ledger, and do not reimplement reward logic in chat. Use the KitCode CLI/server/hook output as the authority.',
178
219
  '',
@@ -213,9 +254,27 @@ export function kitCodeSkillMarkdown(source) {
213
254
  ].join('\n');
214
255
  }
215
256
 
257
+ // A milestone's time as the setup prompt says it: whole hours as "3h", and otherwise as next-break-reminder.mjs writes a time
258
+ // left, "2h 30m", "18m". Here, since this file imports nothing (the dashboard bundles it).
259
+ function targetTime(seconds) {
260
+ const hours = Math.floor(seconds / 3600);
261
+ const minutes = Math.floor((seconds % 3600) / 60);
262
+
263
+ if (hours > 0) {
264
+ return minutes > 0 ? `${hours}h ${minutes}m` : `${hours}h`;
265
+ }
266
+
267
+ return minutes > 0 ? `${minutes}m` : `${seconds}s`;
268
+ }
269
+
270
+ // Since 2026-10-20 each line says where its milestone counts from: install for the first, and for each other the moment the
271
+ // one before it was reached (docs/reward-rules.md §2). Since 2026-10-21 each names its time, "3h of tracked time", where it
272
+ // said "enough tracked time": with the operator's targets of that day a milestone's time is 3 to 8 hours.
216
273
  function milestoneLines() {
217
- return [...KITCODE_REWARD_TIERS, ...KITCODE_DISPLAY_MILESTONES]
218
- .map((milestone) => `- ${milestone.percent}% milestone: reached after enough tracked time and ${milestone.requiredEquals} counted = characters; the dashboard shows its message.`)
274
+ const milestones = [...KITCODE_REWARD_TIERS, ...KITCODE_DISPLAY_MILESTONES];
275
+
276
+ return milestones
277
+ .map((milestone, index) => `- ${milestone.percent}% milestone: reached after ${targetTime(milestone.requiredSeconds)} of tracked time and ${milestone.requiredEquals} counted = characters, both counted ${index === 0 ? 'from install' : `from the moment the ${milestones[index - 1].percent}% milestone was reached`}; the dashboard shows its message.`)
219
278
  .join('\n');
220
279
  }
221
280
 
@@ -0,0 +1,214 @@
1
+ // The milestone record in state.json, `milestonesReached`, read (docs/reward-rules.md §6.1): what each milestone's entry
2
+ // says, checked as KitCode writes it. Pure, with no imports: reward.mjs reads it to decide the milestones, and
3
+ // milestones-reached.mjs to write the record and to report it in the claim bundle.
4
+ //
5
+ // {"recordingSince": "2026-09-25T09:15:00.004Z",
6
+ // "milestones": {"30": {"reachedBeforeRecording": true},
7
+ // "50": {"reachedAt": "2026-10-20T11:03:27.918Z", "focusSeconds": 3600, "equals": 15}},
8
+ // "freshSince": {"at": "2026-10-20T10:00:00.000Z", "focusSeconds": 2400, "equals": 11}}
9
+ //
10
+ // Since 2026-10-20 (rewards/2-no-stack) an entry the CLI writes also holds the totals at the moment the milestone was
11
+ // reached, its focus seconds and its =, and `freshSince` the totals at the moment this KitCode first wrote a record that
12
+ // holds a milestone reached without them: by an earlier KitCode, or before the record began. The milestone after such a
13
+ // one counts from `freshSince` (the plan's decision 2). An entry an earlier KitCode wrote, `reachedAt` alone, stays as it
14
+ // is, and so does every field this version does not know.
15
+ //
16
+ // Since 2026-10-22 (rewards/3-repeat-vouchers, phase 2) the record counts in cycles (the plan of 2026-10-21, decision 1: after a
17
+ // claim, all progress resets). Cycle 1 is the record as it was, its entries in `milestones`; each later cycle is one entry of
18
+ // `cycles`, added when the tracker takes a receipt the claim backend signed for the voucher of the cycle before
19
+ // (milestones-reached.mjs, beginNextCycle), and never changed after but for its own milestones, added once each. Since 2026-10-22's
20
+ // phase 3 a cycle is numbered as the claim backend counts, the one after its receipt's, so the numbers can skip: a KitCode installed
21
+ // afresh in cycle 1 that takes the receipt of cycle 2 begins cycle 3.
22
+ //
23
+ // "cycles": [{"cycle": 2, "startedAt": "2026-10-22T08:00:00.000Z", "focusSeconds": 57900, "equals": 1810,
24
+ // "receipt": {"claimId": "…", "issuedAt": "2026-10-22T07:58:00.000Z"},
25
+ // "milestones": {"30": {"reachedAt": "…", "focusSeconds": 68722, "equals": 2110}}}]
26
+ //
27
+ // A cycle's start is the totals since install at the moment it began, which its first milestone counts from; the totals keep
28
+ // counting across cycles. Nothing of cycle 1 changes when cycle 2 begins: the record is additive only (hard rule 4).
29
+
30
+ // A time as toISOString writes it, and a real one: 2026-02-30 is not.
31
+ const INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
32
+
33
+ function isObject(value) {
34
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
35
+ }
36
+
37
+ export function isInstant(value) {
38
+ if (typeof value !== 'string' || !INSTANT.test(value)) {
39
+ return false;
40
+ }
41
+
42
+ const time = Date.parse(value);
43
+ return Number.isFinite(time) && new Date(time).toISOString() === value;
44
+ }
45
+
46
+ function isCount(value) {
47
+ return Number.isSafeInteger(value) && value >= 0;
48
+ }
49
+
50
+ const CLAIM_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u;
51
+
52
+ // A record as KitCode writes it: when it began, and its entries.
53
+ export function isRecord(record) {
54
+ return isObject(record) && isInstant(record.recordingSince) && isObject(record.milestones);
55
+ }
56
+
57
+ // The totals an entry, or freshSince, holds: both, whole and not below 0, or neither (null). Anything else is undefined:
58
+ // not what KitCode writes.
59
+ function totalsOf(value) {
60
+ const hasSeconds = Object.hasOwn(value, 'focusSeconds');
61
+ const hasEquals = Object.hasOwn(value, 'equals');
62
+
63
+ if (!hasSeconds && !hasEquals) {
64
+ return null;
65
+ }
66
+
67
+ return hasSeconds && hasEquals && isCount(value.focusSeconds) && isCount(value.equals)
68
+ ? {seconds: value.focusSeconds, equals: value.equals}
69
+ : undefined;
70
+ }
71
+
72
+ // One milestone's entry: {kind: 'before-recording'} or {kind: 'reached', reachedAt, end}, `end` the totals it was reached
73
+ // at, or null when the entry holds none; undefined when it is not an entry KitCode writes.
74
+ function entryOf(entry) {
75
+ if (!isObject(entry)) {
76
+ return undefined;
77
+ }
78
+
79
+ if (entry.reachedBeforeRecording === true && entry.reachedAt === undefined) {
80
+ return totalsOf(entry) === null ? {kind: 'before-recording', reachedAt: null, end: null} : undefined;
81
+ }
82
+
83
+ if (isInstant(entry.reachedAt) && entry.reachedBeforeRecording === undefined) {
84
+ const end = totalsOf(entry);
85
+ return end === undefined ? undefined : {kind: 'reached', reachedAt: entry.reachedAt, end};
86
+ }
87
+
88
+ return undefined;
89
+ }
90
+
91
+ // A later cycle's entry, read for `percents`, `after` the number of the cycle before it: {cycle, startedAt, start, receipt,
92
+ // entries}, or a problem's words, a string, when it is not what KitCode writes. Each of its milestones was reached with its
93
+ // totals: a later cycle counts from a start it knows. Its number is past the one before it, by one when the tracker took the
94
+ // receipt of the cycle it was in, and by more since 2026-10-22's phase 3, when it took one of a cycle ahead, as the claim
95
+ // backend counts them (milestones-reached.mjs, beginNextCycle).
96
+ function cycleOf(value, after, percents) {
97
+ if (!isObject(value) || !Number.isSafeInteger(value.cycle) || value.cycle <= after || !isInstant(value.startedAt) || !isCount(value.focusSeconds) || !isCount(value.equals)
98
+ || !isObject(value.receipt) || typeof value.receipt.claimId !== 'string' || !CLAIM_ID.test(value.receipt.claimId) || !isInstant(value.receipt.issuedAt)
99
+ || !isObject(value.milestones)) {
100
+ return `holds a cycle after cycle ${after} that KitCode does not write`;
101
+ }
102
+
103
+ const cycle = value.cycle;
104
+ const entries = new Map();
105
+
106
+ for (const percent of percents) {
107
+ if (!Object.hasOwn(value.milestones, String(percent))) {
108
+ continue;
109
+ }
110
+
111
+ const entry = entryOf(value.milestones[String(percent)]);
112
+
113
+ if (entry?.kind !== 'reached' || entry.end === null) {
114
+ return `holds an entry for ${percent} % in cycle ${cycle} that KitCode does not write`;
115
+ }
116
+
117
+ entries.set(percent, entry);
118
+ }
119
+
120
+ return {
121
+ cycle,
122
+ startedAt: value.startedAt,
123
+ start: {seconds: value.focusSeconds, equals: value.equals},
124
+ receipt: {claimId: value.receipt.claimId, issuedAt: value.receipt.issuedAt},
125
+ entries,
126
+ };
127
+ }
128
+
129
+ // The record, read for `percents`, the milestones in order (the retired 10 and 20 % are never among them, whatever their
130
+ // entries hold):
131
+ //
132
+ // {state: 'none'}: no record yet, a file from before it, or one 0.1.39 rewrote;
133
+ // {state: 'damaged', problem}: not what KitCode writes, which is left as it is, never repaired or written over;
134
+ // {state: 'kept', recordingSince, freshSince, entries, cycles, current}: `entries` maps each percent recorded in cycle 1 to
135
+ // its entry, and `freshSince` is cycle 1's {at, seconds, equals} or null; since 2026-10-22 `cycles` lists the later cycles,
136
+ // oldest first, each {cycle, startedAt, start, receipt, entries}, and `current` is the cycle the milestones count in now:
137
+ // {cycle: 1, startedAt: null, start: {seconds: 0, equals: 0}, receipt: null, entries, freshSince} with no later one, else
138
+ // the last, its freshSince null.
139
+ //
140
+ // A milestone with its totals, after one whose totals are not known, counts from freshSince: without it, the record is
141
+ // not one KitCode writes.
142
+ export function readMilestoneRecord(record, percents) {
143
+ if (record === undefined) {
144
+ return {state: 'none'};
145
+ }
146
+
147
+ if (!isRecord(record)) {
148
+ return {state: 'damaged', problem: 'is not the record KitCode writes'};
149
+ }
150
+
151
+ let freshSince = null;
152
+
153
+ if (record.freshSince !== undefined) {
154
+ const totals = isObject(record.freshSince) && isInstant(record.freshSince.at) ? totalsOf(record.freshSince) : undefined;
155
+
156
+ if (!totals) {
157
+ return {state: 'damaged', problem: 'holds a start of fresh counting (freshSince) that KitCode does not write'};
158
+ }
159
+
160
+ freshSince = {at: record.freshSince.at, ...totals};
161
+ }
162
+
163
+ const entries = new Map();
164
+
165
+ for (const percent of percents) {
166
+ if (!Object.hasOwn(record.milestones, String(percent))) {
167
+ continue;
168
+ }
169
+
170
+ const entry = entryOf(record.milestones[String(percent)]);
171
+
172
+ if (entry === undefined) {
173
+ return {state: 'damaged', problem: `holds an entry for ${percent} % that KitCode does not write`};
174
+ }
175
+
176
+ entries.set(percent, entry);
177
+ }
178
+
179
+ // Each milestone's start, in order: install for the first; for another, the totals the one before it was reached at,
180
+ // when its entry holds them, and otherwise freshSince.
181
+ let previousEnd = {seconds: 0, equals: 0};
182
+
183
+ for (const percent of percents) {
184
+ const entry = entries.get(percent);
185
+
186
+ if (entry?.end && previousEnd === null && freshSince === null) {
187
+ return {state: 'damaged', problem: `holds the totals ${percent} % was reached at, with no start for them to count from`};
188
+ }
189
+
190
+ previousEnd = entry?.end ?? null;
191
+ }
192
+
193
+ // Since 2026-10-22: the later cycles, oldest first, each past the one before it, the first past cycle 1.
194
+ const cycles = [];
195
+
196
+ if (record.cycles !== undefined) {
197
+ if (!Array.isArray(record.cycles)) {
198
+ return {state: 'damaged', problem: 'holds cycles that KitCode does not write'};
199
+ }
200
+
201
+ for (const value of record.cycles) {
202
+ const cycle = cycleOf(value, cycles.at(-1)?.cycle ?? 1, percents);
203
+
204
+ if (typeof cycle === 'string') {
205
+ return {state: 'damaged', problem: cycle};
206
+ }
207
+
208
+ cycles.push(cycle);
209
+ }
210
+ }
211
+
212
+ const current = cycles.at(-1) ?? {cycle: 1, startedAt: null, start: {seconds: 0, equals: 0}, receipt: null, entries, freshSince};
213
+ return {state: 'kept', recordingSince: record.recordingSince, freshSince, entries, cycles, current: {freshSince: null, ...current}};
214
+ }