/* harakiri_quantum.h — Quantum micro agents
 *
 * The macro tier (Vera, Mira, Merlin, Gaven, PainTr) thinks.
 * The quantum tier does. Micro agents are 32-byte ephemeral workers
 * spawned for a single task — watch a PID, hold a notification,
 * meter a resource — then dissolved back into the pool.
 *
 * A micro agent is always bound to a parent (the macro agent that
 * spawned it) and a target (what it watches/acts on). No independent
 * cognition — they're transmitters, not thinkers.
 */
#ifndef _HARAKIRI_QUANTUM_H
#define _HARAKIRI_QUANTUM_H

#include <linux/types.h>
#include <harakiri/harakiri_agent.h>

/* Micro agent task types */
enum hk_qtask {
	HK_QWATCH_PID = 0,	/* monitor a PID's activity */
	HK_QHOLD_NOTE,		/* hold a notification at the gate */
	HK_QMETER_RES,		/* meter a resource (cpu/mem/io) */
	HK_QBOOST_PID,		/* apply a one-shot priority boost */
	HK_NQTASKS
};

#define HK_QPOOL_SIZE	64	/* micro agents per hive */

/* One quantum micro agent. 32 bytes — half a cache line, fits two per. */
struct hk_quantum {
	u32	id;		/* unique micro id */
	u16	parent;		/* parent macro agent id */
	u8	task;		/* enum hk_qtask */
	u8	state;		/* 0=free, 1=active, 2=done */
	u32	target;		/* pid, notification id, resource id */
	u32	data;		/* task-specific payload */
	u32	eta_x1000;	/* confidence at spawn */
	u32	born_tick;	/* hive tick when spawned */
	u8	_pad[8];
} __attribute__((packed));

_Static_assert(sizeof(struct hk_quantum) == 32, "hk_quantum must be 32 bytes");

struct hk_qpool {
	struct hk_quantum	agents[HK_QPOOL_SIZE];
	u32			next_id;
	u32			active;	/* count of state==1 */
};

/* Spawn a micro agent. Returns the micro id, or 0 if the pool is full. */
static inline u32 hk_qspawn(struct hk_qpool *q, u16 parent, u8 task,
			   u32 target, u32 data, u32 eta_x1000,
			   u32 tick)
{
	int i;
	for (i = 0; i < HK_QPOOL_SIZE; i++) {
		if (q->agents[i].state == 0) {
			struct hk_quantum *m = &q->agents[i];
			m->id = q->next_id++;
			if (q->next_id == 0)
				q->next_id = 1; /* 0 = invalid */
			m->parent = parent;
			m->task = task;
			m->state = 1;
			m->target = target;
			m->data = data;
			m->eta_x1000 = eta_x1000;
			m->born_tick = tick;
			q->active++;
			return m->id;
		}
	}
	return 0;
}

/* Dissolve a micro agent back into the pool. */
static inline void hk_qdissolve(struct hk_qpool *q, u32 id)
{
	int i;
	for (i = 0; i < HK_QPOOL_SIZE; i++) {
		if (q->agents[i].id == id && q->agents[i].state == 1) {
			q->agents[i].state = 0;
			q->active--;
			return;
		}
	}
}

/* Find a micro agent by id. NULL if not active. */
static inline struct hk_quantum *hk_qfind(struct hk_qpool *q, u32 id)
{
	int i;
	for (i = 0; i < HK_QPOOL_SIZE; i++) {
		if (q->agents[i].id == id && q->agents[i].state == 1)
			return &q->agents[i];
	}
	return NULL;
}

#endif /* _HARAKIRI_QUANTUM_H */
