#include "resolve.h"
#include "platform.h"
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static const char *const kind_names[AK_COUNT] = {
"skills", "agents", "commands", "instructions", "file", "slot",
};
// The harness key that names the folder for each kind that goes in a harness.
static const char *const folder_keys[AK_INSTRUCTIONS + 1] = {
"skills.user", "agents.user", "commands.user", "instructions.user",
};
const char *asset_kind_name(AssetKind kind)
{
ensure(kind < AK_COUNT);
return kind_names[kind];
}
bool glob_match(const char *pattern, const char *name)
{
const char *star = nullptr;
const char *resume = nullptr;
while (*name != '\0') {
if (*pattern == '*') {
star = pattern++;
resume = name;
} else if (*pattern == *name) {
pattern++;
name++;
} else if (star != nullptr) {
pattern = star + 1;
name = ++resume;
} else {
return false;
}
}
while (*pattern == '*') pattern++;
return *pattern == '\0';
}
typedef struct {
const Conf *c;
const Assets *assets;
const char *home;
const char *suit_home;
const char *store;
Plan *p;
ResolveError *e;
} Ctx;
__attribute__((format(printf, 2, 3)))
static bool fail(Ctx *x, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vsnprintf(x->e->msg, sizeof x->e->msg, fmt, ap);
va_end(ap);
return false;
}
static const char EMPTY[] = "";
// Copy A, B and C joined into the plan's text. If it does not fit, the plan is
// marked overflowed (add_placement says so) and the result is empty.
static const char *join(Plan *p, const char *a, const char *b, const char *c)
{
size_t la = strlen(a), lb = strlen(b), lc = strlen(c);
if (p->used + la + lb + lc + 1 > sizeof p->text) {
p->overflow = true;
return EMPTY;
}
char *out = p->text + p->used;
memcpy(out, a, la);
memcpy(out + la, b, lb);
memcpy(out + la + lb, c, lc + 1);
p->used += la + lb + lc + 1;
return out;
}
// "~" and "~/..." mean the home folder.
static const char *expand(Ctx *x, const char *path)
{
bool tilde = path[0] == '~' && (path[1] == '/' || path[1] == '\0');
return tilde ? join(x->p, x->home, path + 1, "") : join(x->p, path, "", "");
}
static bool plan_full(Ctx *x)
{
return fail(x, "the plan is larger than %zu bytes of paths", PLAN_TEXT_MAX);
}
static bool add_placement(Ctx *x, const char *dest, const char *src, const char *harness,
AssetKind kind)
{
Plan *p = x->p;
if (p->overflow) return plan_full(x);
if (p->n == PLACE_MAX) return fail(x, "more than %u placements", PLACE_MAX);
if (dest[0] != '/')
return fail(x, "%s is not an absolute path (start it with ~ or /)", dest);
if (strpbrk(dest, " \t") != nullptr || strpbrk(src, " \t") != nullptr)
return fail(x, "a space in %s or %s: paths cannot have one", dest, src);
p->p[p->n++] = (Placement){dest, src, harness, kind};
return true;
}
static bool add_skip(Ctx *x, const char *text)
{
Plan *p = x->p;
if (p->nskips == SKIP_MAX) return fail(x, "more than %u skipped lines", SKIP_MAX);
snprintf(p->skips[p->nskips++], SKIP_LEN, "%s", text);
return true;
}
static const Entry *find_entry(const Conf *c, const Section *s, const char *key)
{
for (uint32_t i = 0; i < s->count; i++)
if (strcmp(c->entries[s->first + i].key, key) == 0) return &c->entries[s->first + i];
return nullptr;
}
static const Section *find_outfit(const Conf *c, const char *name, size_t len)
{
for (uint32_t i = 0;; i++) {
ensure(i < c->nsections); // conf_load checked that every name given is an outfit
const Section *s = &c->sections[i];
if (s->kind == KIND_OUTFIT && strncmp(s->arg[0], name, len) == 0 && s->arg[0][len] == '\0')
return s;
}
}
// ---- which outfits ----------------------------------------------------------
typedef struct {
const Section *list[CONF_OUTFIT_MAX];
uint32_t n;
} Outfits;
static void queue_outfits(Ctx *x, Outfits *q, const char *names)
{
const char *w;
size_t len;
while (conf_list_next(&names, &w, &len)) {
const Section *s = find_outfit(x->c, w, len);
bool seen = false;
for (uint32_t i = 0; i < q->n; i++) seen |= q->list[i] == s;
if (!seen) q->list[q->n++] = s;
}
}
// The outfits the User scope wears, each once: first the ones the wear sections
// name in order, then what they include, and so on. A wear with a machine
// limit is not applied yet.
static void collect_outfits(Ctx *x, Outfits *q)
{
q->n = 0;
for (uint32_t i = 0; i < x->c->nsections; i++) {
const Section *s = &x->c->sections[i];
if (s->kind != KIND_WEAR || strcmp(s->arg[0], "user") != 0) continue;
if (s->arg[2][0] != '\0') {
char text[SKIP_LEN];
snprintf(text, sizeof text, "skipped wear user machine=%s (machine limits are not applied yet)",
s->arg[2]);
[[maybe_unused]] bool added = add_skip(x, text);
ensure(added); // there are never as many wears as skipped lines
continue;
}
const Entry *outfits = find_entry(x->c, s, "outfits");
if (outfits != nullptr) queue_outfits(x, q, outfits->val);
}
for (uint32_t head = 0; head < q->n; head++) {
const Entry *inc = find_entry(x->c, q->list[head], "include");
if (inc != nullptr) queue_outfits(x, q, inc->val);
}
}
// ---- placing one asset ------------------------------------------------------
static const char *const kind_dirs[AK_COMMAND + 1] = {"/skills/", "/agents/", "/commands/"};
static bool place_one(Ctx *x, const Section *harness, AssetKind kind, const char *file,
const char *name)
{
const Entry *folder = find_entry(x->c, harness, folder_keys[kind]);
if (folder == nullptr) {
char text[SKIP_LEN];
snprintf(text, sizeof text, "skipped %s %s %s (no folder)", harness->arg[0],
kind_names[kind], name);
return add_skip(x, text);
}
const char *base = expand(x, folder->val);
// Instructions are one file the harness names; the rest go in its folder.
bool instructions = kind == AK_INSTRUCTIONS;
const char *dest = join(x->p, base, instructions ? "" : "/", instructions ? "" : file);
const char *src = instructions ? join(x->p, x->store, "/", file)
: join(x->p, x->store, kind_dirs[kind], file);
return add_placement(x, dest, src, harness->arg[0], kind);
}
static bool eligible(const Section *harness, const char *only)
{
return only == nullptr || strcmp(harness->arg[0], only) == 0;
}
// Match each word of LIST against the names the store has, place every match
// for every harness the outfit is for.
static bool place_names(Ctx *x, const Section *outfit, const char *only, AssetKind kind,
const char *list)
{
const NameList *have = &x->assets->list[kind];
const char *w;
size_t len;
while (conf_list_next(&list, &w, &len)) {
char pattern[CONF_NAME_MAX + 1];
memcpy(pattern, w, len);
pattern[len] = '\0';
uint32_t matched = 0;
for (uint32_t i = 0; i < have->n; i++) {
if (!glob_match(pattern, have->name[i])) continue;
matched++;
for (uint32_t h = 0; h < x->c->nsections; h++) {
const Section *hs = &x->c->sections[h];
if (hs->kind != KIND_HARNESS || !eligible(hs, only)) continue;
if (!place_one(x, hs, kind, have->file[i], have->name[i])) return false;
}
}
if (matched == 0)
return fail(x, "outfit %s: %s '%s' matches nothing in the store", outfit->arg[0],
kind_names[kind], pattern);
}
return true;
}
static bool place_instructions(Ctx *x, const char *only, const char *path)
{
for (uint32_t h = 0; h < x->c->nsections; h++) {
const Section *hs = &x->c->sections[h];
if (hs->kind != KIND_HARNESS || !eligible(hs, only)) continue;
if (!place_one(x, hs, AK_INSTRUCTIONS, path, path)) return false;
}
return true;
}
// "file DEST = SRC" and "slot NAME = SRC": one placement each, whatever the
// harnesses.
static bool place_free(Ctx *x, AssetKind kind, const char *param, const char *src)
{
const char *dest = kind == AK_SLOT ? join(x->p, x->suit_home, "/slots/", param) : expand(x, param);
const char *from = join(x->p, x->store, "/", src);
return add_placement(x, dest, from, "-", kind);
}
static bool place_outfit(Ctx *x, const Section *outfit)
{
const Entry *only_entry = find_entry(x->c, outfit, "only");
const char *only = only_entry != nullptr ? only_entry->val : nullptr;
for (uint32_t i = 0; i < outfit->count; i++) {
const Entry *en = &x->c->entries[outfit->first + i];
bool ok = true;
for (int k = AK_SKILL; k <= AK_COMMAND; k++)
if (strcmp(en->key, kind_names[k]) == 0) ok = place_names(x, outfit, only, (AssetKind)k, en->val);
if (strcmp(en->key, "instructions") == 0) ok = place_instructions(x, only, en->val);
if (strncmp(en->key, "file ", 5) == 0) ok = place_free(x, AK_FILE, en->key + 5, en->val);
if (strncmp(en->key, "slot ", 5) == 0) ok = place_free(x, AK_SLOT, en->key + 5, en->val);
if (!ok) return false;
}
return true;
}
// ---- order and conflicts ----------------------------------------------------
static int cmp_placement(const void *pa, const void *pb)
{
const Placement *a = pa;
const Placement *b = pb;
int r = strcmp(a->dest, b->dest);
return r != 0 ? r : strcmp(a->src, b->src);
}
// Two assets for one destination: the same source is one placement, another
// source is an error that names both.
static bool settle(Ctx *x)
{
Plan *p = x->p;
qsort(p->p, p->n, sizeof p->p[0], cmp_placement);
uint32_t out = 0;
for (uint32_t i = 0; i < p->n; i++) {
bool same_dest = out > 0 && strcmp(p->p[out - 1].dest, p->p[i].dest) == 0;
if (same_dest && strcmp(p->p[out - 1].src, p->p[i].src) != 0)
return fail(x, "two assets want %s: %s and %s", p->p[i].dest, p->p[out - 1].src,
p->p[i].src);
if (!same_dest) p->p[out++] = p->p[i];
}
p->n = out;
return true;
}
bool resolve(const Conf *conf, const Assets *assets, const char *home, const char *suit_home,
const char *store, Plan *p, ResolveError *err)
{
Ctx x = {conf, assets, home, suit_home, store, p, err};
p->n = 0;
p->nskips = 0;
p->used = 0;
p->overflow = false;
static Outfits outfits;
collect_outfits(&x, &outfits);
for (uint32_t i = 0; i < outfits.n; i++)
if (!place_outfit(&x, outfits.list[i])) return false;
return settle(&x);
}