interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / native / kernel / core / lifecycle.c

989 lines · 46680 bytes Raw Blame History
1/* SPDX-License-Identifier: Apache-2.0
2 * Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* lifecycle.c -- resident production lifecycle (native v1 plan P03).
18 *
19 * Linked only into a CK_SERVICE=1 image (Makefile: full-service /
20 * full-service-testkeys). kmain calls ck_lifecycle_run after every boot
21 * stage instead of resetting: the product boundary where the diagnostic
22 * image ends in ck_reset(). The diagnostic images are untouched (they do not
23 * link this file; the weak ck_lifecycle_run is absent there).
24 *
25 * Operator input: the POLLED serial receive of the console UART the boot
26 * stub chose from the ACPI SPCR (core/console.c, core/uart_rx.h: PL011/SBSA
27 * on QEMU virt, 16550 on the DGX Spark), no interrupts. One bounded line
28 * assembler (core/line_rx.c: CK_LC_LINE_MAX bytes, overlong or damaged lines
29 * refused whole) serves the prompt and the cancel poll between generation
30 * steps. Neither UART kind: `console input unsupported on this platform` and
31 * the stop order. The USB keyboard binding stays with the xHCI session code
32 * and is a later cut. Verbs and transitions: core/lifecycle_fsm.c.
33 *
34 * Store: the sealed Store opened by the store stage stays open and the NVMe
35 * stays bound for the service lifetime (svc/store_boot.c, CK_SERVICE). An
36 * approved task is committed as one Store object (kind CK_LC_OBJ_KIND).
37 * Stop order on "shutdown": (1) close the Store (keys erased; every commit
38 * is already durable: ss_transact returns after its final flush), (2) NVMe
39 * normal shutdown, bus master off, SMMU stream to abort (ck_dev_nvme_release),
40 * (3) return to kmain: final report, ck_reset (quiesce hook, PSCI). Never
41 * the other way round.
42 *
43 * LOCKED at boot is the production truth: ck_store_production_keys refuses
44 * (no TPM Slot 0 unwrap); the operator opens the Store with the recovery
45 * secret (`unlock <64-hex>`, P04 cut 1). The TEST-ONLY full-service-testkeys
46 * image (refused with CK_HARDWARE_STAGING) opens it with TEST keys at boot so
47 * the READY and SERVE paths run in QEMU.
48 *
49 * Continuity (P05 cut 1): every Store open runs svc/continuity_service.c:
50 * identity + ALLEN subject provisioned once, restored and resumed on every
51 * boot; a refusal keeps the lifecycle LOCKED. `status` reports it.
52 *
53 * Remembered facts (P06 cut 4, the N3 "memory-only fact"): `remember <text>`
54 * appends one CX_CLAIM record to the canonical Omega Cortex store whose
55 * journal is the sealed Store (svc/cortex_journal.c, chunks of kind 'CJ');
56 * `facts` reads the journal back (every record digest and the chain
57 * re-verified by Omega's cx_open replay) and lists the newest facts. The
58 * journal opens lazily on the first of either verb (a fresh journal is
59 * created only by `remember`), stays open for the service lifetime and is
60 * closed first in the stop order. Its heap is CK_CX_HEAP_PAGES kernel frames
61 * handed to the Cortex bump allocator and returned at the stop order.
62 * Nothing in memory is authoritative: a cold boot answers `facts` from the
63 * disk, the fact never has to be restated.
64 *
65 * Memory-conditioned generation (N3, aienos#329): `prefer <text>` appends a
66 * v1 memory record (core/context.h: bound to the provisioned agent id,
67 * context permission recorded in the record). Every `prompt` first assembles
68 * its context (core/context.c) from the verified journal records: no eligible
69 * record -> the prompt is the operator's text exactly; else a delimited DATA
70 * section precedes it. A journal that fails verification at open, an
71 * unverified, malformed or foreign record refuses the prompt (fail closed:
72 * nothing generated). Recalled text is data: no verb is ever parsed from it
73 * or from a reply. `remember` facts stay private (legacy format, never in a
74 * prompt).
75 *
76 * Exact approval (N3): a pending note or reply is bound when it is shown
77 * (core/context_proposal.h: request id = continuity incarnation + per-boot
78 * sequence, Store generation, SHA-256 of the exact bytes, idempotence key).
79 * `approve` commits exactly those bytes plus the trailer carrying the key,
80 * after refusing a changed or stale binding and a key already on the disk;
81 * `deny`, `cancel` and `shutdown` write nothing. */
82#include <stddef.h>
83#include <stdint.h>
84#include "ck.h"
85#include "ck_internal.h"
86#include "lifecycle_fsm.h"
87#include "line_rx.h"
88#include "context.h"
89#include "context_proposal.h"
90#include "store_boot.h"
91#include "store_sealed.h"
92#include "continuity_service.h"
93#include "cortex_journal.h"
94#include "slot_service.h"
95#include "reply_obj.h"
96#ifdef CK_PI5_LIFECYCLE
97#include "agent_cmd.h"
98#endif
99
100#if !defined(CK_SERVICE)
101#error "lifecycle.c is only part of a CK_SERVICE=1 image"
102#endif
103#if defined(CK_CONSOLE_SESSION) || defined(CK_TEST_STORE_CRASH) || defined(CK_TEST_CONTINUITY) || \
104 defined(CK_QEMU_UNSAFE_DMA) || defined(CK_TEST_FWCFG_ARTIFACTS)
105#error "CK_SERVICE cannot be combined with a TEST-only image flag"
106#endif
107#if defined(CK_SERVICE_TEST_KEYS) && defined(CK_HARDWARE_STAGING)
108#error "CK_SERVICE_TEST_KEYS (TEST keys) cannot be combined with CK_HARDWARE_STAGING"
109#endif
110#if defined(CK_PI5_LIFECYCLE) && (!defined(CK_PI5_UNLOCK_CARD) || defined(CK_SERVICE_TEST_KEYS) || defined(CK_HARDWARE_STAGING))
111#error "CK_PI5_LIFECYCLE (card command script, QUALIFICATION ONLY) needs the card-secret Pi image and no TEST keys or hardware staging"
112#endif
113#ifdef CK_PI5_LIFECYCLE
114_Static_assert(CK_AGENT_CMD_TEXT_MAX == CK_LC_TASK_MAX && CK_AGENT_CMD_LINE_MAX <= CK_LC_LINE_MAX, "script line bounds are the lifecycle bounds");
115#endif
116
117#define CK_LC_OBJ_KIND 0x4e31u /* 'N1': v1 approved note, version 1 */
118#define CK_LC_REPLY_KIND CK_REPLY_OBJ_KIND /* 0x5231 'R1': v1 approved reply (prompt + generated text), version 1 */
119
120void ck_dev_nvme_release(void);
121int ck_store_service_ready(void);
122int ck_store_service_close(void);
123int ck_store_service_unlock(const char *arg, size_t arg_len);
124int ck_store_service_rotate(const char *arg, size_t arg_len);
125
126static ck_lc g_lc;
127
128/* P11 cut 2b health milestone for slot promotion (svc/slot_service.h): Store open,
129 * continuity committed this boot, lifecycle READY. */
130static int slot_healthy(void)
131{
132 return ck_store_service_ready() && ck_cont_service_writable() && g_lc.state == CK_LC_READY;
133}
134static uint8_t g_last_id[32];
135static uint64_t g_last_gen;
136static unsigned g_overlong;
137
138/* The Cortex store over the sealed Store (P06 cuts 3 and 4). */
139#define CK_CX_FACTS_SHOWN 16u /* `facts` lists at most the newest 16 */
140#define CK_CX_HEAP_BYTES (CK_CX_HEAP_PAGES * 4096u)
141static ck_cj g_cj;
142static CxStore g_cx;
143static int g_cx_open; /* 1 while the journal is open */
144static uint64_t g_cx_heap_pa; /* 0: no frames held */
145static uint32_t g_cx_refused; /* remember/facts refused by the Store or Cortex */
146
147/* N3: context assembly and the exact approval binding. */
148_Static_assert(CK_CTX_TASK_MAX == CK_LC_TASK_MAX && CK_CTX_TEXT_MAX == CK_LC_TASK_MAX, "context text bounds");
149_Static_assert(CK_CTX_OWNER_SUBJECT == CK_CX_FACT_SUBJECT, "memory records are about the owner subject");
150_Static_assert(CK_CTX_WORST <= CK_CTX_PROMPT_MAX, "worst-case section fits the prompt limit");
151_Static_assert(CK_CTX_PROMPT_MAX == CK_INFER_RES_PROMPT_BYTES, "prompt limit = resident session prompt bytes");
152_Static_assert(CK_CTX_PROMPT_MAX + CK_CTX_TEMPLATE_IDS + CK_INFER_RES_MAX_NEW <= CK_INFER_RES_KV,
153 "an accepted prompt can always finish its reply inside the KV capacity");
154_Static_assert(CK_LC_REPLY_MAX == CK_INFER_REPLY_TEXT && CK_INFER_REPLY_IDS >= CK_INFER_RES_MAX_NEW, "reply buffers");
155#if !defined(__BYTE_ORDER__) || __BYTE_ORDER__ != __ORDER_LITTLE_ENDIAN__
156#error "context assembly reads Cortex payload words as little-endian bytes"
157#endif
158static ck_ctx g_ctx;
159static ck_prop g_prop;
160static uint64_t g_req_seq; /* proposals bound in this boot */
161static uint8_t g_gen_ctx_sha[32]; /* context of the pending reply (part of its bytes) */
162static uint32_t g_gen_ctx_sel;
163static uint32_t g_contexts, g_memory_used, g_ctx_refused, g_proposals, g_props_dropped;
164static uint8_t g_last_key[32];
165
166static void help(void)
167{
168 ck_puts("lifecycle: verbs: status unlock [<64-hex recovery secret>] rotate <current 64-hex> <new 64-hex> task <text> prompt <text> approve deny cancel recall remember <text> prefer <text> facts update evidence help shutdown\n");
169}
170
171static void status(void)
172{
173 char cs[96];
174 ck_cont_service_status(cs, sizeof cs);
175 ck_printf("lifecycle: state=%s store=%s pending=%s requests=%u %s\n", ck_lc_state_name(g_lc.state),
176 ck_store_service_ready() ? "open" : "locked", g_lc.task_len ? g_lc.task : "-", g_lc.requests, cs);
177}
178
179static void evidence(void)
180{
181 ck_printf("lifecycle: evidence requests=%u refused=%u invalid=%u tasks=%u approved=%u denied=%u cancelled=%u "
182 "overlong=%u last_commit_gen=%llu last_id=%02x%02x%02x%02x prompts=%u replies=%u gen_cancelled=%u "
183 "gen_failed=%u recalls=%u inference=%s remembers=%u facts=%u cortex=%s records=%llu\n",
184 g_lc.requests, g_lc.refused, g_lc.invalid, g_lc.tasks, g_lc.approved, g_lc.denied, g_lc.cancelled,
185 g_overlong, (unsigned long long)g_last_gen, g_last_id[0], g_last_id[1], g_last_id[2], g_last_id[3],
186 g_lc.prompts, g_lc.replies, g_lc.gen_cancelled, g_lc.gen_failed, g_lc.recalls,
187 ck_infer_resident() ? "resident" : "none", g_lc.remembers, g_lc.facts, g_cx_open ? "open" : "none",
188 (unsigned long long)(g_cx_open ? g_cx.n : 0));
189 ck_printf("lifecycle: memory evidence prefers=%u contexts=%u memory_used=%u context_refused=%u proposals=%u "
190 "dropped=%u bind_refused=%u replays=%u last_key=%02x%02x%02x%02x\n",
191 g_lc.prefers, g_contexts, g_memory_used, g_ctx_refused, g_proposals, g_props_dropped, g_lc.bind_refused,
192 g_lc.replays, g_last_key[0], g_last_key[1], g_last_key[2], g_last_key[3]);
193}
194
195static void hex8(char out[17], const uint8_t *b)
196{
197 static const char hx[] = "0123456789abcdef";
198 unsigned i;
199 for (i = 0; i < 8; i++) {
200 out[2 * i] = hx[b[i] >> 4];
201 out[2 * i + 1] = hx[b[i] & 15];
202 }
203 out[16] = 0;
204}
205
206/* Printable copy of a byte span for a serial line: ASCII 0x20..0x7e kept,
207 * everything else (including the newline a reply may end with) becomes '?'. */
208static void printable(char *out, size_t cap, const uint8_t *b, size_t n)
209{
210 size_t i;
211 if (n > cap - 1) n = cap - 1;
212 for (i = 0; i < n; i++) out[i] = (b[i] >= 0x20 && b[i] <= 0x7e) ? (char)b[i] : '?';
213 out[n] = 0;
214}
215
216static void put(uint8_t *buf, size_t *n, const char *s, size_t len)
217{
218 size_t i;
219 for (i = 0; i < len; i++) buf[(*n)++] = (uint8_t)s[i];
220}
221
222/* The artifact bytes of the pending proposal (what approve commits, before
223 * the binding trailer). A note: "aienos.note.v1\n" + text (kind 'N1'). A
224 * reply: "aienos.reply.v1\nprompt: " + the operator's prompt + "\nreply: " +
225 * generated bytes + "\ncontext: sha256=<64 hex> memory=<n>\n" (kind 'R1'; the
226 * context line names the exact assembled prompt that produced the reply).
227 * The committed object appends ck_prop_trailer (request, sha256, key). */
228#define CK_LC_CTX_LINE_MAX (17 + 64 + 8 + 10 + 1)
229#define CK_LC_REPLY_OBJ_MAX (16 + 8 + CK_LC_TASK_MAX + 8 + CK_LC_REPLY_MAX + 1 + CK_LC_CTX_LINE_MAX)
230#define CK_LC_OBJ_MAX (CK_LC_REPLY_OBJ_MAX + CK_PROP_TRAILER_MAX)
231_Static_assert(CK_LC_OBJ_MAX <= SS_MAX_PLAINTEXT, "an approved object is one sealed Store object");
232static uint8_t g_obj[CK_LC_OBJ_MAX];
233
234static size_t build_body(uint8_t *buf, uint16_t *kind)
235{
236 static const char note_hdr[] = "aienos.note.v1\n", hx[] = "0123456789abcdef";
237 size_t n = 0, i;
238 if (g_lc.pending == CK_LC_PENDING_REPLY) {
239 char line[CK_LC_CTX_LINE_MAX + 1];
240 *kind = CK_LC_REPLY_KIND;
241 /* The shared builder (core/reply_obj.h, no trailer) gives "aienos.reply.v1\nprompt: ..\nreply: ..\n";
242 * N3 appends one context line naming the exact assembled prompt (the builder's bytes are unchanged for the Pi agent). */
243 n = ck_reply_obj_build(buf, g_lc.task, g_lc.task_len, (const uint8_t *)g_lc.reply, g_lc.reply_len, 0, 0, 0);
244 put(buf, &n, "context: sha256=", 16);
245 for (i = 0; i < 32; i++) {
246 line[2 * i] = hx[g_gen_ctx_sha[i] >> 4];
247 line[2 * i + 1] = hx[g_gen_ctx_sha[i] & 15];
248 }
249 put(buf, &n, line, 64);
250 int m = ck_snprintf(line, sizeof line, " memory=%u\n", g_gen_ctx_sel);
251 put(buf, &n, line, m > 0 ? (size_t)m : 0);
252 } else {
253 *kind = CK_LC_OBJ_KIND;
254 put(buf, &n, note_hdr, sizeof note_hdr - 1);
255 put(buf, &n, g_lc.task, g_lc.task_len);
256 }
257 return n;
258}
259
260/* A proposal became pending (task accepted, or a reply generated): bind it. */
261static void propose(void)
262{
263 ss_store *s = store_boot_store();
264 const uint8_t *agent = ck_cont_service_agent();
265 uint16_t kind = 0;
266 char sh[17], ky[17];
267 if (!s || !agent) { /* READY implies an open Store and a provisioned subject; never commit unbound */
268 ck_prop_clear(&g_prop);
269 ck_puts("lifecycle: proposal UNBOUND (no Store or no provisioned subject): approve will refuse\n");
270 return;
271 }
272 size_t n = build_body(g_obj, &kind);
273 ck_prop_bind(&g_prop, agent, ck_cont_service_incarnation(), ++g_req_seq, ss_generation(s), kind, g_obj, n);
274 g_proposals++;
275 hex8(sh, g_prop.sha);
276 hex8(ky, g_prop.key);
277 ck_printf("lifecycle: proposal bound request=%llu.%llu store_gen=%llu kind=%s bytes=%u sha256=%s key=%s\n",
278 (unsigned long long)g_prop.inc, (unsigned long long)g_prop.seq, (unsigned long long)g_prop.gen,
279 kind == CK_LC_REPLY_KIND ? "reply" : "note", (unsigned)n, sh, ky);
280}
281
282/* Number of journal chunks ('CJ' objects) the open Store holds. */
283static uint32_t cortex_chunks(const ss_store *s);
284
285/* deny / cancel / shutdown: the binding is forgotten, nothing is written. The
286 * line re-reads the Store generation and the journal chunk count so the gate
287 * can compare them with the ones at proposal time. */
288static void proposal_dropped(const char *why)
289{
290 ss_store *s = store_boot_store();
291 if (!g_prop.active) return;
292 g_props_dropped++;
293 ck_printf("lifecycle: proposal dropped by=%s request=%llu.%llu bound_gen=%llu store_gen=%llu journal_chunks=%u (nothing written)\n",
294 why, (unsigned long long)g_prop.inc, (unsigned long long)g_prop.seq, (unsigned long long)g_prop.gen,
295 (unsigned long long)(s ? ss_generation(s) : 0), s ? cortex_chunks(s) : 0);
296 ck_prop_clear(&g_prop);
297}
298
299/* Replay check: 1 when a committed note or reply already carries key, 0 when
300 * none does, <0 when a committed object cannot be read (fail closed). */
301static int replay_scan(ss_store *s, const uint8_t key[32], uint32_t *scanned)
302{
303 static uint8_t body[SS_MAX_PLAINTEXT];
304 uint32_t k;
305 *scanned = 0;
306 for (k = 0; k < s->nclaims; k++) {
307 const ss_claim *c = &s->ws->claims[k];
308 uint8_t sid[32];
309 size_t len = 0, i;
310 uint16_t kind = 0;
311 if (c->c.obj.object_kind != CK_LC_OBJ_KIND && c->c.obj.object_kind != CK_LC_REPLY_KIND) continue;
312 for (i = 0; i < 32; i++) sid[i] = c->sid[i];
313 if (ss_read(s, sid, body, sizeof body, &len, &kind)) return -1;
314 (*scanned)++;
315 if (ck_prop_has_key(body, len, key)) return 1;
316 }
317 return 0;
318}
319
320/* approve: commit exactly the bound bytes (plus the binding trailer), or
321 * refuse with the reason; prints its own lines. */
322static void approve(void)
323{
324 ss_store *s = store_boot_store();
325 uint16_t kind = 0;
326 uint32_t scanned = 0;
327 size_t n, t, i;
328 char sh[17], ky[17];
329 int rc;
330 if (!s || !ck_store_service_ready()) rc = -1;
331 else if (!ck_cont_service_writable()) rc = CK_SB_E_CONTINUITY; /* degraded mount: read-only */
332 else rc = 0;
333 if (rc) {
334 ck_lc_commit_done(&g_lc, rc);
335 if (rc == CK_SB_E_CONTINUITY)
336 ck_printf("lifecycle: REFUSED verb=approve rc=%d state=%s reason=\"continuity read-only (degraded mount)\"\n", rc,
337 ck_lc_state_name(g_lc.state));
338 else
339 ck_printf("lifecycle: REFUSED verb=approve rc=%d state=%s reason=\"%s\"\n", rc, ck_lc_state_name(g_lc.state),
340 g_lc.reason);
341 return;
342 }
343 n = build_body(g_obj, &kind);
344 int bind = ck_prop_check(&g_prop, ss_generation(s), kind, g_obj, n);
345 rc = bind == CK_PROP_E_STALE ? 0 : bind; /* stale is reported after the replay check */
346 if (rc) {
347 ck_lc_commit_refused(&g_lc, ck_prop_strerror(rc));
348 ck_printf("lifecycle: REFUSED verb=approve rc=%d state=%s reason=\"%s\" bound_gen=%llu store_gen=%llu (nothing written)\n",
349 rc, ck_lc_state_name(g_lc.state), g_lc.reason, (unsigned long long)g_prop.gen,
350 (unsigned long long)ss_generation(s));
351 return;
352 }
353 hex8(sh, g_prop.sha);
354 hex8(ky, g_prop.key);
355 rc = replay_scan(s, g_prop.key, &scanned);
356 if (rc) {
357 if (rc > 0) {
358 ck_lc_commit_replay(&g_lc);
359 ck_prop_clear(&g_prop);
360 } else {
361 ck_lc_commit_refused(&g_lc, "replay check could not read a committed object (fail closed)");
362 }
363 ck_printf("lifecycle: REFUSED verb=approve state=%s reason=\"%s\" key=%s scanned=%u (nothing written)\n",
364 ck_lc_state_name(g_lc.state), g_lc.reason, ky, scanned);
365 return;
366 }
367 if (bind == CK_PROP_E_STALE) { /* the Store moved and not by this request: refuse */
368 ck_lc_commit_refused(&g_lc, ck_prop_strerror(bind));
369 ck_printf("lifecycle: REFUSED verb=approve rc=%d state=%s reason=\"%s\" bound_gen=%llu store_gen=%llu (nothing written)\n",
370 bind, ck_lc_state_name(g_lc.state), g_lc.reason, (unsigned long long)g_prop.gen,
371 (unsigned long long)ss_generation(s));
372 return;
373 }
374 t = ck_prop_trailer(&g_prop, (char *)g_obj + n, sizeof g_obj - n);
375 if (!t) {
376 ck_lc_commit_refused(&g_lc, "binding trailer does not fit");
377 ck_printf("lifecycle: REFUSED verb=approve state=%s reason=\"%s\"\n", ck_lc_state_name(g_lc.state), g_lc.reason);
378 return;
379 }
380 ss_object o = { kind, 1, g_obj, n + t };
381 uint8_t ids[1][32];
382 rc = ss_transact(s, &o, 1, 0, 0, ids);
383 if (rc == 0) {
384 for (i = 0; i < 32; i++) g_last_id[i] = ids[0][i];
385 for (i = 0; i < 32; i++) g_last_key[i] = g_prop.key[i];
386 g_last_gen = ss_generation(s);
387 ck_printf("lifecycle: approve bound request=%llu.%llu bound_gen=%llu sha256=%s key=%s replay_check=clear scanned=%u bytes=%u\n",
388 (unsigned long long)g_prop.inc, (unsigned long long)g_prop.seq, (unsigned long long)g_prop.gen, sh, ky,
389 scanned, (unsigned)(n + t));
390 ck_prop_clear(&g_prop);
391 }
392 ck_lc_commit_done(&g_lc, rc);
393 if (rc == 0)
394 ck_printf("lifecycle: approve committed gen=%llu id=%02x%02x%02x%02x state=%s\n", (unsigned long long)g_last_gen,
395 g_last_id[0], g_last_id[1], g_last_id[2], g_last_id[3], ck_lc_state_name(g_lc.state));
396 else
397 ck_printf("lifecycle: REFUSED verb=approve rc=%d state=%s reason=\"%s\"\n", rc, ck_lc_state_name(g_lc.state),
398 g_lc.reason);
399}
400
401/* Between generation steps the console is polled (no interrupts): a complete
402 * line "cancel" abandons the request; any other complete line, and an
403 * overlong or damaged one, is refused and never run (only cancel is
404 * accepted while generating). Same line rules as the prompt (core/line_rx.c). */
405static struct ck_line_rx g_gen_rx;
406static void gen_refuse(enum ck_lc_verb v, const char *reason)
407{
408 g_lc.refused++;
409 ck_printf("lifecycle: REFUSED verb=%s reason=\"%s\"\n", ck_lc_verb_name(v), reason);
410}
411static int cancel_poll(void)
412{
413#ifdef CK_PI5_LIFECYCLE
414 (void)gen_refuse; /* the card script is never read while generating: no cancel, no refused lines */
415 return 0;
416#else
417 return ck_line_rx_cancel_poll(&g_gen_rx, ck_console_rx_poll, gen_refuse);
418#endif
419}
420
421/* prompt accepted: the resident model generates a bounded reply, which
422 * becomes the pending proposal (approve | deny | cancel) exactly like a
423 * note. Without a resident unit the verb is refused. */
424static int cortex_open(int create);
425
426/* Context assembly for the pending prompt (core/context.h). 0: g_ctx holds
427 * the prompt to generate from. <0: refused (printed; the caller drops the
428 * prompt). The journal is opened read-only-in-effect (never created here);
429 * no journal on the disk is memory none. */
430static int assemble_context(void)
431{
432 static CxRecord r;
433 static char shown[CK_CTX_PROMPT_MAX + 1];
434 const uint8_t *agent = ck_cont_service_agent();
435 char sh[17], ag[17];
436 uint64_t id, records = 0;
437 int rc;
438 g_contexts++;
439 ck_ctx_begin(&g_ctx, agent);
440 rc = cortex_open(0);
441 if (rc < 0) {
442 g_ctx_refused++;
443 ck_printf("lifecycle: context REFUSED rc=%d reason=\"memory journal could not be opened or failed verification (fail closed)\"\n", rc);
444 return rc;
445 }
446 if (rc == 0) {
447 records = g_cx.n;
448 for (id = 1; id <= g_cx.n; id++) {
449 ck_ctx_rec cr;
450 int got = cx_recall_id(&g_cx, id, &r) == CX_OK;
451 cr.id = id;
452 cr.cls = got ? r.hdr.cls : 0;
453 cr.kind = got ? r.hdr.kind : 0;
454 cr.subject = got ? r.hdr.subject : 0;
455 cr.tag = got ? r.hdr.tag : 0;
456 cr.verified = got && r.verified;
457 cr.bytes = got ? (const uint8_t *)r.payload : 0; /* LE words = LE bytes (checked at build) */
458 cr.nbytes = got ? (size_t)r.hdr.n * 8 : 0;
459 if (ck_ctx_add(&g_ctx, &cr)) break;
460 }
461 }
462 rc = ck_ctx_finish(&g_ctx, g_lc.task, g_lc.task_len);
463 if (agent) hex8(ag, agent);
464 else ag[0] = '-', ag[1] = 0;
465 if (rc) {
466 g_ctx_refused++;
467 ck_printf("lifecycle: context REFUSED rc=%d reason=\"%s\" record=%llu records=%llu agent=%s (fail closed)\n", rc,
468 ck_ctx_strerror(rc), (unsigned long long)g_ctx.bad_id, (unsigned long long)records, ag);
469 return rc;
470 }
471 hex8(sh, g_ctx.sha);
472 if (g_ctx.selected) g_memory_used++;
473 ck_printf("lifecycle: context memory=%s selected=%u eligible=%u omitted=%u legacy=%u unpermitted=%u unsafe=%u "
474 "other=%u records=%llu prompt_bytes=%u limit=%u sha256=%s agent=%s\n",
475 g_ctx.selected ? "used" : "none", g_ctx.selected, g_ctx.eligible, g_ctx.omitted, g_ctx.legacy,
476 g_ctx.unpermitted, g_ctx.unsafe, g_ctx.other, (unsigned long long)records, (unsigned)g_ctx.len,
477 (unsigned)CK_CTX_PROMPT_MAX, sh, ag);
478 if (g_ctx.selected) {
479 printable(shown, sizeof shown, (const uint8_t *)g_ctx.prompt, g_ctx.len);
480 ck_printf("lifecycle: context section=\"%s\" (data, never parsed for verbs)\n", shown);
481 }
482 return 0;
483}
484
485static void generate(void)
486{
487 static struct ck_infer_reply r; /* ~1.8 KiB; static keeps it off the EL1 stack */
488 static char shown[CK_LC_REPLY_MAX + 1];
489 unsigned i;
490 if (assemble_context()) {
491 ck_lc_generate_done(&g_lc, CK_LC_GEN_FAILED, 0, 0);
492 g_lc.refused++;
493 ck_printf("lifecycle: REFUSED verb=prompt state=%s reason=\"memory refused: %s\" (nothing generated)\n",
494 ck_lc_state_name(g_lc.state), g_ctx.refused ? ck_ctx_strerror(g_ctx.refused) : "journal not opened or not verified");
495 return;
496 }
497 if (!ck_infer_resident()) {
498 ck_lc_generate_done(&g_lc, CK_LC_GEN_FAILED, 0, 0);
499 g_lc.refused++;
500 ck_printf("lifecycle: REFUSED verb=prompt state=%s reason=\"no inference unit in this image\"\n",
501 ck_lc_state_name(g_lc.state));
502 return;
503 }
504 ck_printf("lifecycle: generating prompt=\"%s\" (cancel stops it between steps)\n", g_lc.task);
505 ck_line_rx_init(&g_gen_rx);
506 int rc = ck_infer_prompt(g_ctx.prompt, g_ctx.len, cancel_poll, &r);
507 if (rc < 0) {
508 ck_lc_generate_done(&g_lc, CK_LC_GEN_FAILED, 0, 0);
509 ck_printf("lifecycle: REFUSED verb=prompt rc=%d state=%s reason=\"inference refused the prompt\"\n", rc,
510 ck_lc_state_name(g_lc.state));
511 return;
512 }
513 if (r.cancelled) {
514 ck_lc_generate_done(&g_lc, CK_LC_GEN_CANCELLED, 0, 0);
515 ck_printf("lifecycle: generation cancelled steps=%u prompt_ids=%u produced=%u us=%llu state=%s\n", r.steps,
516 r.prompt_ids, r.produced, (unsigned long long)r.us, ck_lc_state_name(g_lc.state));
517 return;
518 }
519 ck_printf("lifecycle: reply ids=");
520 for (i = 0; i < r.produced && i < CK_INFER_REPLY_IDS; i++) ck_printf("%s%u", i ? " " : "", r.ids[i]);
521 ck_printf(" tokens=%u prompt_ids=%u steps=%u us=%llu\n", r.produced, r.prompt_ids, r.steps, (unsigned long long)r.us);
522 if (r.text_len == 0) {
523 ck_lc_generate_done(&g_lc, CK_LC_GEN_FAILED, 0, 0);
524 ck_printf("lifecycle: REFUSED verb=prompt state=%s reason=\"empty reply\"\n", ck_lc_state_name(g_lc.state));
525 return;
526 }
527 if (r.text_len >= CK_INFER_REPLY_TEXT) { /* the decode stops at the buffer: the reply may be cut, never approve a cut reply */
528 ck_lc_generate_done(&g_lc, CK_LC_GEN_FAILED, 0, 0);
529 ck_printf("lifecycle: REFUSED verb=prompt state=%s reason=\"reply text reached the %u-byte approval limit (may be cut)\"\n",
530 ck_lc_state_name(g_lc.state), (unsigned)CK_INFER_REPLY_TEXT);
531 return;
532 }
533 for (i = 0; i < 32; i++) g_gen_ctx_sha[i] = g_ctx.sha[i];
534 g_gen_ctx_sel = g_ctx.selected;
535 ck_lc_generate_done(&g_lc, CK_LC_GEN_REPLY, (const char *)r.text, r.text_len);
536 printable(shown, sizeof shown, (const uint8_t *)g_lc.reply, g_lc.reply_len);
537 ck_printf("lifecycle: reply pending state=%s proposed=\"reply: %s\" (approve | deny | cancel)\n",
538 ck_lc_state_name(g_lc.state), shown);
539 if (g_lc.state == CK_LC_SERVE) propose();
540}
541
542/* recall: the newest approved object (note or reply) by Store generation,
543 * read back through the sealed Store. Nothing in memory is trusted: a cold
544 * boot answers from the disk. */
545static void recall(void)
546{
547 static uint8_t body[SS_MAX_PLAINTEXT];
548 static char shown[CK_LC_OBJ_MAX + 1];
549 ss_store *s = store_boot_store();
550 if (!s || !ck_store_service_ready()) {
551 ck_puts("lifecycle: recall REFUSED reason=\"no production Store\"\n");
552 return;
553 }
554 int best = -1;
555 uint32_t k;
556 for (k = 0; k < s->nclaims; k++) {
557 const ss_claim *c = &s->ws->claims[k];
558 if (c->c.obj.object_kind != CK_LC_OBJ_KIND && c->c.obj.object_kind != CK_LC_REPLY_KIND) continue;
559 if (best < 0 || c->c.store_generation > s->ws->claims[best].c.store_generation ||
560 (c->c.store_generation == s->ws->claims[best].c.store_generation &&
561 c->c.object_sequence > s->ws->claims[best].c.object_sequence))
562 best = (int)k;
563 }
564 if (best < 0) {
565 ck_printf("lifecycle: recall none objects=%u\n", (unsigned)s->nclaims);
566 return;
567 }
568 uint8_t sid[32];
569 size_t len = 0, i;
570 uint16_t kind = 0;
571 for (i = 0; i < 32; i++) sid[i] = s->ws->claims[best].sid[i];
572 uint64_t gen = s->ws->claims[best].c.store_generation;
573 int rc = ss_read(s, sid, body, sizeof body, &len, &kind);
574 if (rc) {
575 ck_printf("lifecycle: recall FAIL gen=%llu rc=%d\n", (unsigned long long)gen, rc);
576 return;
577 }
578 printable(shown, sizeof shown, body, len);
579 ck_printf("lifecycle: recall gen=%llu kind=%s id=%02x%02x%02x%02x bytes=%u text=\"%s\"\n", (unsigned long long)gen,
580 kind == CK_LC_REPLY_KIND ? "reply" : "note", sid[0], sid[1], sid[2], sid[3], (unsigned)len, shown);
581}
582
583static uint32_t cortex_chunks(const ss_store *s)
584{
585 uint32_t k, n = 0;
586 for (k = 0; k < s->nclaims; k++)
587 if (s->ws->claims[k].c.obj.object_kind == CK_CJ_KIND) n++;
588 return n;
589}
590
591/* Open the Cortex journal once per service lifetime. create: a missing
592 * journal is created (one sealed header transaction); else a missing journal
593 * answers 1 and opens nothing. 0: open. <0: refused (printed). */
594static int cortex_open(int create)
595{
596 ss_store *s = store_boot_store();
597 if (g_cx_open) return 0;
598 if (!s || !ck_store_service_ready()) return -1;
599 if (!create && cortex_chunks(s) == 0) return 1;
600 if (create && !ck_cont_service_writable()) return CK_SB_E_CONTINUITY;
601 if (!g_cx_heap_pa) {
602 uint64_t pa = 0;
603 int rc = ck_mm_frames_alloc(CK_CX_HEAP_PAGES, &pa);
604 if (rc) {
605 ck_printf("lifecycle: cortex REFUSED heap frames=%u rc=%d\n", (unsigned)CK_CX_HEAP_PAGES, rc);
606 return -2;
607 }
608 g_cx_heap_pa = pa;
609 }
610 ck_cx_heap_init((void *)(uintptr_t)g_cx_heap_pa, CK_CX_HEAP_BYTES);
611 ck_cj_init(&g_cj, s);
612 int rc = cx_open_with(&g_cx, &ck_cx_journal_store, &g_cj, "cortex", CK_CX_SUBJECTS, 0);
613 if (rc != CX_OK) {
614 ck_printf("lifecycle: cortex REFUSED open rc=%d chunks=%u\n", rc, cortex_chunks(s));
615 return rc;
616 }
617 g_cx_open = 1;
618 {
619 size_t used = 0, peak = 0, size = 0;
620 ck_cx_heap_stats(&used, &peak, &size);
621 ck_printf("lifecycle: cortex open records=%llu chunks=%u journal_bytes=%u store_gen=%llu heap_used_kib=%u chain=%s\n",
622 (unsigned long long)g_cx.n, g_cj.nchunks, (unsigned)g_cj.len, (unsigned long long)ss_generation(s),
623 (unsigned)(used / 1024), cx_verify_chain(&g_cx) == CX_OK ? "ok" : "FAIL");
624 }
625 return 0;
626}
627
628/* One owner record appended to the journal (remember / prefer): CX_CLAIM /
629 * CX_K_CLAIM about the owner subject, t = the record count + 1 (monotonic
630 * across boots: the count is replayed at open), generation = the Store
631 * generation its transaction commits, tag = the text bytes. One record is one
632 * sealed Store transaction: durable before the success line is printed.
633 * 0 and *id / *t, or <0 after printing the refusal. */
634static int journal_append(const char *verb, const uint64_t *pay, uint32_t nw, uint64_t tag, uint64_t *id, uint64_t *t)
635{
636 int rc = cortex_open(1);
637 uint32_t i;
638 if (rc == CK_SB_E_CONTINUITY || (rc == 0 && !ck_cont_service_writable())) {
639 g_lc.refused++; g_cx_refused++;
640 ck_printf("lifecycle: REFUSED verb=%s rc=%d state=%s reason=\"continuity read-only (degraded mount)\"\n", verb,
641 CK_SB_E_CONTINUITY, ck_lc_state_name(g_lc.state));
642 return -1;
643 }
644 if (rc) {
645 g_lc.refused++; g_cx_refused++;
646 ck_printf("lifecycle: REFUSED verb=%s rc=%d state=%s reason=\"cortex journal not open\"\n", verb, rc,
647 ck_lc_state_name(g_lc.state));
648 return -1;
649 }
650 CxHeader h;
651 for (i = 0; i < sizeof h; i++) ((uint8_t *)&h)[i] = 0;
652 h.cls = CX_CLAIM;
653 h.kind = CX_K_CLAIM;
654 h.subject = CK_CX_FACT_SUBJECT;
655 h.t = g_cx.n + 1;
656 h.generation = ss_generation(store_boot_store()) + 1; /* the generation this append commits */
657 h.tag = tag;
658 *id = 0;
659 rc = cx_append(&g_cx, &h, pay, nw, id);
660 if (rc != CX_OK) {
661 g_lc.refused++; g_cx_refused++;
662 ck_printf("lifecycle: REFUSED verb=%s rc=%d state=%s reason=\"cortex append failed, nothing written\"\n", verb, rc,
663 ck_lc_state_name(g_lc.state));
664 return -1;
665 }
666 *t = h.t;
667 return 0;
668}
669
670/* remember: a private owner fact, payload = the text packed into
671 * little-endian 64-bit words (the P06 cut 4 format: no binding, never placed
672 * in a prompt). */
673static void remember(void)
674{
675 uint64_t pay[(CK_LC_TASK_MAX + 7) / 8], id = 0, t = 0;
676 uint32_t nw = (uint32_t)((g_lc.fact_len + 7) / 8), i;
677 for (i = 0; i < nw; i++) pay[i] = 0;
678 for (i = 0; i < g_lc.fact_len; i++) pay[i / 8] |= (uint64_t)(uint8_t)g_lc.fact[i] << (8 * (i % 8));
679 if (journal_append("remember", pay, nw, g_lc.fact_len, &id, &t)) return;
680 ck_printf("lifecycle: remembered id=%llu t=%llu store_gen=%llu bytes=%u text=\"%s\"\n", (unsigned long long)id,
681 (unsigned long long)t, (unsigned long long)ss_generation(store_boot_store()), (unsigned)g_lc.fact_len,
682 g_lc.fact);
683}
684
685/* prefer (N3): a v1 memory record (core/context.h) of type preference, bound
686 * to the provisioned agent id, with the context permission recorded in it:
687 * the owner's explicit grant that this text may condition generation. */
688static void prefer(void)
689{
690 uint64_t pay[CK_MEM_MAX_WORDS], id = 0, t = 0;
691 const uint8_t *agent = ck_cont_service_agent();
692 char ag[17];
693 uint32_t nw;
694 if (!agent) {
695 g_lc.refused++; g_cx_refused++;
696 ck_printf("lifecycle: REFUSED verb=prefer state=%s reason=\"no provisioned subject to bind the preference to\"\n",
697 ck_lc_state_name(g_lc.state));
698 return;
699 }
700 nw = ck_mem_encode(pay, CK_MEM_TYPE_PREF, CK_MEM_PERM_CONTEXT, agent, g_lc.fact, g_lc.fact_len);
701 if (!nw) {
702 g_lc.refused++; g_cx_refused++;
703 ck_printf("lifecycle: REFUSED verb=prefer state=%s reason=\"preference text out of bounds\"\n",
704 ck_lc_state_name(g_lc.state));
705 return;
706 }
707 if (journal_append("prefer", pay, nw, g_lc.fact_len, &id, &t)) return;
708 hex8(ag, agent);
709 ck_printf("lifecycle: preferred id=%llu t=%llu store_gen=%llu bytes=%u permitted=context agent=%s safe=%s text=\"%s\"\n",
710 (unsigned long long)id, (unsigned long long)t, (unsigned long long)ss_generation(store_boot_store()),
711 (unsigned)g_lc.fact_len, ag, ck_ctx_text_safe((const uint8_t *)g_lc.fact, g_lc.fact_len) ? "yes" : "no",
712 g_lc.fact);
713}
714
715/* facts: the newest CK_CX_FACTS_SHOWN owner records, oldest first, each read
716 * back through cx_recall_id (digest re-checked) from the journal replayed at
717 * open; then the whole chain is verified again. v1 memory records (prefer)
718 * are listed as `preference` lines with their binding and permission. */
719static void facts(void)
720{
721 static CxRecord r;
722 static char shown[CK_LC_TASK_MAX + 1];
723 uint64_t id, first;
724 unsigned n = 0;
725 int rc = cortex_open(0);
726 if (rc == 1) {
727 ck_puts("lifecycle: facts none cortex=none records=0\n");
728 return;
729 }
730 if (rc) {
731 g_lc.refused++; g_cx_refused++;
732 ck_printf("lifecycle: REFUSED verb=facts rc=%d state=%s reason=\"cortex journal not open\"\n", rc,
733 ck_lc_state_name(g_lc.state));
734 return;
735 }
736 first = g_cx.n > CK_CX_FACTS_SHOWN ? g_cx.n - CK_CX_FACTS_SHOWN + 1 : 1;
737 for (id = first; id <= g_cx.n; id++) {
738 uint8_t text[CK_LC_TASK_MAX];
739 size_t len, i;
740 ck_mem_v1 m;
741 if (cx_recall_id(&g_cx, id, &r) != CX_OK || !r.verified) {
742 ck_printf("lifecycle: fact id=%llu DIGEST_FAIL\n", (unsigned long long)id);
743 continue;
744 }
745 if (r.hdr.cls != CX_CLAIM || r.hdr.kind != CX_K_CLAIM || r.hdr.subject != CK_CX_FACT_SUBJECT) continue;
746 enum ck_mem_form f = ck_mem_parse((const uint8_t *)r.payload, (size_t)r.hdr.n * 8, r.hdr.tag, &m);
747 if (f == CK_MEM_V1) {
748 char ag[17];
749 hex8(ag, m.binding);
750 printable(shown, sizeof shown, m.text, m.text_len);
751 ck_printf("lifecycle: %s id=%llu t=%llu store_gen=%llu agent=%s permitted=%s text=\"%s\"\n",
752 m.type == CK_MEM_TYPE_PREF ? "preference" : "fact", (unsigned long long)id,
753 (unsigned long long)r.hdr.t, (unsigned long long)r.hdr.generation, ag,
754 (m.perm & CK_MEM_PERM_CONTEXT) ? "context" : "no", shown);
755 n++;
756 continue;
757 }
758 if (f == CK_MEM_MALFORMED) {
759 ck_printf("lifecycle: fact id=%llu MALFORMED\n", (unsigned long long)id);
760 continue;
761 }
762 len = (size_t)r.hdr.tag;
763 if (len > sizeof text || len > (size_t)r.hdr.n * 8) len = 0; /* malformed tag: shown empty, still counted */
764 for (i = 0; i < len; i++) text[i] = (uint8_t)(r.payload[i / 8] >> (8 * (i % 8)));
765 printable(shown, sizeof shown, text, len);
766 ck_printf("lifecycle: fact id=%llu t=%llu store_gen=%llu text=\"%s\"\n", (unsigned long long)id,
767 (unsigned long long)r.hdr.t, (unsigned long long)r.hdr.generation, shown);
768 n++;
769 }
770 ck_printf("lifecycle: facts records=%llu shown=%u journal_bytes=%u chain=%s\n", (unsigned long long)g_cx.n, n,
771 (unsigned)g_cj.len, cx_verify_chain(&g_cx) == CX_OK ? "ok" : "FAIL");
772}
773
774/* Stop order step 0: close the journal (nothing to flush: every append was
775 * already durable) and return its heap frames. */
776static void cortex_close(void)
777{
778 if (g_cx_open) {
779 size_t used = 0, peak = 0, size = 0;
780 ck_cx_heap_stats(&used, &peak, &size);
781 ck_printf("lifecycle: cortex closed records=%llu appends=%u reads=%u refused=%u heap_peak_kib=%u\n",
782 (unsigned long long)g_cx.n, g_cj.appends, g_cj.reads, g_cx_refused, (unsigned)(peak / 1024));
783 cx_close(&g_cx);
784 g_cx_open = 0;
785 }
786 if (g_cx_heap_pa) {
787 ck_mm_frames_free(g_cx_heap_pa, CK_CX_HEAP_PAGES);
788 g_cx_heap_pa = 0;
789 }
790}
791
792static void handle_line(const char *line, size_t len)
793{
794 const char *arg;
795 size_t arg_len;
796 enum ck_lc_verb v = ck_lc_decode(line, len, &arg, &arg_len);
797 enum ck_lc_result r = ck_lc_apply(&g_lc, v, arg, arg_len);
798 switch (r) {
799 case CK_LC_R_INVALID:
800 ck_printf("lifecycle: REFUSED verb=%s reason=\"%s\"\n", ck_lc_verb_name(v), g_lc.reason);
801 return;
802 case CK_LC_R_REFUSED:
803 ck_printf("lifecycle: REFUSED verb=%s state=%s reason=\"%s\"\n", ck_lc_verb_name(v),
804 ck_lc_state_name(g_lc.state), g_lc.reason);
805 return;
806 case CK_LC_R_UNLOCK: {
807 int opened = ck_store_service_unlock(arg, arg_len);
808 ck_lc_unlock_done(&g_lc, opened);
809 if (opened) ck_printf("lifecycle: unlock ok state=%s\n", ck_lc_state_name(g_lc.state));
810 if (opened) ck_slot_service_health(slot_healthy());
811 else ck_printf("lifecycle: REFUSED verb=unlock state=%s reason=\"%s\"\n", ck_lc_state_name(g_lc.state), g_lc.reason);
812 return;
813 }
814 case CK_LC_R_ROTATE: {
815 int ok = ck_store_service_rotate(arg, arg_len);
816 ck_lc_rotate_done(&g_lc, ok);
817 if (ok) ck_printf("lifecycle: rotate ok state=%s\n", ck_lc_state_name(g_lc.state));
818 else ck_printf("lifecycle: REFUSED verb=rotate state=%s reason=\"%s\"\n", ck_lc_state_name(g_lc.state), g_lc.reason);
819 return;
820 }
821 case CK_LC_R_COMMIT: approve(); return;
822 case CK_LC_R_STOP:
823 ck_printf("lifecycle: shutdown accepted state=%s\n", ck_lc_state_name(g_lc.state));
824 proposal_dropped("shutdown");
825 return;
826 case CK_LC_R_GENERATE: generate(); return;
827 case CK_LC_R_RECALL: recall(); return;
828 case CK_LC_R_REMEMBER: remember(); return;
829 case CK_LC_R_FACTS: facts(); return;
830 case CK_LC_R_UPDATE: ck_slot_service_update(arg, arg_len); return; /* P11 cut 3, svc/slot_service.c */
831 case CK_LC_R_PREFER: prefer(); return;
832 case CK_LC_R_OK: break;
833 }
834 switch (v) {
835 case CK_LC_V_HELP: help(); break;
836 case CK_LC_V_STATUS: status(); break;
837 case CK_LC_V_EVIDENCE: evidence(); break;
838 case CK_LC_V_TASK:
839 ck_printf("lifecycle: task pending state=%s proposed=\"note: %s\" (approve | deny | cancel)\n",
840 ck_lc_state_name(g_lc.state), g_lc.task);
841 propose();
842 break;
843 case CK_LC_V_DENY: ck_printf("lifecycle: denied state=%s\n", ck_lc_state_name(g_lc.state)); proposal_dropped("deny"); break;
844 case CK_LC_V_CANCEL: ck_printf("lifecycle: cancelled state=%s\n", ck_lc_state_name(g_lc.state)); proposal_dropped("cancel"); break;
845 default: break;
846 }
847}
848
849#ifndef CK_PI5_LIFECYCLE
850/* 1 when the line so far is "unlock" or "rotate" followed by its argument:
851 * those bytes are recovery secrets and are echoed as '*' so the serial log
852 * never carries them. */
853static int after_verb(const char *buf, size_t len, const char *verb)
854{
855 size_t i = 0, j;
856 while (i < len && buf[i] == ' ') i++;
857 for (j = 0; verb[j]; j++)
858 if (i + j >= len || buf[i + j] != verb[j]) return 0;
859 return i + j < len && buf[i + j] == ' ';
860}
861static int in_secret(const char *buf, size_t len)
862{
863 return after_verb(buf, len, "unlock") || after_verb(buf, len, "rotate");
864}
865#endif /* !CK_PI5_LIFECYCLE */
866
867/* Bounded serial line editor over the POLLED console receive (no
868 * interrupts): the rules are core/line_rx.c (printable bytes collected,
869 * Backspace edits, CR or LF ends the line, a line past CK_LC_LINE_MAX or one
870 * with a lost or damaged byte is refused whole at its Enter). This function
871 * only echoes. At most CK_LINE_RX_BURST bytes per call. Returns 1 when
872 * g_rx.buf[0..g_rx.len) is a complete line. */
873static struct ck_line_rx g_rx;
874#ifndef CK_PI5_LIFECYCLE
875static int rx_line(void)
876{
877 for (unsigned n = 0; n < CK_LINE_RX_BURST; n++) {
878 int b = ck_console_rx_poll();
879 if (b == CK_LINE_RX_EMPTY) return 0;
880 switch (ck_line_rx_feed(&g_rx, b)) {
881 case CK_LINE_ECHO: {
882 char e[2] = { in_secret(g_rx.buf, g_rx.len - 1) ? '*' : g_rx.buf[g_rx.len - 1], 0 };
883 ck_puts(e);
884 break;
885 }
886 case CK_LINE_ERASE: ck_puts("\b \b"); break;
887 case CK_LINE_DONE: ck_puts("\n"); return 1;
888 case CK_LINE_OVERLONG:
889 g_overlong++;
890 ck_puts("\n");
891 ck_printf("lifecycle: REFUSED verb=invalid reason=\"line longer than %u bytes\"\n", (unsigned)CK_LC_LINE_MAX);
892 return 0;
893 case CK_LINE_DAMAGED:
894 ck_puts("\n");
895 ck_puts("lifecycle: REFUSED verb=invalid reason=\"receive error in the line (overrun, parity, framing or break): type it again\"\n");
896 return 0;
897 default: break;
898 }
899 }
900 return 0;
901}
902#endif /* !CK_PI5_LIFECYCLE */
903
904#ifdef CK_PI5_LIFECYCLE
905/* PI5-7 cut 2 (QUALIFICATION ONLY): the operator input is the card command script \EFI\AIENOS\AGENT.CMD
906 * (core/agent_cmd.h), already parsed and bounded by the UEFI stub. Each line goes through the same
907 * handle_line the console path uses, so every reply is the one an operator would see; the line is echoed
908 * after "> " first. The parser lets no secret-carrying or control verb through (unlock, rotate, update,
909 * shutdown), and the stop order follows the last line (or an absent or refused script) in any case. */
910static void run_script(void)
911{
912 const struct ck_agent_cmd_boot *b = &ck_agent_cmd_boot;
913 uint32_t i;
914 ck_printf("lifecycle: ready state=%s store=%s (operator input: card command script AGENT.CMD, QUALIFICATION ONLY, no serial)\n",
915 ck_lc_state_name(g_lc.state), ck_store_service_ready() ? "open" : "locked");
916 if (b->state != CK_AGENT_CMD_FOUND) {
917 ck_printf("lifecycle: no command script (%s): nothing to run\n",
918 b->state == CK_AGENT_CMD_REFUSED ? "refused" : "absent");
919 } else {
920 for (i = 0; i < b->cmd.nlines && g_lc.state != CK_LC_QUIESCE; i++) {
921 ck_printf("> %s\n", b->cmd.line[i]);
922 handle_line(b->cmd.line[i], b->cmd.len[i]);
923 }
924 ck_printf("lifecycle: command script done lines=%u\n", (unsigned)b->cmd.nlines);
925 }
926 if (g_lc.state != CK_LC_QUIESCE) handle_line("shutdown", 8);
927}
928#endif
929
930/* Returns 0 after an orderly stop (kmain then prints the final report and
931 * resets). Never returns while serving. */
932int ck_lifecycle_run(void)
933{
934#ifndef CK_PI5_LIFECYCLE
935 uint32_t cr = 0;
936#endif
937 ck_lc_init(&g_lc);
938 ck_line_rx_init(&g_rx);
939 ck_line_rx_init(&g_gen_rx);
940#ifdef CK_SERVICE_TEST_KEYS
941 ck_puts("lifecycle: TEST-ONLY service image (CK_SERVICE_TEST_KEYS=1: TEST Store keys; QEMU only, never a production boot)\n");
942#endif
943 ck_lc_start(&g_lc, ck_store_service_ready());
944 ck_slot_service_start(slot_healthy());
945#ifdef CK_PI5_LIFECYCLE
946 const char *uname = "none (card command script)";
947 run_script();
948#else
949 /* Operator input is the console UART the boot stub chose from the ACPI
950 * SPCR (PL011/SBSA or 16550), POLLED: no interrupt is ever enabled. */
951 const char *uname = ck_console_uart_name();
952 if (uname[0] == 'n') { /* "none": no console UART of a kind this kernel drives */
953 ck_puts("lifecycle: REFUSED console input unsupported on this platform (no PL011/SBSA or 16550 console UART in the ACPI SPCR): stop order\n");
954 ck_lc_apply(&g_lc, CK_LC_V_SHUTDOWN, "", 0);
955 } else if (!ck_console_rx_ready(&cr)) {
956 ck_printf("lifecycle: REFUSED console input not ready (uart=%s base=0x%llx regs=0x%x): stop order\n", uname,
957 (unsigned long long)ck_console_uart_base(), cr);
958 ck_lc_apply(&g_lc, CK_LC_V_SHUTDOWN, "", 0);
959 } else {
960 ck_printf("lifecycle: ready state=%s store=%s (operator input: serial %s at 0x%llx, polled)\n",
961 ck_lc_state_name(g_lc.state), ck_store_service_ready() ? "open" : "locked", uname,
962 (unsigned long long)ck_console_uart_base());
963 ck_puts("> ");
964 while (g_lc.state != CK_LC_QUIESCE) {
965 if (rx_line()) {
966 handle_line(g_rx.buf, g_rx.len);
967 if (g_lc.state != CK_LC_QUIESCE) ck_puts("> ");
968 } else {
969 __asm__ volatile("yield");
970 }
971 }
972 }
973#endif
974 /* Stop order: Cortex journal closed (frames returned), inference session
975 * closed (frames returned), Store closed, then NVMe released, then the
976 * caller resets. */
977 ck_slot_service_stop();
978 cortex_close();
979 ck_infer_resident_close();
980 int closed = ck_store_service_close();
981 ck_dev_nvme_release();
982 ck_lc_stopped(&g_lc);
983 ck_printf("lifecycle: stop order store=%s nvme=released state=%s requests=%u\n", closed ? "closed" : "was-locked",
984 ck_lc_state_name(g_lc.state), g_lc.requests);
985 ck_printf("lifecycle: input uart=%s rx_errors=%u overruns=%u damaged_lines=%u overlong=%u dropped=%u\n", uname,
986 ck_console_rx_errors(), ck_console_rx_overruns(), g_rx.damaged_lines + g_gen_rx.damaged_lines,
987 g_rx.overlong + g_gen_rx.overlong, g_rx.dropped + g_gen_rx.dropped);
988 return 0;
989}